repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.count_expected
def count_expected count = @expected.inject(0) do |n, exp| case exp.first when :list # if the list is greedy, all arguments have to be absorbed return [n, true] unless exp[3] n + exp[3] else n + 1 end end [count, false] end
ruby
def count_expected count = @expected.inject(0) do |n, exp| case exp.first when :list # if the list is greedy, all arguments have to be absorbed return [n, true] unless exp[3] n + exp[3] else n + 1 end end [count, false] end
[ "def", "count_expected", "count", "=", "@expected", ".", "inject", "(", "0", ")", "do", "|", "n", ",", "exp", "|", "case", "exp", ".", "first", "when", ":list", "return", "[", "n", ",", "true", "]", "unless", "exp", "[", "3", "]", "n", "+", "exp", "[", "3", "]", "else", "n", "+", "1", "end", "end", "[", "count", ",", "false", "]", "end" ]
Count the number of arguments expected to be supplied. @raise [Integer, nil] the number of expected arguments, or nil if a list of indeterminate size is specified @api private
[ "Count", "the", "number", "of", "arguments", "expected", "to", "be", "supplied", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L87-L101
train
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.parse_list!
def parse_list!(type, sym, count) args = if count @args.shift count else @args end @results[sym] = Parser.parse_list type, args end
ruby
def parse_list!(type, sym, count) args = if count @args.shift count else @args end @results[sym] = Parser.parse_list type, args end
[ "def", "parse_list!", "(", "type", ",", "sym", ",", "count", ")", "args", "=", "if", "count", "@args", ".", "shift", "count", "else", "@args", "end", "@results", "[", "sym", "]", "=", "Parser", ".", "parse_list", "type", ",", "args", "end" ]
Parse a one or more expected arguments of a given type and add them to the results. @param type [Symbol] the type of the individual elements of the list @param sym [Symbol] the key to store the results under in {results} @param count [Integer, nil] the size of the list, or nil if the list absorbs all following arguments @api private
[ "Parse", "a", "one", "or", "more", "expected", "arguments", "of", "a", "given", "type", "and", "add", "them", "to", "the", "results", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L110-L118
train
toshipon/ean3
lib/ean3/hotels.rb
Ean3.Hotels.getReservation
def getReservation response = conncetion.post do |req| req.url "res", options end return_error_or_body(response, response.body) end
ruby
def getReservation response = conncetion.post do |req| req.url "res", options end return_error_or_body(response, response.body) end
[ "def", "getReservation", "response", "=", "conncetion", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"res\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ")", "end" ]
Book a Reservation
[ "Book", "a", "Reservation" ]
d1aefbaf9b3ddf3e9da694e832314cd9ab615868
https://github.com/toshipon/ean3/blob/d1aefbaf9b3ddf3e9da694e832314cd9ab615868/lib/ean3/hotels.rb#L79-L84
train
toshipon/ean3
lib/ean3/hotels.rb
Ean3.Hotels.getAlternateProperties
def getAlternateProperties response = conncetion.get do |req| req.url "altProps", options end return_error_or_body(response, response.body) end
ruby
def getAlternateProperties response = conncetion.get do |req| req.url "altProps", options end return_error_or_body(response, response.body) end
[ "def", "getAlternateProperties", "response", "=", "conncetion", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"altProps\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ")", "end" ]
Request Alternate Properties
[ "Request", "Alternate", "Properties" ]
d1aefbaf9b3ddf3e9da694e832314cd9ab615868
https://github.com/toshipon/ean3/blob/d1aefbaf9b3ddf3e9da694e832314cd9ab615868/lib/ean3/hotels.rb#L89-L94
train
starpeak/gricer
app/controllers/gricer/dashboard_controller.rb
Gricer.DashboardController.index
def index @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) end
ruby
def index @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) end
[ "def", "index", "@sessions", "=", "Gricer", ".", "config", ".", "session_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "@requests", "=", "Gricer", ".", "config", ".", "request_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "end" ]
This action renders the frame for the statistics tool
[ "This", "action", "renders", "the", "frame", "for", "the", "statistics", "tool" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/dashboard_controller.rb#L5-L8
train
starpeak/gricer
app/controllers/gricer/dashboard_controller.rb
Gricer.DashboardController.overview
def overview @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) render partial: 'overview', formats: [:html], locals: {sessions: @sessions, requests: @requests} end
ruby
def overview @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) render partial: 'overview', formats: [:html], locals: {sessions: @sessions, requests: @requests} end
[ "def", "overview", "@sessions", "=", "Gricer", ".", "config", ".", "session_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "@requests", "=", "Gricer", ".", "config", ".", "request_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "render", "partial", ":", "'overview'", ",", "formats", ":", "[", ":html", "]", ",", "locals", ":", "{", "sessions", ":", "@sessions", ",", "requests", ":", "@requests", "}", "end" ]
This action renderes the overview of some data in the statistics tool
[ "This", "action", "renderes", "the", "overview", "of", "some", "data", "in", "the", "statistics", "tool" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/dashboard_controller.rb#L11-L16
train
redding/enumeration
lib/enumeration/collection.rb
Enumeration.Collection.[]
def [](key) if self.map? && @data.has_key?(key) @data[key] elsif (self.map? && @data.has_value?(key)) || (self.list? && @data.include?(key)) key else nil end end
ruby
def [](key) if self.map? && @data.has_key?(key) @data[key] elsif (self.map? && @data.has_value?(key)) || (self.list? && @data.include?(key)) key else nil end end
[ "def", "[]", "(", "key", ")", "if", "self", ".", "map?", "&&", "@data", ".", "has_key?", "(", "key", ")", "@data", "[", "key", "]", "elsif", "(", "self", ".", "map?", "&&", "@data", ".", "has_value?", "(", "key", ")", ")", "||", "(", "self", ".", "list?", "&&", "@data", ".", "include?", "(", "key", ")", ")", "key", "else", "nil", "end", "end" ]
lookup collection value by a key
[ "lookup", "collection", "value", "by", "a", "key" ]
816d6993c3a05e538a45f65529ccef6dbc9c6bf1
https://github.com/redding/enumeration/blob/816d6993c3a05e538a45f65529ccef6dbc9c6bf1/lib/enumeration/collection.rb#L15-L24
train
redding/enumeration
lib/enumeration/collection.rb
Enumeration.Collection.key
def key(value) if self.map? && @data.has_value?(value) @data.invert[value] elsif (self.map? && @data.has_key?(value)) || (self.list? && @data.include?(value)) value else nil end end
ruby
def key(value) if self.map? && @data.has_value?(value) @data.invert[value] elsif (self.map? && @data.has_key?(value)) || (self.list? && @data.include?(value)) value else nil end end
[ "def", "key", "(", "value", ")", "if", "self", ".", "map?", "&&", "@data", ".", "has_value?", "(", "value", ")", "@data", ".", "invert", "[", "value", "]", "elsif", "(", "self", ".", "map?", "&&", "@data", ".", "has_key?", "(", "value", ")", ")", "||", "(", "self", ".", "list?", "&&", "@data", ".", "include?", "(", "value", ")", ")", "value", "else", "nil", "end", "end" ]
lookup collection key by a value
[ "lookup", "collection", "key", "by", "a", "value" ]
816d6993c3a05e538a45f65529ccef6dbc9c6bf1
https://github.com/redding/enumeration/blob/816d6993c3a05e538a45f65529ccef6dbc9c6bf1/lib/enumeration/collection.rb#L27-L36
train
brianpattison/motion-loco
lib/motion-loco/observable.rb
Loco.Observable.initialize_bindings
def initialize_bindings bindings = self.class.get_class_bindings bindings.each do |binding| binding[:proc].observed_properties.each do |key_path| register_observer(self, key_path) do new_value = binding[:proc].call(self) if binding[:name] self.setValue(new_value, forKey:binding[:name]) end end end end end
ruby
def initialize_bindings bindings = self.class.get_class_bindings bindings.each do |binding| binding[:proc].observed_properties.each do |key_path| register_observer(self, key_path) do new_value = binding[:proc].call(self) if binding[:name] self.setValue(new_value, forKey:binding[:name]) end end end end end
[ "def", "initialize_bindings", "bindings", "=", "self", ".", "class", ".", "get_class_bindings", "bindings", ".", "each", "do", "|", "binding", "|", "binding", "[", ":proc", "]", ".", "observed_properties", ".", "each", "do", "|", "key_path", "|", "register_observer", "(", "self", ",", "key_path", ")", "do", "new_value", "=", "binding", "[", ":proc", "]", ".", "call", "(", "self", ")", "if", "binding", "[", ":name", "]", "self", ".", "setValue", "(", "new_value", ",", "forKey", ":", "binding", "[", ":name", "]", ")", "end", "end", "end", "end", "end" ]
Create the bindings for the computed properties and observers
[ "Create", "the", "bindings", "for", "the", "computed", "properties", "and", "observers" ]
d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6
https://github.com/brianpattison/motion-loco/blob/d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6/lib/motion-loco/observable.rb#L97-L110
train
mmb/tinyatom
lib/tinyatom/feed.rb
TinyAtom.Feed.add_entry
def add_entry(id, title, updated, link, options={}) entries << { :id => id, :title => title, :updated => updated, :link => link }.merge(options) end
ruby
def add_entry(id, title, updated, link, options={}) entries << { :id => id, :title => title, :updated => updated, :link => link }.merge(options) end
[ "def", "add_entry", "(", "id", ",", "title", ",", "updated", ",", "link", ",", "options", "=", "{", "}", ")", "entries", "<<", "{", ":id", "=>", "id", ",", ":title", "=>", "title", ",", ":updated", "=>", "updated", ",", ":link", "=>", "link", "}", ".", "merge", "(", "options", ")", "end" ]
Add an entry to the feed
[ "Add", "an", "entry", "to", "the", "feed" ]
ae2d95a41729fc19f2b85d2df071ec7fa062184c
https://github.com/mmb/tinyatom/blob/ae2d95a41729fc19f2b85d2df071ec7fa062184c/lib/tinyatom/feed.rb#L19-L26
train
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.machined
def machined(config = {}) @machined = nil if config.delete(:reload) @machined ||= Machined::Environment.new(config.reverse_merge(:skip_bundle => true, :skip_autoloading => true)) end
ruby
def machined(config = {}) @machined = nil if config.delete(:reload) @machined ||= Machined::Environment.new(config.reverse_merge(:skip_bundle => true, :skip_autoloading => true)) end
[ "def", "machined", "(", "config", "=", "{", "}", ")", "@machined", "=", "nil", "if", "config", ".", "delete", "(", ":reload", ")", "@machined", "||=", "Machined", "::", "Environment", ".", "new", "(", "config", ".", "reverse_merge", "(", ":skip_bundle", "=>", "true", ",", ":skip_autoloading", "=>", "true", ")", ")", "end" ]
Convenience method for creating a new Machined environment
[ "Convenience", "method", "for", "creating", "a", "new", "Machined", "environment" ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L7-L10
train
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.build_context
def build_context(logical_path = 'application.js', options = {}) pathname = options[:pathname] || Pathname.new('assets').join(logical_path).expand_path env = options[:env] || machined.assets env.context_class.new env, logical_path, pathname end
ruby
def build_context(logical_path = 'application.js', options = {}) pathname = options[:pathname] || Pathname.new('assets').join(logical_path).expand_path env = options[:env] || machined.assets env.context_class.new env, logical_path, pathname end
[ "def", "build_context", "(", "logical_path", "=", "'application.js'", ",", "options", "=", "{", "}", ")", "pathname", "=", "options", "[", ":pathname", "]", "||", "Pathname", ".", "new", "(", "'assets'", ")", ".", "join", "(", "logical_path", ")", ".", "expand_path", "env", "=", "options", "[", ":env", "]", "||", "machined", ".", "assets", "env", ".", "context_class", ".", "new", "env", ",", "logical_path", ",", "pathname", "end" ]
Returns a fresh context, that can be used to test helpers.
[ "Returns", "a", "fresh", "context", "that", "can", "be", "used", "to", "test", "helpers", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L20-L25
train
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.machined_cli
def machined_cli(args, silence = true) capture(:stdout) { Machined::CLI.start args.split(' ') } end
ruby
def machined_cli(args, silence = true) capture(:stdout) { Machined::CLI.start args.split(' ') } end
[ "def", "machined_cli", "(", "args", ",", "silence", "=", "true", ")", "capture", "(", ":stdout", ")", "{", "Machined", "::", "CLI", ".", "start", "args", ".", "split", "(", "' '", ")", "}", "end" ]
Runs the CLI with the given args.
[ "Runs", "the", "CLI", "with", "the", "given", "args", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L28-L32
train
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.modify
def modify(file, content = nil) Pathname.new(file).tap do |file| file.open('w') { |f| f.write(content) } if content future = Time.now + 60 file.utime future, future end end
ruby
def modify(file, content = nil) Pathname.new(file).tap do |file| file.open('w') { |f| f.write(content) } if content future = Time.now + 60 file.utime future, future end end
[ "def", "modify", "(", "file", ",", "content", "=", "nil", ")", "Pathname", ".", "new", "(", "file", ")", ".", "tap", "do", "|", "file", "|", "file", ".", "open", "(", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "content", ")", "}", "if", "content", "future", "=", "Time", ".", "now", "+", "60", "file", ".", "utime", "future", ",", "future", "end", "end" ]
Modifies the given file
[ "Modifies", "the", "given", "file" ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L35-L41
train
redding/osheet
lib/osheet/workbook_element.rb
Osheet.WorkbookElement::PartialSet.verify
def verify(partial) unless partial.kind_of?(Partial) raise ArgumentError, 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key(partial) self[pkey] ||= nil pkey end
ruby
def verify(partial) unless partial.kind_of?(Partial) raise ArgumentError, 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key(partial) self[pkey] ||= nil pkey end
[ "def", "verify", "(", "partial", ")", "unless", "partial", ".", "kind_of?", "(", "Partial", ")", "raise", "ArgumentError", ",", "'you can only push Osheet::Partial objs to the partial set'", "end", "pkey", "=", "partial_key", "(", "partial", ")", "self", "[", "pkey", "]", "||=", "nil", "pkey", "end" ]
verify the partial, init and return the key otherwise ArgumentError it up
[ "verify", "the", "partial", "init", "and", "return", "the", "key", "otherwise", "ArgumentError", "it", "up" ]
207cc7bf29ddcb290f1614136f17a53686a7932e
https://github.com/redding/osheet/blob/207cc7bf29ddcb290f1614136f17a53686a7932e/lib/osheet/workbook_element.rb#L97-L104
train
redding/osheet
lib/osheet/workbook_element.rb
Osheet.WorkbookElement::TemplateSet.verify
def verify(template) unless template.kind_of?(Template) raise ArgumentError, 'you can only push Osheet::Template objs to the template set' end key = template_key(template) self[key.first] ||= {} self[key.first][key.last] ||= nil key end
ruby
def verify(template) unless template.kind_of?(Template) raise ArgumentError, 'you can only push Osheet::Template objs to the template set' end key = template_key(template) self[key.first] ||= {} self[key.first][key.last] ||= nil key end
[ "def", "verify", "(", "template", ")", "unless", "template", ".", "kind_of?", "(", "Template", ")", "raise", "ArgumentError", ",", "'you can only push Osheet::Template objs to the template set'", "end", "key", "=", "template_key", "(", "template", ")", "self", "[", "key", ".", "first", "]", "||=", "{", "}", "self", "[", "key", ".", "first", "]", "[", "key", ".", "last", "]", "||=", "nil", "key", "end" ]
verify the template, init the key set, and return the key string otherwise ArgumentError it up
[ "verify", "the", "template", "init", "the", "key", "set", "and", "return", "the", "key", "string", "otherwise", "ArgumentError", "it", "up" ]
207cc7bf29ddcb290f1614136f17a53686a7932e
https://github.com/redding/osheet/blob/207cc7bf29ddcb290f1614136f17a53686a7932e/lib/osheet/workbook_element.rb#L144-L152
train
linrock/favicon_party
lib/favicon_party/http_client.rb
FaviconParty.HTTPClient.get
def get(url) stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url)) output = encode_utf8(stdout.read).strip error = encode_utf8(stderr.read).strip if !error.nil? && !error.empty? if error.include? "SSL" raise FaviconParty::Curl::SSLError.new(error) elsif error.include? "Couldn't resolve host" raise FaviconParty::Curl::DNSError.new(error) else raise FaviconParty::CurlError.new(error) end end output end
ruby
def get(url) stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url)) output = encode_utf8(stdout.read).strip error = encode_utf8(stderr.read).strip if !error.nil? && !error.empty? if error.include? "SSL" raise FaviconParty::Curl::SSLError.new(error) elsif error.include? "Couldn't resolve host" raise FaviconParty::Curl::DNSError.new(error) else raise FaviconParty::CurlError.new(error) end end output end
[ "def", "get", "(", "url", ")", "stdin", ",", "stdout", ",", "stderr", ",", "t", "=", "Open3", ".", "popen3", "(", "curl_get_cmd", "(", "url", ")", ")", "output", "=", "encode_utf8", "(", "stdout", ".", "read", ")", ".", "strip", "error", "=", "encode_utf8", "(", "stderr", ".", "read", ")", ".", "strip", "if", "!", "error", ".", "nil?", "&&", "!", "error", ".", "empty?", "if", "error", ".", "include?", "\"SSL\"", "raise", "FaviconParty", "::", "Curl", "::", "SSLError", ".", "new", "(", "error", ")", "elsif", "error", ".", "include?", "\"Couldn't resolve host\"", "raise", "FaviconParty", "::", "Curl", "::", "DNSError", ".", "new", "(", "error", ")", "else", "raise", "FaviconParty", "::", "CurlError", ".", "new", "(", "error", ")", "end", "end", "output", "end" ]
Encodes output as utf8 - Not for binary http responses
[ "Encodes", "output", "as", "utf8", "-", "Not", "for", "binary", "http", "responses" ]
645d3c6f4a7152bf705ac092976a74f405f83ca1
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/http_client.rb#L16-L30
train
plangrade/plangrade-ruby
lib/plangrade/oauth2_client.rb
Plangrade.OAuth2Client.exchange_auth_code_for_token
def exchange_auth_code_for_token(opts={}) unless (opts[:params] && opts[:params][:code]) raise ArgumentError.new("You must include an authorization code as a parameter") end opts[:authenticate] ||= :body code = opts[:params].delete(:code) authorization_code.get_token(code, opts) end
ruby
def exchange_auth_code_for_token(opts={}) unless (opts[:params] && opts[:params][:code]) raise ArgumentError.new("You must include an authorization code as a parameter") end opts[:authenticate] ||= :body code = opts[:params].delete(:code) authorization_code.get_token(code, opts) end
[ "def", "exchange_auth_code_for_token", "(", "opts", "=", "{", "}", ")", "unless", "(", "opts", "[", ":params", "]", "&&", "opts", "[", ":params", "]", "[", ":code", "]", ")", "raise", "ArgumentError", ".", "new", "(", "\"You must include an authorization code as a parameter\"", ")", "end", "opts", "[", ":authenticate", "]", "||=", ":body", "code", "=", "opts", "[", ":params", "]", ".", "delete", "(", ":code", ")", "authorization_code", ".", "get_token", "(", "code", ",", "opts", ")", "end" ]
Makes a request to Plangrade server that will swap your authorization code for an access token @see http://docs.plangrade.com/#finish-authorization @opts [Hash] may include redirect uri and other query parameters >> client = PlangradeClient.new(config) >> client.exchange_auth_code_for_token({ :code => '123456789' :redirect_uri => 'http://localhost:3000/auth/plangrade/callback', }) POST /oauth/token HTTP/1.1 Host: www.plangrade.com Content-Type: application/x-www-form-urlencoded client_id={client_id}&code=G3Y6jU3a&grant_type=authorization_code& redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fplangrade%2Fcallback&client_secret={client_secret}
[ "Makes", "a", "request", "to", "Plangrade", "server", "that", "will", "swap", "your", "authorization", "code", "for", "an", "access", "token" ]
fe7240753825358c9b3c6887b51b5858a984c5f8
https://github.com/plangrade/plangrade-ruby/blob/fe7240753825358c9b3c6887b51b5858a984c5f8/lib/plangrade/oauth2_client.rb#L57-L64
train
26fe/sem4r
lib/sem4r_soap/soap_dumper.rb
Sem4rSoap.SoapDumper.dump_soap_options
def dump_soap_options(options) @soap_dump = true @soap_dump_log = nil if options[:directory] @soap_dump_dir = options[:directory] else @soap_dump_log = File.open(options[:file], "w") end @soap_dump_format = false || options[:format] @soap_dump_interceptor = options[:interceptor] if options[:interceptor] end
ruby
def dump_soap_options(options) @soap_dump = true @soap_dump_log = nil if options[:directory] @soap_dump_dir = options[:directory] else @soap_dump_log = File.open(options[:file], "w") end @soap_dump_format = false || options[:format] @soap_dump_interceptor = options[:interceptor] if options[:interceptor] end
[ "def", "dump_soap_options", "(", "options", ")", "@soap_dump", "=", "true", "@soap_dump_log", "=", "nil", "if", "options", "[", ":directory", "]", "@soap_dump_dir", "=", "options", "[", ":directory", "]", "else", "@soap_dump_log", "=", "File", ".", "open", "(", "options", "[", ":file", "]", ",", "\"w\"", ")", "end", "@soap_dump_format", "=", "false", "||", "options", "[", ":format", "]", "@soap_dump_interceptor", "=", "options", "[", ":interceptor", "]", "if", "options", "[", ":interceptor", "]", "end" ]
set the options for the dumping soap message @param [Hash] options @option options [String] :directory @option options [String] :file @option options [String] :format @option options [String] :interceptor
[ "set", "the", "options", "for", "the", "dumping", "soap", "message" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_soap/soap_dumper.rb#L43-L55
train
redding/deas
lib/deas/logging.rb
Deas.BaseLogging.call!
def call!(env) env['rack.logger'] = @logger status, headers, body = nil, nil, nil benchmark = Benchmark.measure do status, headers, body = @app.call(env) end log_error(env['deas.error']) env['deas.time_taken'] = RoundedTime.new(benchmark.real) [status, headers, body] end
ruby
def call!(env) env['rack.logger'] = @logger status, headers, body = nil, nil, nil benchmark = Benchmark.measure do status, headers, body = @app.call(env) end log_error(env['deas.error']) env['deas.time_taken'] = RoundedTime.new(benchmark.real) [status, headers, body] end
[ "def", "call!", "(", "env", ")", "env", "[", "'rack.logger'", "]", "=", "@logger", "status", ",", "headers", ",", "body", "=", "nil", ",", "nil", ",", "nil", "benchmark", "=", "Benchmark", ".", "measure", "do", "status", ",", "headers", ",", "body", "=", "@app", ".", "call", "(", "env", ")", "end", "log_error", "(", "env", "[", "'deas.error'", "]", ")", "env", "[", "'deas.time_taken'", "]", "=", "RoundedTime", ".", "new", "(", "benchmark", ".", "real", ")", "[", "status", ",", "headers", ",", "body", "]", "end" ]
The real Rack call interface. This is the common behavior for both the verbose and summary logging middlewares. It sets rack's logger, times the response and returns it as is.
[ "The", "real", "Rack", "call", "interface", ".", "This", "is", "the", "common", "behavior", "for", "both", "the", "verbose", "and", "summary", "logging", "middlewares", ".", "It", "sets", "rack", "s", "logger", "times", "the", "response", "and", "returns", "it", "as", "is", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L34-L45
train
redding/deas
lib/deas/logging.rb
Deas.VerboseLogging.call!
def call!(env) log "===== Received request =====" Rack::Request.new(env).tap do |request| log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env['deas.logging'] = Proc.new{ |msg| log(msg) } status, headers, body = super(env) log " Redir: #{headers['Location']}" if headers.key?('Location') log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====" [status, headers, body] end
ruby
def call!(env) log "===== Received request =====" Rack::Request.new(env).tap do |request| log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env['deas.logging'] = Proc.new{ |msg| log(msg) } status, headers, body = super(env) log " Redir: #{headers['Location']}" if headers.key?('Location') log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====" [status, headers, body] end
[ "def", "call!", "(", "env", ")", "log", "\"===== Received request =====\"", "Rack", "::", "Request", ".", "new", "(", "env", ")", ".", "tap", "do", "|", "request", "|", "log", "\" Method: #{request.request_method.inspect}\"", "log", "\" Path: #{request.path.inspect}\"", "end", "env", "[", "'deas.logging'", "]", "=", "Proc", ".", "new", "{", "|", "msg", "|", "log", "(", "msg", ")", "}", "status", ",", "headers", ",", "body", "=", "super", "(", "env", ")", "log", "\" Redir: #{headers['Location']}\"", "if", "headers", ".", "key?", "(", "'Location'", ")", "log", "\"===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====\"", "[", "status", ",", "headers", ",", "body", "]", "end" ]
This the real Rack call interface. It adds logging before and after super-ing to the common logging behavior.
[ "This", "the", "real", "Rack", "call", "interface", ".", "It", "adds", "logging", "before", "and", "after", "super", "-", "ing", "to", "the", "common", "logging", "behavior", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L74-L85
train
redding/deas
lib/deas/logging.rb
Deas.SummaryLogging.call!
def call!(env) env['deas.logging'] = Proc.new{ |msg| } # no-op status, headers, body = super(env) request = Rack::Request.new(env) line_attrs = { 'method' => request.request_method, 'path' => request.path, 'params' => env['deas.params'], 'splat' => env['deas.splat'], 'time' => env['deas.time_taken'], 'status' => status } if env['deas.handler_class'] line_attrs['handler'] = env['deas.handler_class'].name end if headers.key?('Location') line_attrs['redir'] = headers['Location'] end log SummaryLine.new(line_attrs) [status, headers, body] end
ruby
def call!(env) env['deas.logging'] = Proc.new{ |msg| } # no-op status, headers, body = super(env) request = Rack::Request.new(env) line_attrs = { 'method' => request.request_method, 'path' => request.path, 'params' => env['deas.params'], 'splat' => env['deas.splat'], 'time' => env['deas.time_taken'], 'status' => status } if env['deas.handler_class'] line_attrs['handler'] = env['deas.handler_class'].name end if headers.key?('Location') line_attrs['redir'] = headers['Location'] end log SummaryLine.new(line_attrs) [status, headers, body] end
[ "def", "call!", "(", "env", ")", "env", "[", "'deas.logging'", "]", "=", "Proc", ".", "new", "{", "|", "msg", "|", "}", "status", ",", "headers", ",", "body", "=", "super", "(", "env", ")", "request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "line_attrs", "=", "{", "'method'", "=>", "request", ".", "request_method", ",", "'path'", "=>", "request", ".", "path", ",", "'params'", "=>", "env", "[", "'deas.params'", "]", ",", "'splat'", "=>", "env", "[", "'deas.splat'", "]", ",", "'time'", "=>", "env", "[", "'deas.time_taken'", "]", ",", "'status'", "=>", "status", "}", "if", "env", "[", "'deas.handler_class'", "]", "line_attrs", "[", "'handler'", "]", "=", "env", "[", "'deas.handler_class'", "]", ".", "name", "end", "if", "headers", ".", "key?", "(", "'Location'", ")", "line_attrs", "[", "'redir'", "]", "=", "headers", "[", "'Location'", "]", "end", "log", "SummaryLine", ".", "new", "(", "line_attrs", ")", "[", "status", ",", "headers", ",", "body", "]", "end" ]
This the real Rack call interface. It adds logging after super-ing to the common logging behavior.
[ "This", "the", "real", "Rack", "call", "interface", ".", "It", "adds", "logging", "after", "super", "-", "ing", "to", "the", "common", "logging", "behavior", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L97-L117
train
jrissler/wafflemix
app/models/wafflemix/asset.rb
Wafflemix.Asset.to_jq_upload
def to_jq_upload { "name" => read_attribute(:asset_name), "size" => asset_size, "url" => asset_url, "thumbnail_url" => asset.thumb('80x80#').url, "delete_url" => Wafflemix::Engine::routes.url_helpers.admin_asset_path(:id => id), "delete_type" => "DELETE" } end
ruby
def to_jq_upload { "name" => read_attribute(:asset_name), "size" => asset_size, "url" => asset_url, "thumbnail_url" => asset.thumb('80x80#').url, "delete_url" => Wafflemix::Engine::routes.url_helpers.admin_asset_path(:id => id), "delete_type" => "DELETE" } end
[ "def", "to_jq_upload", "{", "\"name\"", "=>", "read_attribute", "(", ":asset_name", ")", ",", "\"size\"", "=>", "asset_size", ",", "\"url\"", "=>", "asset_url", ",", "\"thumbnail_url\"", "=>", "asset", ".", "thumb", "(", "'80x80#'", ")", ".", "url", ",", "\"delete_url\"", "=>", "Wafflemix", "::", "Engine", "::", "routes", ".", "url_helpers", ".", "admin_asset_path", "(", ":id", "=>", "id", ")", ",", "\"delete_type\"", "=>", "\"DELETE\"", "}", "end" ]
one convenient method to pass jq_upload the necessary information
[ "one", "convenient", "method", "to", "pass", "jq_upload", "the", "necessary", "information" ]
050db4c321319ff4dee425c79a25b4bd859f67c0
https://github.com/jrissler/wafflemix/blob/050db4c321319ff4dee425c79a25b4bd859f67c0/app/models/wafflemix/asset.rb#L11-L20
train
bumbleworks/bumbleworks
lib/bumbleworks/user.rb
Bumbleworks.User.claim
def claim(task, force = false) raise UnauthorizedClaimAttempt unless has_role?(task.role) release!(task) if force task.claim(claim_token) end
ruby
def claim(task, force = false) raise UnauthorizedClaimAttempt unless has_role?(task.role) release!(task) if force task.claim(claim_token) end
[ "def", "claim", "(", "task", ",", "force", "=", "false", ")", "raise", "UnauthorizedClaimAttempt", "unless", "has_role?", "(", "task", ".", "role", ")", "release!", "(", "task", ")", "if", "force", "task", ".", "claim", "(", "claim_token", ")", "end" ]
Attempts to set self as the claimant of the given task. If not authorized to claim the task, raises exception. Also bubbles exception from Task when task is already claimed by a different claimant.
[ "Attempts", "to", "set", "self", "as", "the", "claimant", "of", "the", "given", "task", ".", "If", "not", "authorized", "to", "claim", "the", "task", "raises", "exception", ".", "Also", "bubbles", "exception", "from", "Task", "when", "task", "is", "already", "claimed", "by", "a", "different", "claimant", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/user.rb#L52-L56
train
bumbleworks/bumbleworks
lib/bumbleworks/user.rb
Bumbleworks.User.release
def release(task, force = false) return unless task.claimed? raise UnauthorizedReleaseAttempt unless force || task.claimant == claim_token task.release end
ruby
def release(task, force = false) return unless task.claimed? raise UnauthorizedReleaseAttempt unless force || task.claimant == claim_token task.release end
[ "def", "release", "(", "task", ",", "force", "=", "false", ")", "return", "unless", "task", ".", "claimed?", "raise", "UnauthorizedReleaseAttempt", "unless", "force", "||", "task", ".", "claimant", "==", "claim_token", "task", ".", "release", "end" ]
If we are the current claimant of the given task, release the task. Does nothing if the task is not claimed, but raises exception if the task is currently claimed by someone else.
[ "If", "we", "are", "the", "current", "claimant", "of", "the", "given", "task", "release", "the", "task", ".", "Does", "nothing", "if", "the", "task", "is", "not", "claimed", "but", "raises", "exception", "if", "the", "task", "is", "currently", "claimed", "by", "someone", "else", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/user.rb#L70-L74
train
cbrumelle/blueprintr
lib/blueprint-css/lib/blueprint/validator.rb
Blueprint.Validator.validate
def validate java_path = `which java`.rstrip raise "You do not have a Java installed, but it is required." if java_path.blank? output_header Blueprint::CSS_FILES.keys.each do |file_name| css_output_path = File.join(Blueprint::BLUEPRINT_ROOT_PATH, file_name) puts "\n\n Testing #{css_output_path}" puts " Output ============================================================\n\n" @error_count += 1 if !system("#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'") end output_footer end
ruby
def validate java_path = `which java`.rstrip raise "You do not have a Java installed, but it is required." if java_path.blank? output_header Blueprint::CSS_FILES.keys.each do |file_name| css_output_path = File.join(Blueprint::BLUEPRINT_ROOT_PATH, file_name) puts "\n\n Testing #{css_output_path}" puts " Output ============================================================\n\n" @error_count += 1 if !system("#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'") end output_footer end
[ "def", "validate", "java_path", "=", "`", "`", ".", "rstrip", "raise", "\"You do not have a Java installed, but it is required.\"", "if", "java_path", ".", "blank?", "output_header", "Blueprint", "::", "CSS_FILES", ".", "keys", ".", "each", "do", "|", "file_name", "|", "css_output_path", "=", "File", ".", "join", "(", "Blueprint", "::", "BLUEPRINT_ROOT_PATH", ",", "file_name", ")", "puts", "\"\\n\\n Testing #{css_output_path}\"", "puts", "\" Output ============================================================\\n\\n\"", "@error_count", "+=", "1", "if", "!", "system", "(", "\"#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'\"", ")", "end", "output_footer", "end" ]
Validates all three CSS files
[ "Validates", "all", "three", "CSS", "files" ]
b414436f614a8d97d77b47b588ddcf3f5e61b6bd
https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/validator.rb#L11-L25
train
charypar/cyclical
lib/cyclical/schedule.rb
Cyclical.Schedule.occurrences_between
def occurrences_between(t1, t2) return ((start_time < t1 || @start_time >= t2) ? [] : [start_time]) if @occurrence.nil? @occurrence.occurrences_between(t1, t2) end
ruby
def occurrences_between(t1, t2) return ((start_time < t1 || @start_time >= t2) ? [] : [start_time]) if @occurrence.nil? @occurrence.occurrences_between(t1, t2) end
[ "def", "occurrences_between", "(", "t1", ",", "t2", ")", "return", "(", "(", "start_time", "<", "t1", "||", "@start_time", ">=", "t2", ")", "?", "[", "]", ":", "[", "start_time", "]", ")", "if", "@occurrence", ".", "nil?", "@occurrence", ".", "occurrences_between", "(", "t1", ",", "t2", ")", "end" ]
occurrences in [t1, t2)
[ "occurrences", "in", "[", "t1", "t2", ")" ]
8e45b8f83e2dd59fcad01e220412bb361867f5c6
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/schedule.rb#L75-L79
train
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.destroy
def destroy response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}", :post)) raise CrateDestroyError, response["message"] unless response["status"] != "failure" end
ruby
def destroy response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}", :post)) raise CrateDestroyError, response["message"] unless response["status"] != "failure" end
[ "def", "destroy", "response", "=", "JSON", ".", "parse", "(", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % [\"#{self.id}\"]}\"", ",", ":post", ")", ")", "raise", "CrateDestroyError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Destroys the given crate object. @return [CrateDestroyError, nil] if there is an issue destroying the crate, an error will be raised with the message explaining why.
[ "Destroys", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L25-L28
train
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.rename
def rename(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}", :post, {:body => {:name => name}})) raise CrateRenameError, response["message"] unless response["status"] != "failure" end
ruby
def rename(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}", :post, {:body => {:name => name}})) raise CrateRenameError, response["message"] unless response["status"] != "failure" end
[ "def", "rename", "(", "name", ")", "response", "=", "JSON", ".", "parse", "(", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % [\"#{self.id}\"]}\"", ",", ":post", ",", "{", ":body", "=>", "{", ":name", "=>", "name", "}", "}", ")", ")", "raise", "CrateRenameError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Renamed the given crate object. @return [CrateRenameError, nil] if there is an issue with renaming the crate, an error will be raised with the message explaining why.
[ "Renamed", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L33-L36
train
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.add_file
def add_file(path) file = File.new(path) response = CrateAPI::Base.call("#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}", :post, {:body => {:file => file, :crate_id => @id}}) raise CrateFileAlreadyExistsError, response["message"] unless response["status"] != "failure" end
ruby
def add_file(path) file = File.new(path) response = CrateAPI::Base.call("#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}", :post, {:body => {:file => file, :crate_id => @id}}) raise CrateFileAlreadyExistsError, response["message"] unless response["status"] != "failure" end
[ "def", "add_file", "(", "path", ")", "file", "=", "File", ".", "new", "(", "path", ")", "response", "=", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}\"", ",", ":post", ",", "{", ":body", "=>", "{", ":file", "=>", "file", ",", ":crate_id", "=>", "@id", "}", "}", ")", "raise", "CrateFileAlreadyExistsError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Add a file to the given crate object. @param [String] This is the path to the file that you wish to upload. @return [CrateFileAlreadyExistsError, nil] if there is an issue uploading the file to the crate, an error will be raised with the message explaining why.
[ "Add", "a", "file", "to", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L42-L46
train
humpyard/humpyard
app/models/humpyard/element.rb
Humpyard.Element.last_modified
def last_modified rails_root_mtime = Time.zone.at(::File.new("#{Rails.root}").mtime) timestamps = [rails_root_mtime, self.updated_at] timestamps.sort.last end
ruby
def last_modified rails_root_mtime = Time.zone.at(::File.new("#{Rails.root}").mtime) timestamps = [rails_root_mtime, self.updated_at] timestamps.sort.last end
[ "def", "last_modified", "rails_root_mtime", "=", "Time", ".", "zone", ".", "at", "(", "::", "File", ".", "new", "(", "\"#{Rails.root}\"", ")", ".", "mtime", ")", "timestamps", "=", "[", "rails_root_mtime", ",", "self", ".", "updated_at", "]", "timestamps", ".", "sort", ".", "last", "end" ]
Return the logical modification time for the element.
[ "Return", "the", "logical", "modification", "time", "for", "the", "element", "." ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/element.rb#L48-L52
train
boxgrinder/boxgrinder-core
lib/boxgrinder-core/helpers/appliance-config-helper.rb
BoxGrinder.ApplianceConfigHelper.substitute
def substitute(init, value, depth) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError, "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value.clone value.gsub!(/(#(.*?)#)+?/) do # 1. Match pre-defined variable, or variable defined in appliance definition. next @appliance_config.variables[$2] if @appliance_config.variables.has_key?($2) # 2. Match from environment variables. next ENV[$2] unless ENV[$2].nil? # 3. No match, replace the original string. $1 end substitute(init, value, depth+1) unless original == value end
ruby
def substitute(init, value, depth) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError, "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value.clone value.gsub!(/(#(.*?)#)+?/) do # 1. Match pre-defined variable, or variable defined in appliance definition. next @appliance_config.variables[$2] if @appliance_config.variables.has_key?($2) # 2. Match from environment variables. next ENV[$2] unless ENV[$2].nil? # 3. No match, replace the original string. $1 end substitute(init, value, depth+1) unless original == value end
[ "def", "substitute", "(", "init", ",", "value", ",", "depth", ")", "if", "depth", ">", "VAR_SUBSTITUTION_MAX_DEPTH", "raise", "SystemStackError", ",", "\"Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping.\"", "end", "original", "=", "value", ".", "clone", "value", ".", "gsub!", "(", "/", "/", ")", "do", "next", "@appliance_config", ".", "variables", "[", "$2", "]", "if", "@appliance_config", ".", "variables", ".", "has_key?", "(", "$2", ")", "next", "ENV", "[", "$2", "]", "unless", "ENV", "[", "$2", "]", ".", "nil?", "$1", "end", "substitute", "(", "init", ",", "value", ",", "depth", "+", "1", ")", "unless", "original", "==", "value", "end" ]
Replace variables with values. This will occur recursively upto a limited depth if the resolved values themselves contain variables.
[ "Replace", "variables", "with", "values", ".", "This", "will", "occur", "recursively", "upto", "a", "limited", "depth", "if", "the", "resolved", "values", "themselves", "contain", "variables", "." ]
7d54ad1ddf040078b6bab0a4dc94392b2492bde5
https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-config-helper.rb#L106-L121
train
boxgrinder/boxgrinder-core
lib/boxgrinder-core/helpers/appliance-config-helper.rb
BoxGrinder.ApplianceConfigHelper.merge_partitions
def merge_partitions partitions = {} merge_field('hardware.partitions') do |parts| parts.each do |root, partition| if partitions.keys.include?(root) partitions[root]['size'] = partition['size'] if partitions[root]['size'] < partition['size'] unless partition['type'].nil? partitions[root].delete('options') if partitions[root]['type'] != partition['type'] partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end else partitions[root] = {} partitions[root]['size'] = partition['size'] unless partition['type'].nil? partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end end partitions[root]['passphrase'] = partition['passphrase'] unless partition['passphrase'].nil? partitions[root]['options'] = partition['options'] unless partition['options'].nil? end end # https://bugzilla.redhat.com/show_bug.cgi?id=466275 partitions['/boot'] = {'type' => 'ext3', 'size' => 0.1} if partitions['/boot'].nil? and (@appliance_config.os.name == 'sl' or @appliance_config.os.name == 'centos' or @appliance_config.os.name == 'rhel') and @appliance_config.os.version == '5' @appliance_config.hardware.partitions = partitions end
ruby
def merge_partitions partitions = {} merge_field('hardware.partitions') do |parts| parts.each do |root, partition| if partitions.keys.include?(root) partitions[root]['size'] = partition['size'] if partitions[root]['size'] < partition['size'] unless partition['type'].nil? partitions[root].delete('options') if partitions[root]['type'] != partition['type'] partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end else partitions[root] = {} partitions[root]['size'] = partition['size'] unless partition['type'].nil? partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end end partitions[root]['passphrase'] = partition['passphrase'] unless partition['passphrase'].nil? partitions[root]['options'] = partition['options'] unless partition['options'].nil? end end # https://bugzilla.redhat.com/show_bug.cgi?id=466275 partitions['/boot'] = {'type' => 'ext3', 'size' => 0.1} if partitions['/boot'].nil? and (@appliance_config.os.name == 'sl' or @appliance_config.os.name == 'centos' or @appliance_config.os.name == 'rhel') and @appliance_config.os.version == '5' @appliance_config.hardware.partitions = partitions end
[ "def", "merge_partitions", "partitions", "=", "{", "}", "merge_field", "(", "'hardware.partitions'", ")", "do", "|", "parts", "|", "parts", ".", "each", "do", "|", "root", ",", "partition", "|", "if", "partitions", ".", "keys", ".", "include?", "(", "root", ")", "partitions", "[", "root", "]", "[", "'size'", "]", "=", "partition", "[", "'size'", "]", "if", "partitions", "[", "root", "]", "[", "'size'", "]", "<", "partition", "[", "'size'", "]", "unless", "partition", "[", "'type'", "]", ".", "nil?", "partitions", "[", "root", "]", ".", "delete", "(", "'options'", ")", "if", "partitions", "[", "root", "]", "[", "'type'", "]", "!=", "partition", "[", "'type'", "]", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "partition", "[", "'type'", "]", "else", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "@appliance_config", ".", "default_filesystem_type", "end", "else", "partitions", "[", "root", "]", "=", "{", "}", "partitions", "[", "root", "]", "[", "'size'", "]", "=", "partition", "[", "'size'", "]", "unless", "partition", "[", "'type'", "]", ".", "nil?", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "partition", "[", "'type'", "]", "else", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "@appliance_config", ".", "default_filesystem_type", "end", "end", "partitions", "[", "root", "]", "[", "'passphrase'", "]", "=", "partition", "[", "'passphrase'", "]", "unless", "partition", "[", "'passphrase'", "]", ".", "nil?", "partitions", "[", "root", "]", "[", "'options'", "]", "=", "partition", "[", "'options'", "]", "unless", "partition", "[", "'options'", "]", ".", "nil?", "end", "end", "partitions", "[", "'/boot'", "]", "=", "{", "'type'", "=>", "'ext3'", ",", "'size'", "=>", "0.1", "}", "if", "partitions", "[", "'/boot'", "]", ".", "nil?", "and", "(", "@appliance_config", ".", "os", ".", "name", "==", "'sl'", "or", "@appliance_config", ".", "os", ".", "name", "==", "'centos'", "or", "@appliance_config", ".", "os", ".", "name", "==", "'rhel'", ")", "and", "@appliance_config", ".", "os", ".", "version", "==", "'5'", "@appliance_config", ".", "hardware", ".", "partitions", "=", "partitions", "end" ]
This will merge partitions from multiple appliances.
[ "This", "will", "merge", "partitions", "from", "multiple", "appliances", "." ]
7d54ad1ddf040078b6bab0a4dc94392b2492bde5
https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-config-helper.rb#L134-L168
train
redding/logsly
lib/logsly/logging182/appenders/rolling_file.rb
Logsly::Logging182::Appenders.RollingFile.copy_truncate
def copy_truncate return unless ::File.exist?(@fn) FileUtils.concat @fn, @fn_copy @io.truncate 0 # touch the age file if needed if @age FileUtils.touch @age_fn @age_fn_mtime = nil end @roller.roll = true end
ruby
def copy_truncate return unless ::File.exist?(@fn) FileUtils.concat @fn, @fn_copy @io.truncate 0 # touch the age file if needed if @age FileUtils.touch @age_fn @age_fn_mtime = nil end @roller.roll = true end
[ "def", "copy_truncate", "return", "unless", "::", "File", ".", "exist?", "(", "@fn", ")", "FileUtils", ".", "concat", "@fn", ",", "@fn_copy", "@io", ".", "truncate", "0", "if", "@age", "FileUtils", ".", "touch", "@age_fn", "@age_fn_mtime", "=", "nil", "end", "@roller", ".", "roll", "=", "true", "end" ]
Copy the contents of the logfile to another file. Truncate the logfile to zero length. This method will set the roll flag so that all the current logfiles will be rolled along with the copied file.
[ "Copy", "the", "contents", "of", "the", "logfile", "to", "another", "file", ".", "Truncate", "the", "logfile", "to", "zero", "length", ".", "This", "method", "will", "set", "the", "roll", "flag", "so", "that", "all", "the", "current", "logfiles", "will", "be", "rolled", "along", "with", "the", "copied", "file", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/rolling_file.rb#L232-L244
train
ketan/diff-display
lib/diff/display/unified/generator.rb
Diff::Display.Unified::Generator.inline_diff
def inline_diff(line, start, ending) if start != 0 || ending != 0 last = ending + line.length str = line[0...start] + '\0' + line[start...last] + '\1' + line[last...line.length] end str || line end
ruby
def inline_diff(line, start, ending) if start != 0 || ending != 0 last = ending + line.length str = line[0...start] + '\0' + line[start...last] + '\1' + line[last...line.length] end str || line end
[ "def", "inline_diff", "(", "line", ",", "start", ",", "ending", ")", "if", "start", "!=", "0", "||", "ending", "!=", "0", "last", "=", "ending", "+", "line", ".", "length", "str", "=", "line", "[", "0", "...", "start", "]", "+", "'\\0'", "+", "line", "[", "start", "...", "last", "]", "+", "'\\1'", "+", "line", "[", "last", "...", "line", ".", "length", "]", "end", "str", "||", "line", "end" ]
Inserts string formating characters around the section of a string that differs internally from another line so that the Line class can insert the desired formating
[ "Inserts", "string", "formating", "characters", "around", "the", "section", "of", "a", "string", "that", "differs", "internally", "from", "another", "line", "so", "that", "the", "Line", "class", "can", "insert", "the", "desired", "formating" ]
39a75568148bcd1ee386189d6b46af3126a3a785
https://github.com/ketan/diff-display/blob/39a75568148bcd1ee386189d6b46af3126a3a785/lib/diff/display/unified/generator.rb#L160-L166
train
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.function
def function(vec1, vec2) case @func when :linear return normalized_radius(vec1, vec2) when :cubic_alt return normalized_radius(vec1, vec2)**(1.5) when :thin_plate_splines return 0.0 if radius(vec1, vec2) == 0.0 return normalized_radius(vec1, vec2)**2.0 * Math.log(normalized_radius(vec1, vec2)) when :thin_plate_splines_alt rnorm = ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0)) return rnorm * Math.log(rnorm) when :multiquadratic # return Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) (@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0) when :inverse_multiquadratic 1.0 / ((@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0)) when :cubic ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))**(1.5) # invs = ((vec1-vec2).square + @r0.square).sqrt**(-1) # invs.sum # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) # when :inverse_multiquadratic # # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) else raise ArgumentError.new("Bad radial basis function: #{@func}") end end
ruby
def function(vec1, vec2) case @func when :linear return normalized_radius(vec1, vec2) when :cubic_alt return normalized_radius(vec1, vec2)**(1.5) when :thin_plate_splines return 0.0 if radius(vec1, vec2) == 0.0 return normalized_radius(vec1, vec2)**2.0 * Math.log(normalized_radius(vec1, vec2)) when :thin_plate_splines_alt rnorm = ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0)) return rnorm * Math.log(rnorm) when :multiquadratic # return Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) (@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0) when :inverse_multiquadratic 1.0 / ((@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0)) when :cubic ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))**(1.5) # invs = ((vec1-vec2).square + @r0.square).sqrt**(-1) # invs.sum # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) # when :inverse_multiquadratic # # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) else raise ArgumentError.new("Bad radial basis function: #{@func}") end end
[ "def", "function", "(", "vec1", ",", "vec2", ")", "case", "@func", "when", ":linear", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "when", ":cubic_alt", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "**", "(", "1.5", ")", "when", ":thin_plate_splines", "return", "0.0", "if", "radius", "(", "vec1", ",", "vec2", ")", "==", "0.0", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "**", "2.0", "*", "Math", ".", "log", "(", "normalized_radius", "(", "vec1", ",", "vec2", ")", ")", "when", ":thin_plate_splines_alt", "rnorm", "=", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "2.0", "/", "@r0", ".", "size", ")", "*", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "return", "rnorm", "*", "Math", ".", "log", "(", "rnorm", ")", "when", ":multiquadratic", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "1.0", "/", "@r0", ".", "size", ")", "*", "Math", ".", "sqrt", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", "when", ":inverse_multiquadratic", "1.0", "/", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "1.0", "/", "@r0", ".", "size", ")", "*", "Math", ".", "sqrt", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "when", ":cubic", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "2.0", "/", "@r0", ".", "size", ")", "*", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "**", "(", "1.5", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Bad radial basis function: #{@func}\"", ")", "end", "end" ]
Return the value of the interpolation kernel for the separation between the two given vectors. If linear was chosen this will just be the normalised distance between the two points.
[ "Return", "the", "value", "of", "the", "interpolation", "kernel", "for", "the", "separation", "between", "the", "two", "given", "vectors", ".", "If", "linear", "was", "chosen", "this", "will", "just", "be", "the", "normalised", "distance", "between", "the", "two", "points", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L176-L205
train
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.eval
def eval(*pars) raise ArgumentError("wrong number of points") if pars.size != @dim # p vals pars = GSL::Vector.alloc(pars) return @npoints.times.inject(0.0) do |sum, i| # sum + function(radius(vals, @gridpoints.row(i)))*@weights[i] sum + function(pars, @gridpoints.row(i))*@weights[i] end end
ruby
def eval(*pars) raise ArgumentError("wrong number of points") if pars.size != @dim # p vals pars = GSL::Vector.alloc(pars) return @npoints.times.inject(0.0) do |sum, i| # sum + function(radius(vals, @gridpoints.row(i)))*@weights[i] sum + function(pars, @gridpoints.row(i))*@weights[i] end end
[ "def", "eval", "(", "*", "pars", ")", "raise", "ArgumentError", "(", "\"wrong number of points\"", ")", "if", "pars", ".", "size", "!=", "@dim", "pars", "=", "GSL", "::", "Vector", ".", "alloc", "(", "pars", ")", "return", "@npoints", ".", "times", ".", "inject", "(", "0.0", ")", "do", "|", "sum", ",", "i", "|", "sum", "+", "function", "(", "pars", ",", "@gridpoints", ".", "row", "(", "i", ")", ")", "*", "@weights", "[", "i", "]", "end", "end" ]
Return the interpolated value for the given parameters.
[ "Return", "the", "interpolated", "value", "for", "the", "given", "parameters", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L209-L217
train
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.gaussian_smooth_eval
def gaussian_smooth_eval(*vals, sigma_vec) npix = 7 raise "npix must be odd" if npix%2==0 case vals.size when 2 # delt0 = 3.0*0.999999*sigma_vec[0] / (npix-1) # delt1 = 3.0*0.999999*sigma_vec[1] / (npix-1) # sig3 = 3.0*sigma vals0 = GSL::Vector.linspace(vals[0] - 3.0* sigma_vec[0], vals[0] + 3.0* sigma_vec[0], npix) vals1 = GSL::Vector.linspace(vals[1] - 3.0* sigma_vec[1], vals[1] + 3.0* sigma_vec[1], npix) mat = GSL::Matrix.alloc(vals0.size, vals1.size) for i in 0...vals0.size for j in 0...vals1.size mat[i,j] = eval(vals0[i], vals1[j]) end end mat.gaussian_smooth(*sigma_vec.to_a) cent = (npix - 1) / 2 return mat[cent, cent] else raise 'Not supported for this number of dimensions yet' end end
ruby
def gaussian_smooth_eval(*vals, sigma_vec) npix = 7 raise "npix must be odd" if npix%2==0 case vals.size when 2 # delt0 = 3.0*0.999999*sigma_vec[0] / (npix-1) # delt1 = 3.0*0.999999*sigma_vec[1] / (npix-1) # sig3 = 3.0*sigma vals0 = GSL::Vector.linspace(vals[0] - 3.0* sigma_vec[0], vals[0] + 3.0* sigma_vec[0], npix) vals1 = GSL::Vector.linspace(vals[1] - 3.0* sigma_vec[1], vals[1] + 3.0* sigma_vec[1], npix) mat = GSL::Matrix.alloc(vals0.size, vals1.size) for i in 0...vals0.size for j in 0...vals1.size mat[i,j] = eval(vals0[i], vals1[j]) end end mat.gaussian_smooth(*sigma_vec.to_a) cent = (npix - 1) / 2 return mat[cent, cent] else raise 'Not supported for this number of dimensions yet' end end
[ "def", "gaussian_smooth_eval", "(", "*", "vals", ",", "sigma_vec", ")", "npix", "=", "7", "raise", "\"npix must be odd\"", "if", "npix", "%", "2", "==", "0", "case", "vals", ".", "size", "when", "2", "vals0", "=", "GSL", "::", "Vector", ".", "linspace", "(", "vals", "[", "0", "]", "-", "3.0", "*", "sigma_vec", "[", "0", "]", ",", "vals", "[", "0", "]", "+", "3.0", "*", "sigma_vec", "[", "0", "]", ",", "npix", ")", "vals1", "=", "GSL", "::", "Vector", ".", "linspace", "(", "vals", "[", "1", "]", "-", "3.0", "*", "sigma_vec", "[", "1", "]", ",", "vals", "[", "1", "]", "+", "3.0", "*", "sigma_vec", "[", "1", "]", ",", "npix", ")", "mat", "=", "GSL", "::", "Matrix", ".", "alloc", "(", "vals0", ".", "size", ",", "vals1", ".", "size", ")", "for", "i", "in", "0", "...", "vals0", ".", "size", "for", "j", "in", "0", "...", "vals1", ".", "size", "mat", "[", "i", ",", "j", "]", "=", "eval", "(", "vals0", "[", "i", "]", ",", "vals1", "[", "j", "]", ")", "end", "end", "mat", ".", "gaussian_smooth", "(", "*", "sigma_vec", ".", "to_a", ")", "cent", "=", "(", "npix", "-", "1", ")", "/", "2", "return", "mat", "[", "cent", ",", "cent", "]", "else", "raise", "'Not supported for this number of dimensions yet'", "end", "end" ]
Evaluate the function,
[ "Evaluate", "the", "function" ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L221-L244
train
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.Contour.graphkit
def graphkit(*args) if args.size == 0 conts = @last_contours else conts = contours(*args) end graphs = conts.map do |val, cons| unless cons[0] nil else (cons.map do |con| # p con contour = con.transpose kit = CodeRunner::GraphKit.autocreate({x: {data: contour[0]}, y: {data: contour[1], title: val.to_s}}) kit.data[0].with = "l" kit end).sum end end graphs.compact.reverse.sum end
ruby
def graphkit(*args) if args.size == 0 conts = @last_contours else conts = contours(*args) end graphs = conts.map do |val, cons| unless cons[0] nil else (cons.map do |con| # p con contour = con.transpose kit = CodeRunner::GraphKit.autocreate({x: {data: contour[0]}, y: {data: contour[1], title: val.to_s}}) kit.data[0].with = "l" kit end).sum end end graphs.compact.reverse.sum end
[ "def", "graphkit", "(", "*", "args", ")", "if", "args", ".", "size", "==", "0", "conts", "=", "@last_contours", "else", "conts", "=", "contours", "(", "*", "args", ")", "end", "graphs", "=", "conts", ".", "map", "do", "|", "val", ",", "cons", "|", "unless", "cons", "[", "0", "]", "nil", "else", "(", "cons", ".", "map", "do", "|", "con", "|", "contour", "=", "con", ".", "transpose", "kit", "=", "CodeRunner", "::", "GraphKit", ".", "autocreate", "(", "{", "x", ":", "{", "data", ":", "contour", "[", "0", "]", "}", ",", "y", ":", "{", "data", ":", "contour", "[", "1", "]", ",", "title", ":", "val", ".", "to_s", "}", "}", ")", "kit", ".", "data", "[", "0", "]", ".", "with", "=", "\"l\"", "kit", "end", ")", ".", "sum", "end", "end", "graphs", ".", "compact", ".", "reverse", ".", "sum", "end" ]
Create a GraphKit object of the contours.
[ "Create", "a", "GraphKit", "object", "of", "the", "contours", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L325-L345
train
NYULibraries/citero-jruby
lib/citero-jruby/CSF.rb
Citero.CSF.method_missing
def method_missing(meth, *args, &block) # Check to see if it can be evaluated if(matches? meth) #Defines the method and caches it to the class self.class.send(:define_method, meth) do # Splits the method and parameter. See formatize and directionize @csf::config()::getStringArray(meth.to_s.to_java_name).to_a end # calls the method send meth, *args, &block else super end end
ruby
def method_missing(meth, *args, &block) # Check to see if it can be evaluated if(matches? meth) #Defines the method and caches it to the class self.class.send(:define_method, meth) do # Splits the method and parameter. See formatize and directionize @csf::config()::getStringArray(meth.to_s.to_java_name).to_a end # calls the method send meth, *args, &block else super end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "if", "(", "matches?", "meth", ")", "self", ".", "class", ".", "send", "(", ":define_method", ",", "meth", ")", "do", "@csf", "::", "config", "(", ")", "::", "getStringArray", "(", "meth", ".", "to_s", ".", "to_java_name", ")", ".", "to_a", "end", "send", "meth", ",", "*", "args", ",", "&", "block", "else", "super", "end", "end" ]
Initialize the CSF object with data The method_missing override checks to see if the called method can be evaluated to a key, then stores it and calls it if it can. For example, .itemType or .authors.
[ "Initialize", "the", "CSF", "object", "with", "data", "The", "method_missing", "override", "checks", "to", "see", "if", "the", "called", "method", "can", "be", "evaluated", "to", "a", "key", "then", "stores", "it", "and", "calls", "it", "if", "it", "can", ".", "For", "example", ".", "itemType", "or", ".", "authors", "." ]
ddf1142a8a05cb1e7153d1887239fe913df563ce
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/CSF.rb#L21-L34
train
yipdw/analysand
lib/analysand/http.rb
Analysand.Http.set_credentials
def set_credentials(req, creds) return unless creds if String === creds req.add_field('Cookie', creds) elsif creds[:username] && creds[:password] req.basic_auth(creds[:username], creds[:password]) end end
ruby
def set_credentials(req, creds) return unless creds if String === creds req.add_field('Cookie', creds) elsif creds[:username] && creds[:password] req.basic_auth(creds[:username], creds[:password]) end end
[ "def", "set_credentials", "(", "req", ",", "creds", ")", "return", "unless", "creds", "if", "String", "===", "creds", "req", ".", "add_field", "(", "'Cookie'", ",", "creds", ")", "elsif", "creds", "[", ":username", "]", "&&", "creds", "[", ":password", "]", "req", ".", "basic_auth", "(", "creds", "[", ":username", "]", ",", "creds", "[", ":password", "]", ")", "end", "end" ]
Sets credentials on a request object. If creds is a hash containing :username and :password keys, HTTP basic authorization is used. If creds is a string, the string is added as a cookie.
[ "Sets", "credentials", "on", "a", "request", "object", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/http.rb#L80-L88
train
zpatten/ztk
lib/ztk/parallel.rb
ZTK.Parallel.wait
def wait(flags=0) config.ui.logger.debug { "wait" } config.ui.logger.debug { "forks(#{@forks.inspect})" } return nil if @forks.count <= 0 pid, status = (Process.wait2(-1, Process::WUNTRACED) rescue nil) if !pid.nil? && !status.nil? && !(fork = @forks.select{ |f| f[:pid] == pid }.first).nil? data = nil begin data = Marshal.load(Zlib::Inflate.inflate(Base64.decode64(fork[:reader].read).to_s)) rescue Zlib::BufError config.ui.logger.fatal { "Encountered Zlib::BufError when reading child pipe." } end config.ui.logger.debug { "read(#{data.inspect})" } data = process_data(data) !data.nil? and @results.push(data) fork[:reader].close fork[:writer].close @forks -= [fork] return [pid, status, data] end nil end
ruby
def wait(flags=0) config.ui.logger.debug { "wait" } config.ui.logger.debug { "forks(#{@forks.inspect})" } return nil if @forks.count <= 0 pid, status = (Process.wait2(-1, Process::WUNTRACED) rescue nil) if !pid.nil? && !status.nil? && !(fork = @forks.select{ |f| f[:pid] == pid }.first).nil? data = nil begin data = Marshal.load(Zlib::Inflate.inflate(Base64.decode64(fork[:reader].read).to_s)) rescue Zlib::BufError config.ui.logger.fatal { "Encountered Zlib::BufError when reading child pipe." } end config.ui.logger.debug { "read(#{data.inspect})" } data = process_data(data) !data.nil? and @results.push(data) fork[:reader].close fork[:writer].close @forks -= [fork] return [pid, status, data] end nil end
[ "def", "wait", "(", "flags", "=", "0", ")", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"wait\"", "}", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"forks(#{@forks.inspect})\"", "}", "return", "nil", "if", "@forks", ".", "count", "<=", "0", "pid", ",", "status", "=", "(", "Process", ".", "wait2", "(", "-", "1", ",", "Process", "::", "WUNTRACED", ")", "rescue", "nil", ")", "if", "!", "pid", ".", "nil?", "&&", "!", "status", ".", "nil?", "&&", "!", "(", "fork", "=", "@forks", ".", "select", "{", "|", "f", "|", "f", "[", ":pid", "]", "==", "pid", "}", ".", "first", ")", ".", "nil?", "data", "=", "nil", "begin", "data", "=", "Marshal", ".", "load", "(", "Zlib", "::", "Inflate", ".", "inflate", "(", "Base64", ".", "decode64", "(", "fork", "[", ":reader", "]", ".", "read", ")", ".", "to_s", ")", ")", "rescue", "Zlib", "::", "BufError", "config", ".", "ui", ".", "logger", ".", "fatal", "{", "\"Encountered Zlib::BufError when reading child pipe.\"", "}", "end", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"read(#{data.inspect})\"", "}", "data", "=", "process_data", "(", "data", ")", "!", "data", ".", "nil?", "and", "@results", ".", "push", "(", "data", ")", "fork", "[", ":reader", "]", ".", "close", "fork", "[", ":writer", "]", ".", "close", "@forks", "-=", "[", "fork", "]", "return", "[", "pid", ",", "status", ",", "data", "]", "end", "nil", "end" ]
Wait for a single fork to finish. If a fork successfully finishes, it's return value from the *process* block is stored into the main result set. @return [Array<pid, status, data>] An array containing the pid, status and data returned from the process block. If wait2() fails nil is returned.
[ "Wait", "for", "a", "single", "fork", "to", "finish", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/parallel.rb#L205-L232
train
zpatten/ztk
lib/ztk/parallel.rb
ZTK.Parallel.signal_all
def signal_all(signal="KILL") signaled = 0 if ([email protected]? && (@forks.count > 0)) @forks.each do |fork| begin Process.kill(signal, fork[:pid]) signaled += 1 rescue nil end end end signaled end
ruby
def signal_all(signal="KILL") signaled = 0 if ([email protected]? && (@forks.count > 0)) @forks.each do |fork| begin Process.kill(signal, fork[:pid]) signaled += 1 rescue nil end end end signaled end
[ "def", "signal_all", "(", "signal", "=", "\"KILL\"", ")", "signaled", "=", "0", "if", "(", "!", "@forks", ".", "nil?", "&&", "(", "@forks", ".", "count", ">", "0", ")", ")", "@forks", ".", "each", "do", "|", "fork", "|", "begin", "Process", ".", "kill", "(", "signal", ",", "fork", "[", ":pid", "]", ")", "signaled", "+=", "1", "rescue", "nil", "end", "end", "end", "signaled", "end" ]
Signals all forks. @return [Integer] The number of processes signaled.
[ "Signals", "all", "forks", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/parallel.rb#L248-L261
train
tylerflint/vli
lib/vli/registry.rb
Vli.Registry.register
def register(key, value=nil, &block) block = lambda { value } if value @actions[key] = block end
ruby
def register(key, value=nil, &block) block = lambda { value } if value @actions[key] = block end
[ "def", "register", "(", "key", ",", "value", "=", "nil", ",", "&", "block", ")", "block", "=", "lambda", "{", "value", "}", "if", "value", "@actions", "[", "key", "]", "=", "block", "end" ]
Register a callable by key. The callable should be given in a block which will be lazily evaluated when the action is needed. If an action by the given name already exists then it will be overwritten.
[ "Register", "a", "callable", "by", "key", "." ]
7509ae2df7fcac0325edb819866a4b3be37edede
https://github.com/tylerflint/vli/blob/7509ae2df7fcac0325edb819866a4b3be37edede/lib/vli/registry.rb#L23-L26
train
tylerflint/vli
lib/vli/registry.rb
Vli.Registry.get
def get(key) return nil if [email protected]_key?(key) return @results_cache[key] if @results_cache.has_key?(key) @results_cache[key] = @actions[key].call end
ruby
def get(key) return nil if [email protected]_key?(key) return @results_cache[key] if @results_cache.has_key?(key) @results_cache[key] = @actions[key].call end
[ "def", "get", "(", "key", ")", "return", "nil", "if", "!", "@actions", ".", "has_key?", "(", "key", ")", "return", "@results_cache", "[", "key", "]", "if", "@results_cache", ".", "has_key?", "(", "key", ")", "@results_cache", "[", "key", "]", "=", "@actions", "[", "key", "]", ".", "call", "end" ]
Get an action by the given key. This will evaluate the block given to `register` and return the resulting action stack.
[ "Get", "an", "action", "by", "the", "given", "key", "." ]
7509ae2df7fcac0325edb819866a4b3be37edede
https://github.com/tylerflint/vli/blob/7509ae2df7fcac0325edb819866a4b3be37edede/lib/vli/registry.rb#L32-L36
train
rixth/tay
lib/tay/specification_validator.rb
Tay.SpecificationValidator.check_file_presence
def check_file_presence spec.icons.values.each do |path| fail_if_not_exist "Icon", path end if spec.browser_action fail_if_not_exist "Browser action popup", spec.browser_action.popup fail_if_not_exist "Browser action icon", spec.browser_action.icon end if spec.page_action fail_if_not_exist "Page action popup", spec.page_action.popup fail_if_not_exist "Page action icon", spec.page_action.icon end if spec.packaged_app fail_if_not_exist "App launch page", spec.packaged_app.page end spec.content_scripts.each do |content_script| content_script.javascripts.each do |script_path| fail_if_not_exist "Content script javascript", script_path end content_script.stylesheets.each do |style_path| fail_if_not_exist "Content script style", style_path end end spec.background_scripts.each do |script_path| fail_if_not_exist "Background script style", script_path end fail_if_not_exist "Background page", spec.background_page fail_if_not_exist "Options page", spec.options_page spec.web_intents.each do |web_intent| fail_if_not_exist "Web intent href", web_intent.href end spec.nacl_modules.each do |nacl_module| fail_if_not_exist "NaCl module", nacl_module.path end spec.web_accessible_resources.each do |path| fail_if_not_exist "Web accessible resource", path end end
ruby
def check_file_presence spec.icons.values.each do |path| fail_if_not_exist "Icon", path end if spec.browser_action fail_if_not_exist "Browser action popup", spec.browser_action.popup fail_if_not_exist "Browser action icon", spec.browser_action.icon end if spec.page_action fail_if_not_exist "Page action popup", spec.page_action.popup fail_if_not_exist "Page action icon", spec.page_action.icon end if spec.packaged_app fail_if_not_exist "App launch page", spec.packaged_app.page end spec.content_scripts.each do |content_script| content_script.javascripts.each do |script_path| fail_if_not_exist "Content script javascript", script_path end content_script.stylesheets.each do |style_path| fail_if_not_exist "Content script style", style_path end end spec.background_scripts.each do |script_path| fail_if_not_exist "Background script style", script_path end fail_if_not_exist "Background page", spec.background_page fail_if_not_exist "Options page", spec.options_page spec.web_intents.each do |web_intent| fail_if_not_exist "Web intent href", web_intent.href end spec.nacl_modules.each do |nacl_module| fail_if_not_exist "NaCl module", nacl_module.path end spec.web_accessible_resources.each do |path| fail_if_not_exist "Web accessible resource", path end end
[ "def", "check_file_presence", "spec", ".", "icons", ".", "values", ".", "each", "do", "|", "path", "|", "fail_if_not_exist", "\"Icon\"", ",", "path", "end", "if", "spec", ".", "browser_action", "fail_if_not_exist", "\"Browser action popup\"", ",", "spec", ".", "browser_action", ".", "popup", "fail_if_not_exist", "\"Browser action icon\"", ",", "spec", ".", "browser_action", ".", "icon", "end", "if", "spec", ".", "page_action", "fail_if_not_exist", "\"Page action popup\"", ",", "spec", ".", "page_action", ".", "popup", "fail_if_not_exist", "\"Page action icon\"", ",", "spec", ".", "page_action", ".", "icon", "end", "if", "spec", ".", "packaged_app", "fail_if_not_exist", "\"App launch page\"", ",", "spec", ".", "packaged_app", ".", "page", "end", "spec", ".", "content_scripts", ".", "each", "do", "|", "content_script", "|", "content_script", ".", "javascripts", ".", "each", "do", "|", "script_path", "|", "fail_if_not_exist", "\"Content script javascript\"", ",", "script_path", "end", "content_script", ".", "stylesheets", ".", "each", "do", "|", "style_path", "|", "fail_if_not_exist", "\"Content script style\"", ",", "style_path", "end", "end", "spec", ".", "background_scripts", ".", "each", "do", "|", "script_path", "|", "fail_if_not_exist", "\"Background script style\"", ",", "script_path", "end", "fail_if_not_exist", "\"Background page\"", ",", "spec", ".", "background_page", "fail_if_not_exist", "\"Options page\"", ",", "spec", ".", "options_page", "spec", ".", "web_intents", ".", "each", "do", "|", "web_intent", "|", "fail_if_not_exist", "\"Web intent href\"", ",", "web_intent", ".", "href", "end", "spec", ".", "nacl_modules", ".", "each", "do", "|", "nacl_module", "|", "fail_if_not_exist", "\"NaCl module\"", ",", "nacl_module", ".", "path", "end", "spec", ".", "web_accessible_resources", ".", "each", "do", "|", "path", "|", "fail_if_not_exist", "\"Web accessible resource\"", ",", "path", "end", "end" ]
Go through the specification checking that files that are pointed to actually exist
[ "Go", "through", "the", "specification", "checking", "that", "files", "that", "are", "pointed", "to", "actually", "exist" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification_validator.rb#L62-L108
train
kellysutton/bliptv
lib/bliptv/request.rb
BlipTV.Request.set
def set(container, &declarations) struct = OpenStruct.new declarations.call(struct) send("#{container}=", struct.table) end
ruby
def set(container, &declarations) struct = OpenStruct.new declarations.call(struct) send("#{container}=", struct.table) end
[ "def", "set", "(", "container", ",", "&", "declarations", ")", "struct", "=", "OpenStruct", ".", "new", "declarations", ".", "call", "(", "struct", ")", "send", "(", "\"#{container}=\"", ",", "struct", ".", "table", ")", "end" ]
Use this method to setup your request's payload and headers. Example: request.set :headers do |h| h.content_type = 'application/ufo' end request.set :params do |p| p.sessionid = '12323' p.api_key = '13123 end
[ "Use", "this", "method", "to", "setup", "your", "request", "s", "payload", "and", "headers", "." ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/request.rb#L45-L49
train
kellysutton/bliptv
lib/bliptv/request.rb
BlipTV.Request.run
def run(&block) if block_given? set(:params, &block) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient::Request.execute( :method => http_method, :url => url, :headers => headers, :payload => body ) self.response = parse_response(request) end
ruby
def run(&block) if block_given? set(:params, &block) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient::Request.execute( :method => http_method, :url => url, :headers => headers, :payload => body ) self.response = parse_response(request) end
[ "def", "run", "(", "&", "block", ")", "if", "block_given?", "set", "(", ":params", ",", "&", "block", ")", "end", "if", "post?", "and", "multipart?", "put_multipart_params_into_body", "else", "put_params_into_url", "end", "request", "=", "RestClient", "::", "Request", ".", "execute", "(", ":method", "=>", "http_method", ",", ":url", "=>", "url", ",", ":headers", "=>", "headers", ",", ":payload", "=>", "body", ")", "self", ".", "response", "=", "parse_response", "(", "request", ")", "end" ]
Send http request to Viddler API.
[ "Send", "http", "request", "to", "Viddler", "API", "." ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/request.rb#L52-L70
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.authenticate
def authenticate begin @backend.transaction(true){ raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created] check_salt! } rescue OpenSSL::Cipher::CipherError raise WrongMasterPasswordError end end
ruby
def authenticate begin @backend.transaction(true){ raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created] check_salt! } rescue OpenSSL::Cipher::CipherError raise WrongMasterPasswordError end end
[ "def", "authenticate", "begin", "@backend", ".", "transaction", "(", "true", ")", "{", "raise", "NotInitializedError", ".", "new", "(", "@backend", ".", "path", ".", "path", ")", "unless", "@backend", "[", ":user", "]", "&&", "@backend", "[", ":system", "]", "&&", "@backend", "[", ":system", "]", "[", ":created", "]", "check_salt!", "}", "rescue", "OpenSSL", "::", "Cipher", "::", "CipherError", "raise", "WrongMasterPasswordError", "end", "end" ]
Check that the master password is correct. This is done to prevent opening an existing but blank locker with the wrong password.
[ "Check", "that", "the", "master", "password", "is", "correct", ".", "This", "is", "done", "to", "prevent", "opening", "an", "existing", "but", "blank", "locker", "with", "the", "wrong", "password", "." ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L116-L125
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.get
def get(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_accessed) value = @backend[:user][encrypt(key)] raise KeyNotFoundError.new(key) unless value EntryMapper.from_json(decrypt(value)) } end
ruby
def get(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_accessed) value = @backend[:user][encrypt(key)] raise KeyNotFoundError.new(key) unless value EntryMapper.from_json(decrypt(value)) } end
[ "def", "get", "(", "key", ")", "raise", "BlankKeyError", "if", "key", ".", "blank?", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_accessed", ")", "value", "=", "@backend", "[", ":user", "]", "[", "encrypt", "(", "key", ")", "]", "raise", "KeyNotFoundError", ".", "new", "(", "key", ")", "unless", "value", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "value", ")", ")", "}", "end" ]
Return the value stored under key
[ "Return", "the", "value", "stored", "under", "key" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L130-L138
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.add
def add(entry_or_key, value = nil) if value.nil? and entry_or_key.is_a?(Entry) # treat as entry entry = entry_or_key else entry = Entry.new(entry_or_key) entry.password = value end entry.validate! @backend.transaction{ timestamp!(:last_modified) @backend[:user][encrypt(entry.name)] = encrypt(EntryMapper.to_json(entry)) } end
ruby
def add(entry_or_key, value = nil) if value.nil? and entry_or_key.is_a?(Entry) # treat as entry entry = entry_or_key else entry = Entry.new(entry_or_key) entry.password = value end entry.validate! @backend.transaction{ timestamp!(:last_modified) @backend[:user][encrypt(entry.name)] = encrypt(EntryMapper.to_json(entry)) } end
[ "def", "add", "(", "entry_or_key", ",", "value", "=", "nil", ")", "if", "value", ".", "nil?", "and", "entry_or_key", ".", "is_a?", "(", "Entry", ")", "entry", "=", "entry_or_key", "else", "entry", "=", "Entry", ".", "new", "(", "entry_or_key", ")", "entry", ".", "password", "=", "value", "end", "entry", ".", "validate!", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_modified", ")", "@backend", "[", ":user", "]", "[", "encrypt", "(", "entry", ".", "name", ")", "]", "=", "encrypt", "(", "EntryMapper", ".", "to_json", "(", "entry", ")", ")", "}", "end" ]
Store entry or value under key
[ "Store", "entry", "or", "value", "under", "key" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L143-L157
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.delete
def delete(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_modified) old_value = @backend[:user].delete(encrypt(key)) raise KeyNotFoundError.new(key) unless old_value EntryMapper.from_json(decrypt(old_value)) } end
ruby
def delete(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_modified) old_value = @backend[:user].delete(encrypt(key)) raise KeyNotFoundError.new(key) unless old_value EntryMapper.from_json(decrypt(old_value)) } end
[ "def", "delete", "(", "key", ")", "raise", "BlankKeyError", "if", "key", ".", "blank?", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_modified", ")", "old_value", "=", "@backend", "[", ":user", "]", ".", "delete", "(", "encrypt", "(", "key", ")", ")", "raise", "KeyNotFoundError", ".", "new", "(", "key", ")", "unless", "old_value", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "old_value", ")", ")", "}", "end" ]
Delete the value that is stored under key and return it
[ "Delete", "the", "value", "that", "is", "stored", "under", "key", "and", "return", "it" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L162-L170
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.all
def all result = [] @backend.transaction(true){ @backend[:user].each{|k,v| result << EntryMapper.from_json(decrypt(v))} } result end
ruby
def all result = [] @backend.transaction(true){ @backend[:user].each{|k,v| result << EntryMapper.from_json(decrypt(v))} } result end
[ "def", "all", "result", "=", "[", "]", "@backend", ".", "transaction", "(", "true", ")", "{", "@backend", "[", ":user", "]", ".", "each", "{", "|", "k", ",", "v", "|", "result", "<<", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "v", ")", ")", "}", "}", "result", "end" ]
Return all entries as array
[ "Return", "all", "entries", "as", "array" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L190-L196
train
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.change_password!
def change_password!(new_master_password) self.class.password_policy.validate!(new_master_password) @backend.transaction{ # Decrypt each key and value with the old master password and encrypt them with the new master password copy = {} @backend[:user].each{|k,v| # No need to (de)serialize - the value comes in as JSON and goes out as JSON new_key = Encryptor.encrypt(decrypt(k), :key => new_master_password) new_val = Encryptor.encrypt(decrypt(v), :key => new_master_password) copy[new_key] = new_val } # re-write user branch with newly encrypted keys and values @backend[:user] = copy # from now on, use the new master password as long as the object lives @master_password = new_master_password timestamp!(:last_modified) @backend[:system][:salt] = encrypt(Random.rand.to_s) } end
ruby
def change_password!(new_master_password) self.class.password_policy.validate!(new_master_password) @backend.transaction{ # Decrypt each key and value with the old master password and encrypt them with the new master password copy = {} @backend[:user].each{|k,v| # No need to (de)serialize - the value comes in as JSON and goes out as JSON new_key = Encryptor.encrypt(decrypt(k), :key => new_master_password) new_val = Encryptor.encrypt(decrypt(v), :key => new_master_password) copy[new_key] = new_val } # re-write user branch with newly encrypted keys and values @backend[:user] = copy # from now on, use the new master password as long as the object lives @master_password = new_master_password timestamp!(:last_modified) @backend[:system][:salt] = encrypt(Random.rand.to_s) } end
[ "def", "change_password!", "(", "new_master_password", ")", "self", ".", "class", ".", "password_policy", ".", "validate!", "(", "new_master_password", ")", "@backend", ".", "transaction", "{", "copy", "=", "{", "}", "@backend", "[", ":user", "]", ".", "each", "{", "|", "k", ",", "v", "|", "new_key", "=", "Encryptor", ".", "encrypt", "(", "decrypt", "(", "k", ")", ",", ":key", "=>", "new_master_password", ")", "new_val", "=", "Encryptor", ".", "encrypt", "(", "decrypt", "(", "v", ")", ",", ":key", "=>", "new_master_password", ")", "copy", "[", "new_key", "]", "=", "new_val", "}", "@backend", "[", ":user", "]", "=", "copy", "@master_password", "=", "new_master_password", "timestamp!", "(", ":last_modified", ")", "@backend", "[", ":system", "]", "[", ":salt", "]", "=", "encrypt", "(", "Random", ".", "rand", ".", "to_s", ")", "}", "end" ]
Change the master password to +new_master_password+. Note that we don't take a password confirmation here. This is up to a UI layer.
[ "Change", "the", "master", "password", "to", "+", "new_master_password", "+", ".", "Note", "that", "we", "don", "t", "take", "a", "password", "confirmation", "here", ".", "This", "is", "up", "to", "a", "UI", "layer", "." ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L202-L224
train
vojto/active_harmony
lib/active_harmony/synchronizer.rb
ActiveHarmony.Synchronizer.pull_object
def pull_object(id) local_object = @factory.with_remote_id(id) if local_object # FIXME What if there's no local object and we still want to set some # contexts? @service.set_contexts(local_object.contexts) else local_object = @factory.new end local_object.before_pull(self) if local_object.respond_to?(:before_pull) object_hash = @service.show(object_name, id) @service.clear_contexts local_object._remote_id = object_hash.delete('id') fields = configuration.synchronizable_for_pull fields.each do |key| value = object_hash[key.to_s] local_object.send("#{key}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end
ruby
def pull_object(id) local_object = @factory.with_remote_id(id) if local_object # FIXME What if there's no local object and we still want to set some # contexts? @service.set_contexts(local_object.contexts) else local_object = @factory.new end local_object.before_pull(self) if local_object.respond_to?(:before_pull) object_hash = @service.show(object_name, id) @service.clear_contexts local_object._remote_id = object_hash.delete('id') fields = configuration.synchronizable_for_pull fields.each do |key| value = object_hash[key.to_s] local_object.send("#{key}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end
[ "def", "pull_object", "(", "id", ")", "local_object", "=", "@factory", ".", "with_remote_id", "(", "id", ")", "if", "local_object", "@service", ".", "set_contexts", "(", "local_object", ".", "contexts", ")", "else", "local_object", "=", "@factory", ".", "new", "end", "local_object", ".", "before_pull", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":before_pull", ")", "object_hash", "=", "@service", ".", "show", "(", "object_name", ",", "id", ")", "@service", ".", "clear_contexts", "local_object", ".", "_remote_id", "=", "object_hash", ".", "delete", "(", "'id'", ")", "fields", "=", "configuration", ".", "synchronizable_for_pull", "fields", ".", "each", "do", "|", "key", "|", "value", "=", "object_hash", "[", "key", ".", "to_s", "]", "local_object", ".", "send", "(", "\"#{key}=\"", ",", "value", ")", "end", "local_object", ".", "after_pull", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":after_pull", ")", "local_object", ".", "save", "end" ]
Pulls object from remote service @param [Integer] Remote ID of object. @return [Boolean] Result of pulling
[ "Pulls", "object", "from", "remote", "service" ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/synchronizer.rb#L41-L61
train
vojto/active_harmony
lib/active_harmony/synchronizer.rb
ActiveHarmony.Synchronizer.push_object
def push_object(local_object) object_name = @factory.object_name.to_sym local_object.before_push(self) if local_object.respond_to?(:before_push) changes = {} fields = configuration.synchronizable_for_push fields.each do |atr| value = local_object.send(atr) changes[atr.to_s] = value end @service.set_contexts(local_object.contexts) if local_object._remote_id @service.update(object_name, local_object._remote_id, changes) else result = @service.create(object_name, changes) if result local_object._remote_id = result['id'] fields = configuration.synchronizable_for_pull fields.each do |atr| local_object.write_attribute(atr, result[atr.to_s]) end local_object.save end end local_object.after_push(self) if local_object.respond_to?(:after_push) @service.clear_contexts end
ruby
def push_object(local_object) object_name = @factory.object_name.to_sym local_object.before_push(self) if local_object.respond_to?(:before_push) changes = {} fields = configuration.synchronizable_for_push fields.each do |atr| value = local_object.send(atr) changes[atr.to_s] = value end @service.set_contexts(local_object.contexts) if local_object._remote_id @service.update(object_name, local_object._remote_id, changes) else result = @service.create(object_name, changes) if result local_object._remote_id = result['id'] fields = configuration.synchronizable_for_pull fields.each do |atr| local_object.write_attribute(atr, result[atr.to_s]) end local_object.save end end local_object.after_push(self) if local_object.respond_to?(:after_push) @service.clear_contexts end
[ "def", "push_object", "(", "local_object", ")", "object_name", "=", "@factory", ".", "object_name", ".", "to_sym", "local_object", ".", "before_push", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":before_push", ")", "changes", "=", "{", "}", "fields", "=", "configuration", ".", "synchronizable_for_push", "fields", ".", "each", "do", "|", "atr", "|", "value", "=", "local_object", ".", "send", "(", "atr", ")", "changes", "[", "atr", ".", "to_s", "]", "=", "value", "end", "@service", ".", "set_contexts", "(", "local_object", ".", "contexts", ")", "if", "local_object", ".", "_remote_id", "@service", ".", "update", "(", "object_name", ",", "local_object", ".", "_remote_id", ",", "changes", ")", "else", "result", "=", "@service", ".", "create", "(", "object_name", ",", "changes", ")", "if", "result", "local_object", ".", "_remote_id", "=", "result", "[", "'id'", "]", "fields", "=", "configuration", ".", "synchronizable_for_pull", "fields", ".", "each", "do", "|", "atr", "|", "local_object", ".", "write_attribute", "(", "atr", ",", "result", "[", "atr", ".", "to_s", "]", ")", "end", "local_object", ".", "save", "end", "end", "local_object", ".", "after_push", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":after_push", ")", "@service", ".", "clear_contexts", "end" ]
Pushes local object to remote services. Er, I mean, its attributes. Like not object itself. Just attributes. @param [Object] Local object
[ "Pushes", "local", "object", "to", "remote", "services", ".", "Er", "I", "mean", "its", "attributes", ".", "Like", "not", "object", "itself", ".", "Just", "attributes", "." ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/synchronizer.rb#L68-L98
train
vojto/active_harmony
lib/active_harmony/synchronizer.rb
ActiveHarmony.Synchronizer.pull_collection
def pull_collection @service.set_contexts(@contexts) collection = @service.list(object_name) @service.clear_contexts collection.each_with_index do |remote_object_hash, index| remote_id = remote_object_hash.delete("id") local_object = @factory.with_remote_id(remote_id) unless local_object local_object = @factory.new local_object.update_remote_id(remote_id) end local_object.before_pull(self) if local_object.respond_to?(:before_pull) local_object._collection_order = index fields = configuration.synchronizable_for_pull fields.each do |field| value = remote_object_hash[field.to_s] local_object.send("#{field}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end collection.count end
ruby
def pull_collection @service.set_contexts(@contexts) collection = @service.list(object_name) @service.clear_contexts collection.each_with_index do |remote_object_hash, index| remote_id = remote_object_hash.delete("id") local_object = @factory.with_remote_id(remote_id) unless local_object local_object = @factory.new local_object.update_remote_id(remote_id) end local_object.before_pull(self) if local_object.respond_to?(:before_pull) local_object._collection_order = index fields = configuration.synchronizable_for_pull fields.each do |field| value = remote_object_hash[field.to_s] local_object.send("#{field}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end collection.count end
[ "def", "pull_collection", "@service", ".", "set_contexts", "(", "@contexts", ")", "collection", "=", "@service", ".", "list", "(", "object_name", ")", "@service", ".", "clear_contexts", "collection", ".", "each_with_index", "do", "|", "remote_object_hash", ",", "index", "|", "remote_id", "=", "remote_object_hash", ".", "delete", "(", "\"id\"", ")", "local_object", "=", "@factory", ".", "with_remote_id", "(", "remote_id", ")", "unless", "local_object", "local_object", "=", "@factory", ".", "new", "local_object", ".", "update_remote_id", "(", "remote_id", ")", "end", "local_object", ".", "before_pull", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":before_pull", ")", "local_object", ".", "_collection_order", "=", "index", "fields", "=", "configuration", ".", "synchronizable_for_pull", "fields", ".", "each", "do", "|", "field", "|", "value", "=", "remote_object_hash", "[", "field", ".", "to_s", "]", "local_object", ".", "send", "(", "\"#{field}=\"", ",", "value", ")", "end", "local_object", ".", "after_pull", "(", "self", ")", "if", "local_object", ".", "respond_to?", "(", ":after_pull", ")", "local_object", ".", "save", "end", "collection", ".", "count", "end" ]
Pulls whole remote collection. If it cannot find matching local object, it will create one. This method is slow, useful for initial import, not for regular updates. For regular updates, only changed remote objects should be updates using pull_object @see pull_object
[ "Pulls", "whole", "remote", "collection", ".", "If", "it", "cannot", "find", "matching", "local", "object", "it", "will", "create", "one", ".", "This", "method", "is", "slow", "useful", "for", "initial", "import", "not", "for", "regular", "updates", ".", "For", "regular", "updates", "only", "changed", "remote", "objects", "should", "be", "updates", "using", "pull_object" ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/synchronizer.rb#L107-L129
train
26fe/sem4r
lib/sem4r/ad_group/ad_group.rb
Sem4r.AdGroup.xml
def xml(t) t.campaignId campaign.id t.name name t.status "ENABLED" @bids.to_xml(t) if @bids end
ruby
def xml(t) t.campaignId campaign.id t.name name t.status "ENABLED" @bids.to_xml(t) if @bids end
[ "def", "xml", "(", "t", ")", "t", ".", "campaignId", "campaign", ".", "id", "t", ".", "name", "name", "t", ".", "status", "\"ENABLED\"", "@bids", ".", "to_xml", "(", "t", ")", "if", "@bids", "end" ]
Build xml into Builder @param [Builder::XmlMarkup]
[ "Build", "xml", "into", "Builder" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/ad_group/ad_group.rb#L72-L77
train
26fe/sem4r
lib/sem4r/ad_group/ad_group.rb
Sem4r.AdGroup.keyword
def keyword(text = nil, match = nil, &block) biddable_criterion = BiddableAdGroupCriterion.new(self) criterion = CriterionKeyword.new(self, text, match, &block) biddable_criterion.criterion = criterion @criterions ||= [] @criterions.push( biddable_criterion ) biddable_criterion end
ruby
def keyword(text = nil, match = nil, &block) biddable_criterion = BiddableAdGroupCriterion.new(self) criterion = CriterionKeyword.new(self, text, match, &block) biddable_criterion.criterion = criterion @criterions ||= [] @criterions.push( biddable_criterion ) biddable_criterion end
[ "def", "keyword", "(", "text", "=", "nil", ",", "match", "=", "nil", ",", "&", "block", ")", "biddable_criterion", "=", "BiddableAdGroupCriterion", ".", "new", "(", "self", ")", "criterion", "=", "CriterionKeyword", ".", "new", "(", "self", ",", "text", ",", "match", ",", "&", "block", ")", "biddable_criterion", ".", "criterion", "=", "criterion", "@criterions", "||=", "[", "]", "@criterions", ".", "push", "(", "biddable_criterion", ")", "biddable_criterion", "end" ]
instantiate an BiddableAdGroupCriterion but it is called 'keyword' for convenience http://code.google.com/apis/adwords/v2009/docs/reference/AdGroupCriterionService.BiddableAdGroupCriterion.html
[ "instantiate", "an", "BiddableAdGroupCriterion", "but", "it", "is", "called", "keyword", "for", "convenience" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/ad_group/ad_group.rb#L246-L253
train
26fe/sem4r
lib/sem4r/ad_group/ad_group.rb
Sem4r.AdGroup.ad_param
def ad_param(criterion, index = nil, text = nil, &block) ad_param = AdParam.new(self, criterion, index, text, &block) ad_param.save unless inside_initialize? or criterion.inside_initialize? @ad_params ||= [] @ad_params.push( ad_param ) ad_param end
ruby
def ad_param(criterion, index = nil, text = nil, &block) ad_param = AdParam.new(self, criterion, index, text, &block) ad_param.save unless inside_initialize? or criterion.inside_initialize? @ad_params ||= [] @ad_params.push( ad_param ) ad_param end
[ "def", "ad_param", "(", "criterion", ",", "index", "=", "nil", ",", "text", "=", "nil", ",", "&", "block", ")", "ad_param", "=", "AdParam", ".", "new", "(", "self", ",", "criterion", ",", "index", ",", "text", ",", "&", "block", ")", "ad_param", ".", "save", "unless", "inside_initialize?", "or", "criterion", ".", "inside_initialize?", "@ad_params", "||=", "[", "]", "@ad_params", ".", "push", "(", "ad_param", ")", "ad_param", "end" ]
ad param management
[ "ad", "param", "management" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/ad_group/ad_group.rb#L317-L323
train
boof/xbel
lib/nokogiri/decorators/xbel/folder.rb
Nokogiri::Decorators::XBEL.Folder.add_bookmark
def add_bookmark(title, href, attributes = {}, &block) attributes = attributes.merge :title => title, :href => href add_child build(:bookmark, attributes, &block) end
ruby
def add_bookmark(title, href, attributes = {}, &block) attributes = attributes.merge :title => title, :href => href add_child build(:bookmark, attributes, &block) end
[ "def", "add_bookmark", "(", "title", ",", "href", ",", "attributes", "=", "{", "}", ",", "&", "block", ")", "attributes", "=", "attributes", ".", "merge", ":title", "=>", "title", ",", ":href", "=>", "href", "add_child", "build", "(", ":bookmark", ",", "attributes", ",", "&", "block", ")", "end" ]
Builds a bookmark with given attributes and add it.
[ "Builds", "a", "bookmark", "with", "given", "attributes", "and", "add", "it", "." ]
a1997a0ff61e99f390cc4f05ef9ec4757557048e
https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel/folder.rb#L46-L49
train
boof/xbel
lib/nokogiri/decorators/xbel/folder.rb
Nokogiri::Decorators::XBEL.Folder.add_folder
def add_folder(title, attributes = {}, &block) attributes = attributes.merge :title => title add_child build(:folder, attributes, &block) end
ruby
def add_folder(title, attributes = {}, &block) attributes = attributes.merge :title => title add_child build(:folder, attributes, &block) end
[ "def", "add_folder", "(", "title", ",", "attributes", "=", "{", "}", ",", "&", "block", ")", "attributes", "=", "attributes", ".", "merge", ":title", "=>", "title", "add_child", "build", "(", ":folder", ",", "attributes", ",", "&", "block", ")", "end" ]
Builds a folder with given attributes and add it.
[ "Builds", "a", "folder", "with", "given", "attributes", "and", "add", "it", "." ]
a1997a0ff61e99f390cc4f05ef9ec4757557048e
https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel/folder.rb#L51-L54
train
boof/xbel
lib/nokogiri/decorators/xbel/folder.rb
Nokogiri::Decorators::XBEL.Folder.add_alias
def add_alias(ref) node = Nokogiri::XML::Node.new 'alias', document node.ref = (Entry === ref) ? ref.id : ref.to_s add_child node end
ruby
def add_alias(ref) node = Nokogiri::XML::Node.new 'alias', document node.ref = (Entry === ref) ? ref.id : ref.to_s add_child node end
[ "def", "add_alias", "(", "ref", ")", "node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "'alias'", ",", "document", "node", ".", "ref", "=", "(", "Entry", "===", "ref", ")", "?", "ref", ".", "id", ":", "ref", ".", "to_s", "add_child", "node", "end" ]
Builds an alias with given attributes and add it.
[ "Builds", "an", "alias", "with", "given", "attributes", "and", "add", "it", "." ]
a1997a0ff61e99f390cc4f05ef9ec4757557048e
https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel/folder.rb#L56-L61
train
StormhelmSoftworks/specfacthor
lib/specfac.rb
Specfac.CLI.generate
def generate(*args) init_vars(options) controller = args.shift actions = args if controller sanitize(controller, actions, options) else puts "Please provide a controller name." exit end end
ruby
def generate(*args) init_vars(options) controller = args.shift actions = args if controller sanitize(controller, actions, options) else puts "Please provide a controller name." exit end end
[ "def", "generate", "(", "*", "args", ")", "init_vars", "(", "options", ")", "controller", "=", "args", ".", "shift", "actions", "=", "args", "if", "controller", "sanitize", "(", "controller", ",", "actions", ",", "options", ")", "else", "puts", "\"Please provide a controller name.\"", "exit", "end", "end" ]
end to end tests
[ "end", "to", "end", "tests" ]
8fb36d7e44b12183dc18954bc9f80c04b46b7f6d
https://github.com/StormhelmSoftworks/specfacthor/blob/8fb36d7e44b12183dc18954bc9f80c04b46b7f6d/lib/specfac.rb#L86-L98
train
kristianmandrup/rails3_artifactor
lib/rails3_artifactor/base/crud/create.rb
Rails3::Assist::Artifact::CRUD.Create.new_artifact_content
def new_artifact_content name, options = {}, &block type = get_type(options) content = extract_content type, options, &block %Q{class #{marker(name, type)} #{content} end} end
ruby
def new_artifact_content name, options = {}, &block type = get_type(options) content = extract_content type, options, &block %Q{class #{marker(name, type)} #{content} end} end
[ "def", "new_artifact_content", "name", ",", "options", "=", "{", "}", ",", "&", "block", "type", "=", "get_type", "(", "options", ")", "content", "=", "extract_content", "type", ",", "options", ",", "&", "block", "%Q{class #{marker(name, type)} #{content}end}", "end" ]
def new_artifact_content name, type, content=nil, &block
[ "def", "new_artifact_content", "name", "type", "content", "=", "nil", "&block" ]
79500e011e022042ab9f9115c6df91b6d63f3b3d
https://github.com/kristianmandrup/rails3_artifactor/blob/79500e011e022042ab9f9115c6df91b6d63f3b3d/lib/rails3_artifactor/base/crud/create.rb#L39-L45
train
Figure53/qlab-ruby
lib/qlab-ruby/reply.rb
QLab.Reply.json
def json @json ||= begin JSON.parse(osc_message.to_a.first) rescue => ex puts ex.message {} end end
ruby
def json @json ||= begin JSON.parse(osc_message.to_a.first) rescue => ex puts ex.message {} end end
[ "def", "json", "@json", "||=", "begin", "JSON", ".", "parse", "(", "osc_message", ".", "to_a", ".", "first", ")", "rescue", "=>", "ex", "puts", "ex", ".", "message", "{", "}", "end", "end" ]
Actually perform the message unpacking
[ "Actually", "perform", "the", "message", "unpacking" ]
169494940f478b897066db4c15f130769aa43243
https://github.com/Figure53/qlab-ruby/blob/169494940f478b897066db4c15f130769aa43243/lib/qlab-ruby/reply.rb#L41-L48
train
michaelmior/mipper
lib/mipper/glpk/model.rb
MIPPeR.GLPKModel.glpk_type
def glpk_type(type) case type when :integer GLPK::GLP_IV when :binary GLPK::GLP_BV when :continuous GLPK::GLP_CV else fail type end end
ruby
def glpk_type(type) case type when :integer GLPK::GLP_IV when :binary GLPK::GLP_BV when :continuous GLPK::GLP_CV else fail type end end
[ "def", "glpk_type", "(", "type", ")", "case", "type", "when", ":integer", "GLPK", "::", "GLP_IV", "when", ":binary", "GLPK", "::", "GLP_BV", "when", ":continuous", "GLPK", "::", "GLP_CV", "else", "fail", "type", "end", "end" ]
Get the constant GLPK uses to represent our variable types
[ "Get", "the", "constant", "GLPK", "uses", "to", "represent", "our", "variable", "types" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/glpk/model.rb#L184-L195
train
jeremyvdw/disqussion
lib/disqussion/client/applications.rb
Disqussion.Applications.listUsage
def listUsage(*args) options = args.last.is_a?(Hash) ? args.pop : {} get('applications/listUsage', options) end
ruby
def listUsage(*args) options = args.last.is_a?(Hash) ? args.pop : {} get('applications/listUsage', options) end
[ "def", "listUsage", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "get", "(", "'applications/listUsage'", ",", "options", ")", "end" ]
Returns the API usage per day for this application. @accessibility: public key, secret key @methods: GET @format: json, jsonp @authenticated: true @limited: false @return [Hashie::Rash] API usage per day for this application. @param application [Integer] Defaults to null @param days [Integer] Defaults to 30, Maximum length of 30 @example Returns the API usage per day for this application. Disqussion::Client.applications.listUsage @see http://disqus.com/api/3.0/applications/listUsage.json
[ "Returns", "the", "API", "usage", "per", "day", "for", "this", "application", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/applications.rb#L15-L18
train
cajun/smile
lib/smile/smug.rb
Smile.Smug.auth
def auth( email, pass ) json = secure_web_method_call( { :method => 'smugmug.login.withPassword', :EmailAddress => email, :Password => pass } ) self.session.id = json["login"]["session"]["id"] json end
ruby
def auth( email, pass ) json = secure_web_method_call( { :method => 'smugmug.login.withPassword', :EmailAddress => email, :Password => pass } ) self.session.id = json["login"]["session"]["id"] json end
[ "def", "auth", "(", "email", ",", "pass", ")", "json", "=", "secure_web_method_call", "(", "{", ":method", "=>", "'smugmug.login.withPassword'", ",", ":EmailAddress", "=>", "email", ",", ":Password", "=>", "pass", "}", ")", "self", ".", "session", ".", "id", "=", "json", "[", "\"login\"", "]", "[", "\"session\"", "]", "[", "\"id\"", "]", "json", "end" ]
Login to SmugMug using a specific user account. @param [String] email The username ( Nickname ) for the SmugMug account @param [String] password The password for the SmugMug account @return [Smile::SmugMug.new] An Smug object that has been authenticated
[ "Login", "to", "SmugMug", "using", "a", "specific", "user", "account", "." ]
5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6
https://github.com/cajun/smile/blob/5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6/lib/smile/smug.rb#L16-L26
train
hackersrc/hs-cli
lib/hs/models/course.rb
HS.Course.find_chapter
def find_chapter(slug) chapters.find { |c| c.slug.to_s == slug.to_s } end
ruby
def find_chapter(slug) chapters.find { |c| c.slug.to_s == slug.to_s } end
[ "def", "find_chapter", "(", "slug", ")", "chapters", ".", "find", "{", "|", "c", "|", "c", ".", "slug", ".", "to_s", "==", "slug", ".", "to_s", "}", "end" ]
Tries to find chapter in this course by chapter slug.
[ "Tries", "to", "find", "chapter", "in", "this", "course", "by", "chapter", "slug", "." ]
018367cab5e8d324f2097e79faaf71819390eccc
https://github.com/hackersrc/hs-cli/blob/018367cab5e8d324f2097e79faaf71819390eccc/lib/hs/models/course.rb#L32-L34
train
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.parse
def parse tags = [] while tokens = @tokenizer.read_line_tokens() if tokens.last.type == :START_BLOCK # tag with a block tag = construct_tag(tokens[0...-1]) add_children(tag) tags << tag elsif tokens.first.type == :END_BLOCK # we found an block end token that should have been consumed by # add_children() normally parse_error( "No opening block ({) for close block (}).", tokens.first.line, tokens.first.position) else # tag without block tags << construct_tag(tokens) end end @tokenizer.close() return tags end
ruby
def parse tags = [] while tokens = @tokenizer.read_line_tokens() if tokens.last.type == :START_BLOCK # tag with a block tag = construct_tag(tokens[0...-1]) add_children(tag) tags << tag elsif tokens.first.type == :END_BLOCK # we found an block end token that should have been consumed by # add_children() normally parse_error( "No opening block ({) for close block (}).", tokens.first.line, tokens.first.position) else # tag without block tags << construct_tag(tokens) end end @tokenizer.close() return tags end
[ "def", "parse", "tags", "=", "[", "]", "while", "tokens", "=", "@tokenizer", ".", "read_line_tokens", "(", ")", "if", "tokens", ".", "last", ".", "type", "==", ":START_BLOCK", "tag", "=", "construct_tag", "(", "tokens", "[", "0", "...", "-", "1", "]", ")", "add_children", "(", "tag", ")", "tags", "<<", "tag", "elsif", "tokens", ".", "first", ".", "type", "==", ":END_BLOCK", "parse_error", "(", "\"No opening block ({) for close block (}).\"", ",", "tokens", ".", "first", ".", "line", ",", "tokens", ".", "first", ".", "position", ")", "else", "tags", "<<", "construct_tag", "(", "tokens", ")", "end", "end", "@tokenizer", ".", "close", "(", ")", "return", "tags", "end" ]
Creates an SDL parser on the specified +IO+. IO.open("path/to/sdl_file") { |io| parser = SDL4R::Parser.new(io) tags = parser.parse() } Parses the underlying +IO+ and returns an +Array+ of +Tag+. ==Errors [IOError] If a problem is encountered with the IO [SdlParseError] If the document is malformed
[ "Creates", "an", "SDL", "parser", "on", "the", "specified", "+", "IO", "+", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L70-L96
train
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.add_children
def add_children(parent) while tokens = @tokenizer.read_line_tokens() if tokens.first.type == :END_BLOCK return elsif tokens.last.type == :START_BLOCK # found a child with a block tag = construct_tag(tokens[0...-1]); add_children(tag) parent.add_child(tag) else parent.add_child(construct_tag(tokens)) end end parse_error("No close block (}).", @tokenizer.line_no, UNKNOWN_POSITION) end
ruby
def add_children(parent) while tokens = @tokenizer.read_line_tokens() if tokens.first.type == :END_BLOCK return elsif tokens.last.type == :START_BLOCK # found a child with a block tag = construct_tag(tokens[0...-1]); add_children(tag) parent.add_child(tag) else parent.add_child(construct_tag(tokens)) end end parse_error("No close block (}).", @tokenizer.line_no, UNKNOWN_POSITION) end
[ "def", "add_children", "(", "parent", ")", "while", "tokens", "=", "@tokenizer", ".", "read_line_tokens", "(", ")", "if", "tokens", ".", "first", ".", "type", "==", ":END_BLOCK", "return", "elsif", "tokens", ".", "last", ".", "type", "==", ":START_BLOCK", "tag", "=", "construct_tag", "(", "tokens", "[", "0", "...", "-", "1", "]", ")", ";", "add_children", "(", "tag", ")", "parent", ".", "add_child", "(", "tag", ")", "else", "parent", ".", "add_child", "(", "construct_tag", "(", "tokens", ")", ")", "end", "end", "parse_error", "(", "\"No close block (}).\"", ",", "@tokenizer", ".", "line_no", ",", "UNKNOWN_POSITION", ")", "end" ]
Parses the children tags of +parent+ until an end of block is found.
[ "Parses", "the", "children", "tags", "of", "+", "parent", "+", "until", "an", "end", "of", "block", "is", "found", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L112-L129
train
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.combine
def combine(date, time_span_with_zone) time_zone_offset = time_span_with_zone.time_zone_offset time_zone_offset = TimeSpanWithZone.default_time_zone_offset if time_zone_offset.nil? new_date_time( date.year, date.month, date.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec, time_zone_offset) end
ruby
def combine(date, time_span_with_zone) time_zone_offset = time_span_with_zone.time_zone_offset time_zone_offset = TimeSpanWithZone.default_time_zone_offset if time_zone_offset.nil? new_date_time( date.year, date.month, date.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec, time_zone_offset) end
[ "def", "combine", "(", "date", ",", "time_span_with_zone", ")", "time_zone_offset", "=", "time_span_with_zone", ".", "time_zone_offset", "time_zone_offset", "=", "TimeSpanWithZone", ".", "default_time_zone_offset", "if", "time_zone_offset", ".", "nil?", "new_date_time", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "time_span_with_zone", ".", "hour", ",", "time_span_with_zone", ".", "min", ",", "time_span_with_zone", ".", "sec", ",", "time_zone_offset", ")", "end" ]
Combines a simple Date with a TimeSpanWithZone to create a DateTime
[ "Combines", "a", "simple", "Date", "with", "a", "TimeSpanWithZone", "to", "create", "a", "DateTime" ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L417-L429
train
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.expecting_but_got
def expecting_but_got(expecting, got, line, position) @tokenizer.expecting_but_got(expecting, got, line, position) end
ruby
def expecting_but_got(expecting, got, line, position) @tokenizer.expecting_but_got(expecting, got, line, position) end
[ "def", "expecting_but_got", "(", "expecting", ",", "got", ",", "line", ",", "position", ")", "@tokenizer", ".", "expecting_but_got", "(", "expecting", ",", "got", ",", "line", ",", "position", ")", "end" ]
Close the reader and throw a SdlParseError using the format Was expecting X but got Y.
[ "Close", "the", "reader", "and", "throw", "a", "SdlParseError", "using", "the", "format", "Was", "expecting", "X", "but", "got", "Y", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L648-L650
train
rikas/tracinho
lib/tracinho/complement_builder.rb
Tracinho.ComplementBuilder.build
def build text = @word.hyphenated? ? remove_dash(@word.to_s) : add_dash(@word.to_s) Word.new(text) end
ruby
def build text = @word.hyphenated? ? remove_dash(@word.to_s) : add_dash(@word.to_s) Word.new(text) end
[ "def", "build", "text", "=", "@word", ".", "hyphenated?", "?", "remove_dash", "(", "@word", ".", "to_s", ")", ":", "add_dash", "(", "@word", ".", "to_s", ")", "Word", ".", "new", "(", "text", ")", "end" ]
Builds the complementary word. ComplementBuilder.new(Word.new('fizeste')).build # => #<Tracinho::Word:0x007f8a9b0ba928 @text="fize-te"> ComplementBuilder.new(Word.new('passa-mos')).build # => #<Tracinho::Word:0x007f8a9b10f270 @text="passamos">
[ "Builds", "the", "complementary", "word", "." ]
2d0abfec5da8fd24ba4dc72480401cd5adbf5fac
https://github.com/rikas/tracinho/blob/2d0abfec5da8fd24ba4dc72480401cd5adbf5fac/lib/tracinho/complement_builder.rb#L17-L21
train
elgalu/strongly_typed
lib/strongly_typed/model.rb
StronglyTyped.Model.initialize_from_hash
def initialize_from_hash(hsh) hsh.first.each_pair do |k, v| if self.class.members.include?(k.to_sym) self.public_send("#{k}=", v) else raise NameError, "Trying to assign non-existing member #{k}=#{v}" end end end
ruby
def initialize_from_hash(hsh) hsh.first.each_pair do |k, v| if self.class.members.include?(k.to_sym) self.public_send("#{k}=", v) else raise NameError, "Trying to assign non-existing member #{k}=#{v}" end end end
[ "def", "initialize_from_hash", "(", "hsh", ")", "hsh", ".", "first", ".", "each_pair", "do", "|", "k", ",", "v", "|", "if", "self", ".", "class", ".", "members", ".", "include?", "(", "k", ".", "to_sym", ")", "self", ".", "public_send", "(", "\"#{k}=\"", ",", "v", ")", "else", "raise", "NameError", ",", "\"Trying to assign non-existing member #{k}=#{v}\"", "end", "end", "end" ]
Entity constructor from a Hash @param [Hash] hsh hash of values @example class Person include StronglyTyped::Model attribute :id, Integer attribute :slug, String end Person.new(id: 1, slug: 'elgalu') #=> #<Person:0x00c98 @id=1, @slug="elgalu"> leo.id #=> 1 leo.slug #=> "elgalu" @raise [NameError] if tries to assign a non-existing member @private
[ "Entity", "constructor", "from", "a", "Hash" ]
b779ec9fe7bde28608a8a7022b28ef322fcdcebd
https://github.com/elgalu/strongly_typed/blob/b779ec9fe7bde28608a8a7022b28ef322fcdcebd/lib/strongly_typed/model.rb#L59-L67
train
elgalu/strongly_typed
lib/strongly_typed/model.rb
StronglyTyped.Model.initialize_from_ordered_args
def initialize_from_ordered_args(values) raise ArgumentError, "wrong number of arguments(#{values.size} for #{self.class.members.size})" if values.size > self.class.members.size values.each_with_index do |v, i| # instance_variable_set("@#{self.class.members[i]}", v) self.public_send("#{self.class.members[i]}=", v) end end
ruby
def initialize_from_ordered_args(values) raise ArgumentError, "wrong number of arguments(#{values.size} for #{self.class.members.size})" if values.size > self.class.members.size values.each_with_index do |v, i| # instance_variable_set("@#{self.class.members[i]}", v) self.public_send("#{self.class.members[i]}=", v) end end
[ "def", "initialize_from_ordered_args", "(", "values", ")", "raise", "ArgumentError", ",", "\"wrong number of arguments(#{values.size} for #{self.class.members.size})\"", "if", "values", ".", "size", ">", "self", ".", "class", ".", "members", ".", "size", "values", ".", "each_with_index", "do", "|", "v", ",", "i", "|", "self", ".", "public_send", "(", "\"#{self.class.members[i]}=\"", ",", "v", ")", "end", "end" ]
Entity constructor from ordered params @param [Array] values ordered values @example class Person include StronglyTyped::Model attribute :id, Integer attribute :slug, String end Person.new(1, 'elgalu') #=> #<Person:0x00c99 @id=1, @slug="elgalu"> leo.id #=> 1 leo.slug #=> "elgalu" @raise [ArgumentError] if the arity doesn't match @private
[ "Entity", "constructor", "from", "ordered", "params" ]
b779ec9fe7bde28608a8a7022b28ef322fcdcebd
https://github.com/elgalu/strongly_typed/blob/b779ec9fe7bde28608a8a7022b28ef322fcdcebd/lib/strongly_typed/model.rb#L89-L96
train
AndreasWurm/pingback
lib/pingback/server.rb
Pingback.Server.call
def call(env) @request = Rack::Request.new(env) xml_response = @xmlrpc_handler.process(request_body) [200, {'Content-Type' => 'text/xml'}, [xml_response]] end
ruby
def call(env) @request = Rack::Request.new(env) xml_response = @xmlrpc_handler.process(request_body) [200, {'Content-Type' => 'text/xml'}, [xml_response]] end
[ "def", "call", "(", "env", ")", "@request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "xml_response", "=", "@xmlrpc_handler", ".", "process", "(", "request_body", ")", "[", "200", ",", "{", "'Content-Type'", "=>", "'text/xml'", "}", ",", "[", "xml_response", "]", "]", "end" ]
A new instance of Server. @param [Proc, #call] request_handler proc which implements the pingback registration and takes the source_uri and the target_uri as params. Use the exceptions defined in Pingback to indicate errors.
[ "A", "new", "instance", "of", "Server", "." ]
44028aa94420b5cb5454ee56d459f0e4ff31194f
https://github.com/AndreasWurm/pingback/blob/44028aa94420b5cb5454ee56d459f0e4ff31194f/lib/pingback/server.rb#L20-L24
train
pengwynn/buzzsprout
lib/buzzsprout/episode.rb
Buzzsprout.Episode.duration=
def duration=(value) new_duration = value.to_s.split(":").reverse s, m = new_duration self[:duration] = (s.to_i + (m.to_i*60)) end
ruby
def duration=(value) new_duration = value.to_s.split(":").reverse s, m = new_duration self[:duration] = (s.to_i + (m.to_i*60)) end
[ "def", "duration", "=", "(", "value", ")", "new_duration", "=", "value", ".", "to_s", ".", "split", "(", "\":\"", ")", ".", "reverse", "s", ",", "m", "=", "new_duration", "self", "[", ":duration", "]", "=", "(", "s", ".", "to_i", "+", "(", "m", ".", "to_i", "*", "60", ")", ")", "end" ]
Set the duration @param [String] duration as time
[ "Set", "the", "duration" ]
6a4bf696efc086ef6d009293ece21e001fc133cd
https://github.com/pengwynn/buzzsprout/blob/6a4bf696efc086ef6d009293ece21e001fc133cd/lib/buzzsprout/episode.rb#L40-L44
train
philosophie/stairs
lib/stairs/step.rb
Stairs.Step.provide
def provide(prompt, options = {}) options.reverse_merge! required: true, default: nil required = options[:required] && !options[:default] prompt = "#{defaulted_prompt(prompt, options[:default])}: " if Stairs.configuration.use_defaults && options[:default] options[:default] else Stairs::Util::CLI.collect(prompt.blue, required: required) || options[:default] end end
ruby
def provide(prompt, options = {}) options.reverse_merge! required: true, default: nil required = options[:required] && !options[:default] prompt = "#{defaulted_prompt(prompt, options[:default])}: " if Stairs.configuration.use_defaults && options[:default] options[:default] else Stairs::Util::CLI.collect(prompt.blue, required: required) || options[:default] end end
[ "def", "provide", "(", "prompt", ",", "options", "=", "{", "}", ")", "options", ".", "reverse_merge!", "required", ":", "true", ",", "default", ":", "nil", "required", "=", "options", "[", ":required", "]", "&&", "!", "options", "[", ":default", "]", "prompt", "=", "\"#{defaulted_prompt(prompt, options[:default])}: \"", "if", "Stairs", ".", "configuration", ".", "use_defaults", "&&", "options", "[", ":default", "]", "options", "[", ":default", "]", "else", "Stairs", "::", "Util", "::", "CLI", ".", "collect", "(", "prompt", ".", "blue", ",", "required", ":", "required", ")", "||", "options", "[", ":default", "]", "end", "end" ]
Prompt user to provide input
[ "Prompt", "user", "to", "provide", "input" ]
535f69a783bd5ff418d786af8c91789925c4388b
https://github.com/philosophie/stairs/blob/535f69a783bd5ff418d786af8c91789925c4388b/lib/stairs/step.rb#L39-L50
train
philosophie/stairs
lib/stairs/step.rb
Stairs.Step.env
def env(name, value) ENV[name] = value if value Stairs.configuration.env_adapter.set name, value else Stairs.configuration.env_adapter.unset name end end
ruby
def env(name, value) ENV[name] = value if value Stairs.configuration.env_adapter.set name, value else Stairs.configuration.env_adapter.unset name end end
[ "def", "env", "(", "name", ",", "value", ")", "ENV", "[", "name", "]", "=", "value", "if", "value", "Stairs", ".", "configuration", ".", "env_adapter", ".", "set", "name", ",", "value", "else", "Stairs", ".", "configuration", ".", "env_adapter", ".", "unset", "name", "end", "end" ]
Set or update env var
[ "Set", "or", "update", "env", "var" ]
535f69a783bd5ff418d786af8c91789925c4388b
https://github.com/philosophie/stairs/blob/535f69a783bd5ff418d786af8c91789925c4388b/lib/stairs/step.rb#L64-L72
train
26fe/dircat
lib/dircat/cat_on_yaml/cat_on_yaml.rb
DirCat.CatOnYaml.from_dir
def from_dir(dirname) unless File.directory?(dirname) raise "'#{dirname}' is not a directory or doesn't exists" end @dirname = File.expand_path dirname @ctime = DateTime.now _load_from_dir self end
ruby
def from_dir(dirname) unless File.directory?(dirname) raise "'#{dirname}' is not a directory or doesn't exists" end @dirname = File.expand_path dirname @ctime = DateTime.now _load_from_dir self end
[ "def", "from_dir", "(", "dirname", ")", "unless", "File", ".", "directory?", "(", "dirname", ")", "raise", "\"'#{dirname}' is not a directory or doesn't exists\"", "end", "@dirname", "=", "File", ".", "expand_path", "dirname", "@ctime", "=", "DateTime", ".", "now", "_load_from_dir", "self", "end" ]
Build a catalog from a directory
[ "Build", "a", "catalog", "from", "a", "directory" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_yaml/cat_on_yaml.rb#L59-L67
train
26fe/dircat
lib/dircat/cat_on_yaml/cat_on_yaml.rb
DirCat.CatOnYaml.from_file
def from_file(filename) unless File.exist?(filename) raise DirCatException.new, "'#{filename}' not exists" end dircat_ser = File.open(filename) { |f| YAML::load(f) } @dirname = dircat_ser.dirname @ctime = dircat_ser.ctime dircat_ser.entries.each do |entry_ser| add_entry(Entry.from_ser(entry_ser)) end self end
ruby
def from_file(filename) unless File.exist?(filename) raise DirCatException.new, "'#{filename}' not exists" end dircat_ser = File.open(filename) { |f| YAML::load(f) } @dirname = dircat_ser.dirname @ctime = dircat_ser.ctime dircat_ser.entries.each do |entry_ser| add_entry(Entry.from_ser(entry_ser)) end self end
[ "def", "from_file", "(", "filename", ")", "unless", "File", ".", "exist?", "(", "filename", ")", "raise", "DirCatException", ".", "new", ",", "\"'#{filename}' not exists\"", "end", "dircat_ser", "=", "File", ".", "open", "(", "filename", ")", "{", "|", "f", "|", "YAML", "::", "load", "(", "f", ")", "}", "@dirname", "=", "dircat_ser", ".", "dirname", "@ctime", "=", "dircat_ser", ".", "ctime", "dircat_ser", ".", "entries", ".", "each", "do", "|", "entry_ser", "|", "add_entry", "(", "Entry", ".", "from_ser", "(", "entry_ser", ")", ")", "end", "self", "end" ]
Load catalog from a file
[ "Load", "catalog", "from", "a", "file" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_yaml/cat_on_yaml.rb#L70-L81
train
26fe/dircat
lib/dircat/cat_on_yaml/cat_on_yaml.rb
DirCat.CatOnYaml.save_to
def save_to(file) if file.kind_of?(String) begin File.open(file, "w") do |f| f.puts to_ser.to_yaml end rescue Errno::ENOENT raise DirCatException.new, "DirCat: cannot write into '#{file}'", caller end else file.puts to_ser.to_yaml end end
ruby
def save_to(file) if file.kind_of?(String) begin File.open(file, "w") do |f| f.puts to_ser.to_yaml end rescue Errno::ENOENT raise DirCatException.new, "DirCat: cannot write into '#{file}'", caller end else file.puts to_ser.to_yaml end end
[ "def", "save_to", "(", "file", ")", "if", "file", ".", "kind_of?", "(", "String", ")", "begin", "File", ".", "open", "(", "file", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "puts", "to_ser", ".", "to_yaml", "end", "rescue", "Errno", "::", "ENOENT", "raise", "DirCatException", ".", "new", ",", "\"DirCat: cannot write into '#{file}'\"", ",", "caller", "end", "else", "file", ".", "puts", "to_ser", ".", "to_yaml", "end", "end" ]
Save serialized catalog to file @param [String,File] file
[ "Save", "serialized", "catalog", "to", "file" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_yaml/cat_on_yaml.rb#L139-L151
train
26fe/dircat
lib/dircat/cat_on_yaml/cat_on_yaml.rb
DirCat.CatOnYaml.report
def report dups = duplicates s = "Base dir: #{@dirname}\n" s += "Nr. file: #{size}" if dups.size > 0 s+= " (duplicates #{dups.size})" end s += "\nBytes: #{bytes.with_separator}" s end
ruby
def report dups = duplicates s = "Base dir: #{@dirname}\n" s += "Nr. file: #{size}" if dups.size > 0 s+= " (duplicates #{dups.size})" end s += "\nBytes: #{bytes.with_separator}" s end
[ "def", "report", "dups", "=", "duplicates", "s", "=", "\"Base dir: #{@dirname}\\n\"", "s", "+=", "\"Nr. file: #{size}\"", "if", "dups", ".", "size", ">", "0", "s", "+=", "\" (duplicates #{dups.size})\"", "end", "s", "+=", "\"\\nBytes: #{bytes.with_separator}\"", "s", "end" ]
simple report with essential information about this catalog @return [String] report
[ "simple", "report", "with", "essential", "information", "about", "this", "catalog" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_yaml/cat_on_yaml.rb#L177-L186
train
26fe/dircat
lib/dircat/cat_on_yaml/cat_on_yaml.rb
DirCat.CatOnYaml.script_dup
def script_dup r = "require 'fileutils'\n" duplicates.each do |entries| flg_first = true r += "\n" entries.each do |entry| src = File.join(@dirname, entry.path, entry.name) if flg_first flg_first = false r += "# FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" else r += "FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" end end end r end
ruby
def script_dup r = "require 'fileutils'\n" duplicates.each do |entries| flg_first = true r += "\n" entries.each do |entry| src = File.join(@dirname, entry.path, entry.name) if flg_first flg_first = false r += "# FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" else r += "FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" end end end r end
[ "def", "script_dup", "r", "=", "\"require 'fileutils'\\n\"", "duplicates", ".", "each", "do", "|", "entries", "|", "flg_first", "=", "true", "r", "+=", "\"\\n\"", "entries", ".", "each", "do", "|", "entry", "|", "src", "=", "File", ".", "join", "(", "@dirname", ",", "entry", ".", "path", ",", "entry", ".", "name", ")", "if", "flg_first", "flg_first", "=", "false", "r", "+=", "\"# FileUtils.mv( \\\"#{src}\\\", \\\"#{Dir.tmpdir}\\\" )\\n\"", "else", "r", "+=", "\"FileUtils.mv( \\\"#{src}\\\", \\\"#{Dir.tmpdir}\\\" )\\n\"", "end", "end", "end", "r", "end" ]
return ruby script to eliminate duplicated @return [String] ruby script
[ "return", "ruby", "script", "to", "eliminate", "duplicated" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_yaml/cat_on_yaml.rb#L265-L281
train
jimjh/reaction
lib/reaction/registry/registry.rb
Reaction.Registry.add
def add(channel, client) @lock.synchronize do _remove(client) if @clients.include? client and @clients[client] != channel debug { "Adding #{client} to #{channel}." } @clients[client] = channel @channels[channel] = @channels[channel] ? @channels[channel] + 1 : 1 end end
ruby
def add(channel, client) @lock.synchronize do _remove(client) if @clients.include? client and @clients[client] != channel debug { "Adding #{client} to #{channel}." } @clients[client] = channel @channels[channel] = @channels[channel] ? @channels[channel] + 1 : 1 end end
[ "def", "add", "(", "channel", ",", "client", ")", "@lock", ".", "synchronize", "do", "_remove", "(", "client", ")", "if", "@clients", ".", "include?", "client", "and", "@clients", "[", "client", "]", "!=", "channel", "debug", "{", "\"Adding #{client} to #{channel}.\"", "}", "@clients", "[", "client", "]", "=", "channel", "@channels", "[", "channel", "]", "=", "@channels", "[", "channel", "]", "?", "@channels", "[", "channel", "]", "+", "1", ":", "1", "end", "end" ]
Creates a new registry. Registers a new client for that channel. Migrates client to new channel if client already exists. @param [String] channel ID @param [String] client ID
[ "Creates", "a", "new", "registry", ".", "Registers", "a", "new", "client", "for", "that", "channel", ".", "Migrates", "client", "to", "new", "channel", "if", "client", "already", "exists", "." ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/registry/registry.rb#L27-L34
train
jimjh/reaction
lib/reaction/registry/registry.rb
Reaction.Registry._remove
def _remove(client) return unless @clients.include? client channel = @clients.delete(client) debug { "Removing #{client} from #{channel}." } @channels[channel] -= 1 @channels.delete(channel) if @channels[channel].zero? end
ruby
def _remove(client) return unless @clients.include? client channel = @clients.delete(client) debug { "Removing #{client} from #{channel}." } @channels[channel] -= 1 @channels.delete(channel) if @channels[channel].zero? end
[ "def", "_remove", "(", "client", ")", "return", "unless", "@clients", ".", "include?", "client", "channel", "=", "@clients", ".", "delete", "(", "client", ")", "debug", "{", "\"Removing #{client} from #{channel}.\"", "}", "@channels", "[", "channel", "]", "-=", "1", "@channels", ".", "delete", "(", "channel", ")", "if", "@channels", "[", "channel", "]", ".", "zero?", "end" ]
Removes client from +@clients+, and decrements channel's client count. If channel has no clients, it is removed. @param [String] client ID
[ "Removes", "client", "from", "+" ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/registry/registry.rb#L55-L61
train
NathanTCz/idlc-sdk-core
lib/idlc-sdk-core/helpers.rb
Idlc.Helpers.system_command
def system_command(*command_args) cmd = Mixlib::ShellOut.new(*command_args) cmd.run_command cmd end
ruby
def system_command(*command_args) cmd = Mixlib::ShellOut.new(*command_args) cmd.run_command cmd end
[ "def", "system_command", "(", "*", "command_args", ")", "cmd", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "*", "command_args", ")", "cmd", ".", "run_command", "cmd", "end" ]
Runs given commands using mixlib-shellout
[ "Runs", "given", "commands", "using", "mixlib", "-", "shellout" ]
a9cf07f65a1b206b7f776183d29923aa345f582e
https://github.com/NathanTCz/idlc-sdk-core/blob/a9cf07f65a1b206b7f776183d29923aa345f582e/lib/idlc-sdk-core/helpers.rb#L8-L12
train
leather-s/renote_dac
app/workers/renote_dac/service_queue_worker.rb
RenoteDac.ServiceQueueWorker.work
def work(message) # invoke service object to save message to database message = JSON.parse(message) RenoteDac::Mailer.enqueue( message['postmark_data']['template'], message['postmark_data']['address'], message['postmark_data']['params'], message['postmark_data']['attachments'] ) # let queue know message was received ack! end
ruby
def work(message) # invoke service object to save message to database message = JSON.parse(message) RenoteDac::Mailer.enqueue( message['postmark_data']['template'], message['postmark_data']['address'], message['postmark_data']['params'], message['postmark_data']['attachments'] ) # let queue know message was received ack! end
[ "def", "work", "(", "message", ")", "message", "=", "JSON", ".", "parse", "(", "message", ")", "RenoteDac", "::", "Mailer", ".", "enqueue", "(", "message", "[", "'postmark_data'", "]", "[", "'template'", "]", ",", "message", "[", "'postmark_data'", "]", "[", "'address'", "]", ",", "message", "[", "'postmark_data'", "]", "[", "'params'", "]", ",", "message", "[", "'postmark_data'", "]", "[", "'attachments'", "]", ")", "ack!", "end" ]
work method receives message payload in raw format in our case it is JSON encoded string which we can pass to RecentPosts service without changes
[ "work", "method", "receives", "message", "payload", "in", "raw", "format", "in", "our", "case", "it", "is", "JSON", "encoded", "string", "which", "we", "can", "pass", "to", "RecentPosts", "service", "without", "changes" ]
2836ab504891d94e5b18758b0910dae9a2cda8f9
https://github.com/leather-s/renote_dac/blob/2836ab504891d94e5b18758b0910dae9a2cda8f9/app/workers/renote_dac/service_queue_worker.rb#L16-L27
train
joakimk/dboard
lib/collector.rb
Dboard.Collector.update_source
def update_source(source, instance) begin data = instance.fetch publish_data(source, data) ensure @after_update_callback.call end rescue Exception => ex puts "Failed to update #{source}: #{ex.message}" puts ex.backtrace @error_callback.call(ex) end
ruby
def update_source(source, instance) begin data = instance.fetch publish_data(source, data) ensure @after_update_callback.call end rescue Exception => ex puts "Failed to update #{source}: #{ex.message}" puts ex.backtrace @error_callback.call(ex) end
[ "def", "update_source", "(", "source", ",", "instance", ")", "begin", "data", "=", "instance", ".", "fetch", "publish_data", "(", "source", ",", "data", ")", "ensure", "@after_update_callback", ".", "call", "end", "rescue", "Exception", "=>", "ex", "puts", "\"Failed to update #{source}: #{ex.message}\"", "puts", "ex", ".", "backtrace", "@error_callback", ".", "call", "(", "ex", ")", "end" ]
Public because the old tests depend on it
[ "Public", "because", "the", "old", "tests", "depend", "on", "it" ]
49a05d1ee679cf1ba8b2b543ac5836651d4cfd38
https://github.com/joakimk/dboard/blob/49a05d1ee679cf1ba8b2b543ac5836651d4cfd38/lib/collector.rb#L58-L69
train
thriventures/storage_room_gem
lib/storage_room/proxy.rb
StorageRoom.Proxy.method_missing
def method_missing(method_name, *args, &block) if @object.loaded? || METHODS_WITHOUT_RELOAD.include?(method_name) # no need to reload else StorageRoom.log("Reloading #{@object['url']} due to #{method_name}") @object.reload(@object['url'], @parameters) end @object.send(method_name, *args, &block) end
ruby
def method_missing(method_name, *args, &block) if @object.loaded? || METHODS_WITHOUT_RELOAD.include?(method_name) # no need to reload else StorageRoom.log("Reloading #{@object['url']} due to #{method_name}") @object.reload(@object['url'], @parameters) end @object.send(method_name, *args, &block) end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "if", "@object", ".", "loaded?", "||", "METHODS_WITHOUT_RELOAD", ".", "include?", "(", "method_name", ")", "else", "StorageRoom", ".", "log", "(", "\"Reloading #{@object['url']} due to #{method_name}\"", ")", "@object", ".", "reload", "(", "@object", "[", "'url'", "]", ",", "@parameters", ")", "end", "@object", ".", "send", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "end" ]
Forward all method calls to the proxied object, reload if necessary
[ "Forward", "all", "method", "calls", "to", "the", "proxied", "object", "reload", "if", "necessary" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/proxy.rb#L37-L46
train
alphagov/govuk_navigation_helpers
lib/govuk_navigation_helpers/grouped_related_links.rb
GovukNavigationHelpers.GroupedRelatedLinks.tagged_to_same_mainstream_browse_page
def tagged_to_same_mainstream_browse_page return [] unless content_item.parent @tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| related_item.mainstream_browse_pages.map(&:content_id).include?(content_item.parent.content_id) end end
ruby
def tagged_to_same_mainstream_browse_page return [] unless content_item.parent @tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| related_item.mainstream_browse_pages.map(&:content_id).include?(content_item.parent.content_id) end end
[ "def", "tagged_to_same_mainstream_browse_page", "return", "[", "]", "unless", "content_item", ".", "parent", "@tagged_to_same_mainstream_browse_page", "||=", "content_item", ".", "related_links", ".", "select", "do", "|", "related_item", "|", "related_item", ".", "mainstream_browse_pages", ".", "map", "(", "&", ":content_id", ")", ".", "include?", "(", "content_item", ".", "parent", ".", "content_id", ")", "end", "end" ]
This will return related items that are tagged to the same mainstream browse page as the main content item.
[ "This", "will", "return", "related", "items", "that", "are", "tagged", "to", "the", "same", "mainstream", "browse", "page", "as", "the", "main", "content", "item", "." ]
5eddcaec5412473fa4e22ef8b8d2cbe406825886
https://github.com/alphagov/govuk_navigation_helpers/blob/5eddcaec5412473fa4e22ef8b8d2cbe406825886/lib/govuk_navigation_helpers/grouped_related_links.rb#L16-L22
train
alphagov/govuk_navigation_helpers
lib/govuk_navigation_helpers/grouped_related_links.rb
GovukNavigationHelpers.GroupedRelatedLinks.parents_tagged_to_same_mainstream_browse_page
def parents_tagged_to_same_mainstream_browse_page return [] unless content_item.parent && content_item.parent.parent common_parent_content_ids = tagged_to_same_mainstream_browse_page.map(&:content_id) @parents_tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| next if common_parent_content_ids.include?(related_item.content_id) related_item.mainstream_browse_pages.map(&:parent).map(&:content_id).include?(content_item.parent.parent.content_id) end end
ruby
def parents_tagged_to_same_mainstream_browse_page return [] unless content_item.parent && content_item.parent.parent common_parent_content_ids = tagged_to_same_mainstream_browse_page.map(&:content_id) @parents_tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| next if common_parent_content_ids.include?(related_item.content_id) related_item.mainstream_browse_pages.map(&:parent).map(&:content_id).include?(content_item.parent.parent.content_id) end end
[ "def", "parents_tagged_to_same_mainstream_browse_page", "return", "[", "]", "unless", "content_item", ".", "parent", "&&", "content_item", ".", "parent", ".", "parent", "common_parent_content_ids", "=", "tagged_to_same_mainstream_browse_page", ".", "map", "(", "&", ":content_id", ")", "@parents_tagged_to_same_mainstream_browse_page", "||=", "content_item", ".", "related_links", ".", "select", "do", "|", "related_item", "|", "next", "if", "common_parent_content_ids", ".", "include?", "(", "related_item", ".", "content_id", ")", "related_item", ".", "mainstream_browse_pages", ".", "map", "(", "&", ":parent", ")", ".", "map", "(", "&", ":content_id", ")", ".", "include?", "(", "content_item", ".", "parent", ".", "parent", ".", "content_id", ")", "end", "end" ]
This will return related items whose parents are tagged to the same mainstream browse page as the main content item's parent.
[ "This", "will", "return", "related", "items", "whose", "parents", "are", "tagged", "to", "the", "same", "mainstream", "browse", "page", "as", "the", "main", "content", "item", "s", "parent", "." ]
5eddcaec5412473fa4e22ef8b8d2cbe406825886
https://github.com/alphagov/govuk_navigation_helpers/blob/5eddcaec5412473fa4e22ef8b8d2cbe406825886/lib/govuk_navigation_helpers/grouped_related_links.rb#L26-L35
train
alphagov/govuk_navigation_helpers
lib/govuk_navigation_helpers/grouped_related_links.rb
GovukNavigationHelpers.GroupedRelatedLinks.tagged_to_different_mainstream_browse_pages
def tagged_to_different_mainstream_browse_pages all_content_ids = (tagged_to_same_mainstream_browse_page + parents_tagged_to_same_mainstream_browse_page).map(&:content_id) @tagged_to_different_mainstream_browse_pages ||= content_item.related_links.reject do |related_item| all_content_ids.include?(related_item.content_id) end end
ruby
def tagged_to_different_mainstream_browse_pages all_content_ids = (tagged_to_same_mainstream_browse_page + parents_tagged_to_same_mainstream_browse_page).map(&:content_id) @tagged_to_different_mainstream_browse_pages ||= content_item.related_links.reject do |related_item| all_content_ids.include?(related_item.content_id) end end
[ "def", "tagged_to_different_mainstream_browse_pages", "all_content_ids", "=", "(", "tagged_to_same_mainstream_browse_page", "+", "parents_tagged_to_same_mainstream_browse_page", ")", ".", "map", "(", "&", ":content_id", ")", "@tagged_to_different_mainstream_browse_pages", "||=", "content_item", ".", "related_links", ".", "reject", "do", "|", "related_item", "|", "all_content_ids", ".", "include?", "(", "related_item", ".", "content_id", ")", "end", "end" ]
This will return related links that are tagged to mainstream browse pages unrelated to the main content item.
[ "This", "will", "return", "related", "links", "that", "are", "tagged", "to", "mainstream", "browse", "pages", "unrelated", "to", "the", "main", "content", "item", "." ]
5eddcaec5412473fa4e22ef8b8d2cbe406825886
https://github.com/alphagov/govuk_navigation_helpers/blob/5eddcaec5412473fa4e22ef8b8d2cbe406825886/lib/govuk_navigation_helpers/grouped_related_links.rb#L39-L45
train
alexblackie/yokunai
lib/yokunai/template.rb
Yokunai.Template.render
def render(template, context = {}) return nil unless exist?(template) path = File.join(@template_path, template + ".erb") layout_context = context.merge(partial: ERB.new(File.read(path)).result(Yokunai::RenderContext.new(context).get_binding)) ERB.new(@raw_layout).result(Yokunai::RenderContext.new(layout_context).get_binding) end
ruby
def render(template, context = {}) return nil unless exist?(template) path = File.join(@template_path, template + ".erb") layout_context = context.merge(partial: ERB.new(File.read(path)).result(Yokunai::RenderContext.new(context).get_binding)) ERB.new(@raw_layout).result(Yokunai::RenderContext.new(layout_context).get_binding) end
[ "def", "render", "(", "template", ",", "context", "=", "{", "}", ")", "return", "nil", "unless", "exist?", "(", "template", ")", "path", "=", "File", ".", "join", "(", "@template_path", ",", "template", "+", "\".erb\"", ")", "layout_context", "=", "context", ".", "merge", "(", "partial", ":", "ERB", ".", "new", "(", "File", ".", "read", "(", "path", ")", ")", ".", "result", "(", "Yokunai", "::", "RenderContext", ".", "new", "(", "context", ")", ".", "get_binding", ")", ")", "ERB", ".", "new", "(", "@raw_layout", ")", ".", "result", "(", "Yokunai", "::", "RenderContext", ".", "new", "(", "layout_context", ")", ".", "get_binding", ")", "end" ]
Render an ERB template with the given name, and cache the result for subsequent calls. @param template [String] the name of a template @param context [Hash] key/value pairs of variables to bind the template @return [String] the ERB render result
[ "Render", "an", "ERB", "template", "with", "the", "given", "name", "and", "cache", "the", "result", "for", "subsequent", "calls", "." ]
a3266c8e3980cc174b143030c96467c2c956c0f8
https://github.com/alexblackie/yokunai/blob/a3266c8e3980cc174b143030c96467c2c956c0f8/lib/yokunai/template.rb#L19-L26
train
dmerrick/nagios_alerter
lib/nagios/alerter.rb
Nagios.Alerter.connection_params
def connection_params(host, port) params = {} if !host.nil? params[:host] = host elsif !Nagios::Connection.instance.host.nil? params[:host] = Nagios::Connection.instance.host else raise ArgumentError, "You must provide a Nagios host or use Nagios::Connection" end if !port.nil? params[:port] = port elsif !Nagios::Connection.instance.port.nil? params[:port] = Nagios::Connection.instance.port else raise ArgumentError, "You must provide a Nagios port or use Nagios::Connection" end return params end
ruby
def connection_params(host, port) params = {} if !host.nil? params[:host] = host elsif !Nagios::Connection.instance.host.nil? params[:host] = Nagios::Connection.instance.host else raise ArgumentError, "You must provide a Nagios host or use Nagios::Connection" end if !port.nil? params[:port] = port elsif !Nagios::Connection.instance.port.nil? params[:port] = Nagios::Connection.instance.port else raise ArgumentError, "You must provide a Nagios port or use Nagios::Connection" end return params end
[ "def", "connection_params", "(", "host", ",", "port", ")", "params", "=", "{", "}", "if", "!", "host", ".", "nil?", "params", "[", ":host", "]", "=", "host", "elsif", "!", "Nagios", "::", "Connection", ".", "instance", ".", "host", ".", "nil?", "params", "[", ":host", "]", "=", "Nagios", "::", "Connection", ".", "instance", ".", "host", "else", "raise", "ArgumentError", ",", "\"You must provide a Nagios host or use Nagios::Connection\"", "end", "if", "!", "port", ".", "nil?", "params", "[", ":port", "]", "=", "port", "elsif", "!", "Nagios", "::", "Connection", ".", "instance", ".", "port", ".", "nil?", "params", "[", ":port", "]", "=", "Nagios", "::", "Connection", ".", "instance", ".", "port", "else", "raise", "ArgumentError", ",", "\"You must provide a Nagios port or use Nagios::Connection\"", "end", "return", "params", "end" ]
check that we have the Nagios server details
[ "check", "that", "we", "have", "the", "Nagios", "server", "details" ]
c38f9d8dee7bc082d399bb4987382fbf8cd67d7d
https://github.com/dmerrick/nagios_alerter/blob/c38f9d8dee7bc082d399bb4987382fbf8cd67d7d/lib/nagios/alerter.rb#L66-L87
train
mguymon/buildr-resolver
lib/buildr/packaging/repository_array.rb
Buildr.RepositoryArray.concat
def concat(urls) if !urls.nil? converted = urls.map { |url| convert_remote_url( url ) } super(converted) else super(nil) end end
ruby
def concat(urls) if !urls.nil? converted = urls.map { |url| convert_remote_url( url ) } super(converted) else super(nil) end end
[ "def", "concat", "(", "urls", ")", "if", "!", "urls", ".", "nil?", "converted", "=", "urls", ".", "map", "{", "|", "url", "|", "convert_remote_url", "(", "url", ")", "}", "super", "(", "converted", ")", "else", "super", "(", "nil", ")", "end", "end" ]
Appends the elements in other_array to self, as standardized URL Hashes
[ "Appends", "the", "elements", "in", "other_array", "to", "self", "as", "standardized", "URL", "Hashes" ]
dbe612cffeb7e5e8b88862f54cf773f196dd6722
https://github.com/mguymon/buildr-resolver/blob/dbe612cffeb7e5e8b88862f54cf773f196dd6722/lib/buildr/packaging/repository_array.rb#L45-L52
train
mguymon/buildr-resolver
lib/buildr/packaging/repository_array.rb
Buildr.RepositoryArray.replace
def replace( other_array ) if !other_array.nil? converted = other_array.map { |url| convert_remote_url( url ) } super( converted ) else super( nil ) end end
ruby
def replace( other_array ) if !other_array.nil? converted = other_array.map { |url| convert_remote_url( url ) } super( converted ) else super( nil ) end end
[ "def", "replace", "(", "other_array", ")", "if", "!", "other_array", ".", "nil?", "converted", "=", "other_array", ".", "map", "{", "|", "url", "|", "convert_remote_url", "(", "url", ")", "}", "super", "(", "converted", ")", "else", "super", "(", "nil", ")", "end", "end" ]
Replaces the contents of self with the contents of other_array, truncating or expanding if necessary. The contents of other_array is converted standardized URL Hashes.
[ "Replaces", "the", "contents", "of", "self", "with", "the", "contents", "of", "other_array", "truncating", "or", "expanding", "if", "necessary", ".", "The", "contents", "of", "other_array", "is", "converted", "standardized", "URL", "Hashes", "." ]
dbe612cffeb7e5e8b88862f54cf773f196dd6722
https://github.com/mguymon/buildr-resolver/blob/dbe612cffeb7e5e8b88862f54cf773f196dd6722/lib/buildr/packaging/repository_array.rb#L99-L106
train
jonahoffline/link_shrink
lib/link_shrink/request.rb
LinkShrink.Request.request
def request(new_url, shrinker) shrinker.url = new_url Typhoeus::Request.new( shrinker.api_url, method: shrinker.http_method, body: shrinker.body_parameters(shrinker.url), headers: { 'Content-Type' => shrinker.content_type } ).run end
ruby
def request(new_url, shrinker) shrinker.url = new_url Typhoeus::Request.new( shrinker.api_url, method: shrinker.http_method, body: shrinker.body_parameters(shrinker.url), headers: { 'Content-Type' => shrinker.content_type } ).run end
[ "def", "request", "(", "new_url", ",", "shrinker", ")", "shrinker", ".", "url", "=", "new_url", "Typhoeus", "::", "Request", ".", "new", "(", "shrinker", ".", "api_url", ",", "method", ":", "shrinker", ".", "http_method", ",", "body", ":", "shrinker", ".", "body_parameters", "(", "shrinker", ".", "url", ")", ",", "headers", ":", "{", "'Content-Type'", "=>", "shrinker", ".", "content_type", "}", ")", ".", "run", "end" ]
Calls URL API @see LinkShrink::Shrinkers::Base#api_url @see LinkShrink::Shrinkers::Base#body_parameters
[ "Calls", "URL", "API" ]
8ed842b4f004265e4e91693df72a4d8c49de3ea8
https://github.com/jonahoffline/link_shrink/blob/8ed842b4f004265e4e91693df72a4d8c49de3ea8/lib/link_shrink/request.rb#L47-L55
train