id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
9,600
NUBIC/aker
lib/aker/authorities/composite.rb
Aker::Authorities.Composite.poll
def poll(method, *args) authorities.select { |a| a.respond_to?(method) }.collect { |a| [a.send(method, *args), a] } end
ruby
def poll(method, *args) authorities.select { |a| a.respond_to?(method) }.collect { |a| [a.send(method, *args), a] } end
[ "def", "poll", "(", "method", ",", "*", "args", ")", "authorities", ".", "select", "{", "|", "a", "|", "a", ".", "respond_to?", "(", "method", ")", "}", ".", "collect", "{", "|", "a", "|", "[", "a", ".", "send", "(", "method", ",", "args", ")", ",", "a", "]", "}", "end" ]
Invokes the specified method with the specified arguments on all the authorities which will respond to it.
[ "Invokes", "the", "specified", "method", "with", "the", "specified", "arguments", "on", "all", "the", "authorities", "which", "will", "respond", "to", "it", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/composite.rb#L293-L299
9,601
redbubble/megaphone-client-ruby
lib/megaphone/client.rb
Megaphone.Client.publish!
def publish!(topic, subtopic, schema, partition_key, payload) event = Event.new(topic, subtopic, origin, schema, partition_key, payload) raise MegaphoneInvalidEventError.new(event.errors.join(', ')) unless event.valid? unless logger.post(topic, event.to_hash) if transient_error?(logger.last_error) raise MegaphoneMessageDelayWarning.new(logger.last_error.message, event.stream_id) else raise MegaphoneUnavailableError.new(logger.last_error.message, event.stream_id) end end end
ruby
def publish!(topic, subtopic, schema, partition_key, payload) event = Event.new(topic, subtopic, origin, schema, partition_key, payload) raise MegaphoneInvalidEventError.new(event.errors.join(', ')) unless event.valid? unless logger.post(topic, event.to_hash) if transient_error?(logger.last_error) raise MegaphoneMessageDelayWarning.new(logger.last_error.message, event.stream_id) else raise MegaphoneUnavailableError.new(logger.last_error.message, event.stream_id) end end end
[ "def", "publish!", "(", "topic", ",", "subtopic", ",", "schema", ",", "partition_key", ",", "payload", ")", "event", "=", "Event", ".", "new", "(", "topic", ",", "subtopic", ",", "origin", ",", "schema", ",", "partition_key", ",", "payload", ")", "raise", "MegaphoneInvalidEventError", ".", "new", "(", "event", ".", "errors", ".", "join", "(", "', '", ")", ")", "unless", "event", ".", "valid?", "unless", "logger", ".", "post", "(", "topic", ",", "event", ".", "to_hash", ")", "if", "transient_error?", "(", "logger", ".", "last_error", ")", "raise", "MegaphoneMessageDelayWarning", ".", "new", "(", "logger", ".", "last_error", ".", "message", ",", "event", ".", "stream_id", ")", "else", "raise", "MegaphoneUnavailableError", ".", "new", "(", "logger", ".", "last_error", ".", "message", ",", "event", ".", "stream_id", ")", "end", "end", "end" ]
Main entry point for apps using this library. Will default to environment for host and port settings, if not passed. Note that a missing callback_handler will result in a default handler being assigned if the FluentLogger is used.
[ "Main", "entry", "point", "for", "apps", "using", "this", "library", ".", "Will", "default", "to", "environment", "for", "host", "and", "port", "settings", "if", "not", "passed", ".", "Note", "that", "a", "missing", "callback_handler", "will", "result", "in", "a", "default", "handler", "being", "assigned", "if", "the", "FluentLogger", "is", "used", "." ]
0e9a9d6f7041852accc8e02948694539e9faea59
https://github.com/redbubble/megaphone-client-ruby/blob/0e9a9d6f7041852accc8e02948694539e9faea59/lib/megaphone/client.rb#L25-L35
9,602
npolar/npolar-api-client-ruby
lib/npolar/api/client/npolar_api_command.rb
Npolar::Api::Client.NpolarApiCommand.run
def run @client = JsonApiClient.new(uri) @client.log = log @client.header = header @client.param = parameters if param[:concurrency] @client.concurrency = param[:concurrency].to_i end if param[:slice] @client.slice = param[:slice].to_i end if uri =~ /\w+[:]\w+[@]/ username, password = URI.parse(uri).userinfo.split(":") @client.username = username @client.password = password end if param[:auth] # Force authorization @client.authorization = true end method = param[:method].upcase response = nil case method when "DELETE" response = delete when "GET" response = get when "HEAD" response = head when "PATCH" response = patch when "POST" if data.is_a? Dir raise "Not implemented" else response = post(data) end when "PUT" response = put(data) else raise ArgumentError, "Unsupported HTTP method: #{param[:method]}" end #Loop dirs? if not response.nil? and (response.respond_to? :body or response.is_a? Array) if response.is_a? Array responses = response else responses = [response] end i = 0 responses.each do | response | i += 1 log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+ " DNS time: #{response.namelookup_time}"+ " Connect time: #{response.connect_time}"+ " Pre-transer time: #{response.pretransfer_time}" if "HEAD" == method or headers? puts response.response_headers end unless param[:join] puts response.body end end statuses = responses.map {|r| r.code }.uniq status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "") real_responses_size = responses.select {|r| r.code >= 100 }.size log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}" else raise "Invalid response: #{response}" end if param[:join] joined = responses.map {|r| JSON.parse(r.body) } puts joined.to_json end end
ruby
def run @client = JsonApiClient.new(uri) @client.log = log @client.header = header @client.param = parameters if param[:concurrency] @client.concurrency = param[:concurrency].to_i end if param[:slice] @client.slice = param[:slice].to_i end if uri =~ /\w+[:]\w+[@]/ username, password = URI.parse(uri).userinfo.split(":") @client.username = username @client.password = password end if param[:auth] # Force authorization @client.authorization = true end method = param[:method].upcase response = nil case method when "DELETE" response = delete when "GET" response = get when "HEAD" response = head when "PATCH" response = patch when "POST" if data.is_a? Dir raise "Not implemented" else response = post(data) end when "PUT" response = put(data) else raise ArgumentError, "Unsupported HTTP method: #{param[:method]}" end #Loop dirs? if not response.nil? and (response.respond_to? :body or response.is_a? Array) if response.is_a? Array responses = response else responses = [response] end i = 0 responses.each do | response | i += 1 log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+ " DNS time: #{response.namelookup_time}"+ " Connect time: #{response.connect_time}"+ " Pre-transer time: #{response.pretransfer_time}" if "HEAD" == method or headers? puts response.response_headers end unless param[:join] puts response.body end end statuses = responses.map {|r| r.code }.uniq status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "") real_responses_size = responses.select {|r| r.code >= 100 }.size log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}" else raise "Invalid response: #{response}" end if param[:join] joined = responses.map {|r| JSON.parse(r.body) } puts joined.to_json end end
[ "def", "run", "@client", "=", "JsonApiClient", ".", "new", "(", "uri", ")", "@client", ".", "log", "=", "log", "@client", ".", "header", "=", "header", "@client", ".", "param", "=", "parameters", "if", "param", "[", ":concurrency", "]", "@client", ".", "concurrency", "=", "param", "[", ":concurrency", "]", ".", "to_i", "end", "if", "param", "[", ":slice", "]", "@client", ".", "slice", "=", "param", "[", ":slice", "]", ".", "to_i", "end", "if", "uri", "=~", "/", "\\w", "\\w", "/", "username", ",", "password", "=", "URI", ".", "parse", "(", "uri", ")", ".", "userinfo", ".", "split", "(", "\":\"", ")", "@client", ".", "username", "=", "username", "@client", ".", "password", "=", "password", "end", "if", "param", "[", ":auth", "]", "# Force authorization", "@client", ".", "authorization", "=", "true", "end", "method", "=", "param", "[", ":method", "]", ".", "upcase", "response", "=", "nil", "case", "method", "when", "\"DELETE\"", "response", "=", "delete", "when", "\"GET\"", "response", "=", "get", "when", "\"HEAD\"", "response", "=", "head", "when", "\"PATCH\"", "response", "=", "patch", "when", "\"POST\"", "if", "data", ".", "is_a?", "Dir", "raise", "\"Not implemented\"", "else", "response", "=", "post", "(", "data", ")", "end", "when", "\"PUT\"", "response", "=", "put", "(", "data", ")", "else", "raise", "ArgumentError", ",", "\"Unsupported HTTP method: #{param[:method]}\"", "end", "#Loop dirs?", "if", "not", "response", ".", "nil?", "and", "(", "response", ".", "respond_to?", ":body", "or", "response", ".", "is_a?", "Array", ")", "if", "response", ".", "is_a?", "Array", "responses", "=", "response", "else", "responses", "=", "[", "response", "]", "end", "i", "=", "0", "responses", ".", "each", "do", "|", "response", "|", "i", "+=", "1", "log", ".", "debug", "\"#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}\"", "+", "\" DNS time: #{response.namelookup_time}\"", "+", "\" Connect time: #{response.connect_time}\"", "+", "\" Pre-transer time: #{response.pretransfer_time}\"", "if", "\"HEAD\"", "==", "method", "or", "headers?", "puts", "response", ".", "response_headers", "end", "unless", "param", "[", ":join", "]", "puts", "response", ".", "body", "end", "end", "statuses", "=", "responses", ".", "map", "{", "|", "r", "|", "r", ".", "code", "}", ".", "uniq", "status", "=", "statuses", ".", "map", "{", "|", "code", "|", "{", "code", "=>", "responses", ".", "select", "{", "|", "r", "|", "code", "==", "r", ".", "code", "}", ".", "size", "}", "}", ".", "to_json", ".", "gsub", "(", "/", "\\[", "\\]", "/", ",", "\"\"", ")", "real_responses_size", "=", "responses", ".", "select", "{", "|", "r", "|", "r", ".", "code", ">=", "100", "}", ".", "size", "log", ".", "info", "\"Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}\"", "else", "raise", "\"Invalid response: #{response}\"", "end", "if", "param", "[", ":join", "]", "joined", "=", "responses", ".", "map", "{", "|", "r", "|", "JSON", ".", "parse", "(", "r", ".", "body", ")", "}", "puts", "joined", ".", "to_json", "end", "end" ]
Execute npolar-api command @return [nil]
[ "Execute", "npolar", "-", "api", "command" ]
e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb
https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/npolar_api_command.rb#L165-L259
9,603
jtzero/vigilem-core
lib/vigilem/core/hooks/conditional_hook.rb
Vigilem::Core::Hooks.ConditionalHook.enumerate
def enumerate(args={}, &block) passed, failed = [], [] hook = self super do |callback| if hook.condition.call(*callback.options[:condition_args]) hook.passed << callback callback.evaluate(args[:context], *args[:args], &args[:block]) else hook.failed << callback end end end
ruby
def enumerate(args={}, &block) passed, failed = [], [] hook = self super do |callback| if hook.condition.call(*callback.options[:condition_args]) hook.passed << callback callback.evaluate(args[:context], *args[:args], &args[:block]) else hook.failed << callback end end end
[ "def", "enumerate", "(", "args", "=", "{", "}", ",", "&", "block", ")", "passed", ",", "failed", "=", "[", "]", ",", "[", "]", "hook", "=", "self", "super", "do", "|", "callback", "|", "if", "hook", ".", "condition", ".", "call", "(", "callback", ".", "options", "[", ":condition_args", "]", ")", "hook", ".", "passed", "<<", "callback", "callback", ".", "evaluate", "(", "args", "[", ":context", "]", ",", "args", "[", ":args", "]", ",", "args", "[", ":block", "]", ")", "else", "hook", ".", "failed", "<<", "callback", "end", "end", "end" ]
enumerate over the callbacks @param [Array] args @param [Proc] block @return
[ "enumerate", "over", "the", "callbacks" ]
a35864229ee76800f5197e3c3c6fb2bf34a68495
https://github.com/jtzero/vigilem-core/blob/a35864229ee76800f5197e3c3c6fb2bf34a68495/lib/vigilem/core/hooks/conditional_hook.rb#L12-L23
9,604
zealot128/poltergeist-screenshot_overview
lib/poltergeist/screenshot_overview/manager.rb
Poltergeist::ScreenshotOverview.Manager.add_image_from_rspec
def add_image_from_rspec(argument, example, url_path) blob = caller.find{|i| i[ example.file_path.gsub(/:\d*|^\./,"") ]} file_with_line = blob.split(":")[0,2].join(":") filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(" ").gsub(/\W+/,"_") + ".jpg" full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename ) FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory describe = example.metadata[:example_group][:description_args] @files << Screenshot.new({ :url => url_path, :argument => argument, :local_image => filename, :full_path => full_name, :group_description => describe, :example_description => example.description, :file_with_line => file_with_line }) full_name end
ruby
def add_image_from_rspec(argument, example, url_path) blob = caller.find{|i| i[ example.file_path.gsub(/:\d*|^\./,"") ]} file_with_line = blob.split(":")[0,2].join(":") filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(" ").gsub(/\W+/,"_") + ".jpg" full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename ) FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory describe = example.metadata[:example_group][:description_args] @files << Screenshot.new({ :url => url_path, :argument => argument, :local_image => filename, :full_path => full_name, :group_description => describe, :example_description => example.description, :file_with_line => file_with_line }) full_name end
[ "def", "add_image_from_rspec", "(", "argument", ",", "example", ",", "url_path", ")", "blob", "=", "caller", ".", "find", "{", "|", "i", "|", "i", "[", "example", ".", "file_path", ".", "gsub", "(", "/", "\\d", "\\.", "/", ",", "\"\"", ")", "]", "}", "file_with_line", "=", "blob", ".", "split", "(", "\":\"", ")", "[", "0", ",", "2", "]", ".", "join", "(", "\":\"", ")", "filename", "=", "[", "example", ".", "description", ",", "argument", ",", "file_with_line", ",", "SecureRandom", ".", "hex", "(", "6", ")", "]", ".", "join", "(", "\" \"", ")", ".", "gsub", "(", "/", "\\W", "/", ",", "\"_\"", ")", "+", "\".jpg\"", "full_name", "=", "File", ".", "join", "(", "Poltergeist", "::", "ScreenshotOverview", ".", "target_directory", ",", "filename", ")", "FileUtils", ".", "mkdir_p", "Poltergeist", "::", "ScreenshotOverview", ".", "target_directory", "describe", "=", "example", ".", "metadata", "[", ":example_group", "]", "[", ":description_args", "]", "@files", "<<", "Screenshot", ".", "new", "(", "{", ":url", "=>", "url_path", ",", ":argument", "=>", "argument", ",", ":local_image", "=>", "filename", ",", ":full_path", "=>", "full_name", ",", ":group_description", "=>", "describe", ",", ":example_description", "=>", "example", ".", "description", ",", ":file_with_line", "=>", "file_with_line", "}", ")", "full_name", "end" ]
adds image_path and metadata to our list, returns a full path where the Engine should put the screenshot in
[ "adds", "image_path", "and", "metadata", "to", "our", "list", "returns", "a", "full", "path", "where", "the", "Engine", "should", "put", "the", "screenshot", "in" ]
de208475d6dac7f867243802cdc7d86b0f20564c
https://github.com/zealot128/poltergeist-screenshot_overview/blob/de208475d6dac7f867243802cdc7d86b0f20564c/lib/poltergeist/screenshot_overview/manager.rb#L85-L103
9,605
SCPR/audio_vision-ruby
lib/audio_vision/client.rb
AudioVision.Client.get
def get(path, params={}) connection.get do |request| request.url path request.params = params end end
ruby
def get(path, params={}) connection.get do |request| request.url path request.params = params end end
[ "def", "get", "(", "path", ",", "params", "=", "{", "}", ")", "connection", ".", "get", "do", "|", "request", "|", "request", ".", "url", "path", "request", ".", "params", "=", "params", "end", "end" ]
Get a response from the AudioVision API. Returns a Faraday Response object. Example: client.get("posts/1")
[ "Get", "a", "response", "from", "the", "AudioVision", "API", ".", "Returns", "a", "Faraday", "Response", "object", "." ]
63053edd534badb4a8d5d05b788f295ad7d19455
https://github.com/SCPR/audio_vision-ruby/blob/63053edd534badb4a8d5d05b788f295ad7d19455/lib/audio_vision/client.rb#L11-L16
9,606
maxjacobson/todo_lint
lib/todo_lint/config_file.rb
TodoLint.ConfigFile.read_config_file
def read_config_file(file) @config_hash = YAML.load_file(file) @starting_path = File.expand_path(File.split(file).first) @config_options = {} load_tags load_file_exclusions load_extension_inclusions config_options end
ruby
def read_config_file(file) @config_hash = YAML.load_file(file) @starting_path = File.expand_path(File.split(file).first) @config_options = {} load_tags load_file_exclusions load_extension_inclusions config_options end
[ "def", "read_config_file", "(", "file", ")", "@config_hash", "=", "YAML", ".", "load_file", "(", "file", ")", "@starting_path", "=", "File", ".", "expand_path", "(", "File", ".", "split", "(", "file", ")", ".", "first", ")", "@config_options", "=", "{", "}", "load_tags", "load_file_exclusions", "load_extension_inclusions", "config_options", "end" ]
Parses the config file and loads the options @api public @example ConfigFile.new.read_config_file('.todo-lint.yml') @return [Hash] parsed file-options
[ "Parses", "the", "config", "file", "and", "loads", "the", "options" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L10-L18
9,607
maxjacobson/todo_lint
lib/todo_lint/config_file.rb
TodoLint.ConfigFile.load_file_exclusions
def load_file_exclusions return unless config_hash["Exclude Files"] config_options[:excluded_files] = [] config_hash["Exclude Files"].each do |short_file| config_options[:excluded_files] << File.join(starting_path, short_file) end end
ruby
def load_file_exclusions return unless config_hash["Exclude Files"] config_options[:excluded_files] = [] config_hash["Exclude Files"].each do |short_file| config_options[:excluded_files] << File.join(starting_path, short_file) end end
[ "def", "load_file_exclusions", "return", "unless", "config_hash", "[", "\"Exclude Files\"", "]", "config_options", "[", ":excluded_files", "]", "=", "[", "]", "config_hash", "[", "\"Exclude Files\"", "]", ".", "each", "do", "|", "short_file", "|", "config_options", "[", ":excluded_files", "]", "<<", "File", ".", "join", "(", "starting_path", ",", "short_file", ")", "end", "end" ]
Adds the exclude file options to the config_options hash @api private @return [Hash]
[ "Adds", "the", "exclude", "file", "options", "to", "the", "config_options", "hash" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L40-L46
9,608
maxjacobson/todo_lint
lib/todo_lint/config_file.rb
TodoLint.ConfigFile.load_tags
def load_tags config_options[:tags] = {} return unless config_hash["Tags"] config_hash["Tags"].each do |tag, due_date| unless due_date.is_a? Date raise ArgumentError, "#{due_date} is not a date" end config_options[:tags]["##{tag}"] = DueDate.new(due_date) end end
ruby
def load_tags config_options[:tags] = {} return unless config_hash["Tags"] config_hash["Tags"].each do |tag, due_date| unless due_date.is_a? Date raise ArgumentError, "#{due_date} is not a date" end config_options[:tags]["##{tag}"] = DueDate.new(due_date) end end
[ "def", "load_tags", "config_options", "[", ":tags", "]", "=", "{", "}", "return", "unless", "config_hash", "[", "\"Tags\"", "]", "config_hash", "[", "\"Tags\"", "]", ".", "each", "do", "|", "tag", ",", "due_date", "|", "unless", "due_date", ".", "is_a?", "Date", "raise", "ArgumentError", ",", "\"#{due_date} is not a date\"", "end", "config_options", "[", ":tags", "]", "[", "\"##{tag}\"", "]", "=", "DueDate", ".", "new", "(", "due_date", ")", "end", "end" ]
Load the tags from the configuration file as DueDates @return is irrelevant @api private
[ "Load", "the", "tags", "from", "the", "configuration", "file", "as", "DueDates" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/config_file.rb#L60-L70
9,609
nestor-custodio/automodel-sqlserver
lib/automodel/schema_inspector.rb
Automodel.SchemaInspector.columns
def columns(table_name) table_name = table_name.to_s @columns ||= {} @columns[table_name] ||= if @registration[:columns].present? @registration[:columns].call(@connection, table_name) else @connection.columns(table_name) end end
ruby
def columns(table_name) table_name = table_name.to_s @columns ||= {} @columns[table_name] ||= if @registration[:columns].present? @registration[:columns].call(@connection, table_name) else @connection.columns(table_name) end end
[ "def", "columns", "(", "table_name", ")", "table_name", "=", "table_name", ".", "to_s", "@columns", "||=", "{", "}", "@columns", "[", "table_name", "]", "||=", "if", "@registration", "[", ":columns", "]", ".", "present?", "@registration", "[", ":columns", "]", ".", "call", "(", "@connection", ",", "table_name", ")", "else", "@connection", ".", "columns", "(", "table_name", ")", "end", "end" ]
Returns a list of columns for the given table. If a matching Automodel::SchemaInspector registration is found for the connection's adapter, and that registration specified a `:columns` Proc, the Proc is called. Otherwise, the standard connection `#columns` is returned. @param table_name [String] The table whose columns should be fetched. @return [Array<ActiveRecord::ConnectionAdapters::Column>]
[ "Returns", "a", "list", "of", "columns", "for", "the", "given", "table", "." ]
7269224752274f59113ccf8267fc49316062ae22
https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L101-L110
9,610
nestor-custodio/automodel-sqlserver
lib/automodel/schema_inspector.rb
Automodel.SchemaInspector.primary_key
def primary_key(table_name) table_name = table_name.to_s @primary_keys ||= {} @primary_keys[table_name] ||= if @registration[:primary_key].present? @registration[:primary_key].call(@connection, table_name) else @connection.primary_key(table_name) end end
ruby
def primary_key(table_name) table_name = table_name.to_s @primary_keys ||= {} @primary_keys[table_name] ||= if @registration[:primary_key].present? @registration[:primary_key].call(@connection, table_name) else @connection.primary_key(table_name) end end
[ "def", "primary_key", "(", "table_name", ")", "table_name", "=", "table_name", ".", "to_s", "@primary_keys", "||=", "{", "}", "@primary_keys", "[", "table_name", "]", "||=", "if", "@registration", "[", ":primary_key", "]", ".", "present?", "@registration", "[", ":primary_key", "]", ".", "call", "(", "@connection", ",", "table_name", ")", "else", "@connection", ".", "primary_key", "(", "table_name", ")", "end", "end" ]
Returns the primary key for the given table. If a matching Automodel::SchemaInspector registration is found for the connection's adapter, and that registration specified a `:primary_key` Proc, the Proc is called. Otherwise, the standard connection `#primary_key` is returned. @param table_name [String] The table whose primary key should be fetched. @return [String, Array<String>]
[ "Returns", "the", "primary", "key", "for", "the", "given", "table", "." ]
7269224752274f59113ccf8267fc49316062ae22
https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L125-L134
9,611
nestor-custodio/automodel-sqlserver
lib/automodel/schema_inspector.rb
Automodel.SchemaInspector.foreign_keys
def foreign_keys(table_name) table_name = table_name.to_s @foreign_keys ||= {} @foreign_keys[table_name] ||= begin if @registration[:foreign_keys].present? @registration[:foreign_keys].call(@connection, table_name) else begin @connection.foreign_keys(table_name) rescue ::NoMethodError, ::NotImplementedError ## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make ## a best-effort attempt to intuit relationships from the table and column names. ## columns(table_name).map do |column| id_pattern = %r{(?:_id|Id)$} next unless column.name =~ id_pattern target_table = column.name.sub(id_pattern, '') next unless target_table.in? tables target_column = primary_key(qualified_name(target_table, context: table_name)) next unless target_column.in? ['id', 'Id', 'ID', column.name] ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new( table_name.split('.').last, target_table, name: "FK_#{SecureRandom.uuid.delete('-')}", column: column.name, primary_key: target_column, on_update: nil, on_delete: nil ) end.compact end end end end
ruby
def foreign_keys(table_name) table_name = table_name.to_s @foreign_keys ||= {} @foreign_keys[table_name] ||= begin if @registration[:foreign_keys].present? @registration[:foreign_keys].call(@connection, table_name) else begin @connection.foreign_keys(table_name) rescue ::NoMethodError, ::NotImplementedError ## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make ## a best-effort attempt to intuit relationships from the table and column names. ## columns(table_name).map do |column| id_pattern = %r{(?:_id|Id)$} next unless column.name =~ id_pattern target_table = column.name.sub(id_pattern, '') next unless target_table.in? tables target_column = primary_key(qualified_name(target_table, context: table_name)) next unless target_column.in? ['id', 'Id', 'ID', column.name] ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new( table_name.split('.').last, target_table, name: "FK_#{SecureRandom.uuid.delete('-')}", column: column.name, primary_key: target_column, on_update: nil, on_delete: nil ) end.compact end end end end
[ "def", "foreign_keys", "(", "table_name", ")", "table_name", "=", "table_name", ".", "to_s", "@foreign_keys", "||=", "{", "}", "@foreign_keys", "[", "table_name", "]", "||=", "begin", "if", "@registration", "[", ":foreign_keys", "]", ".", "present?", "@registration", "[", ":foreign_keys", "]", ".", "call", "(", "@connection", ",", "table_name", ")", "else", "begin", "@connection", ".", "foreign_keys", "(", "table_name", ")", "rescue", "::", "NoMethodError", ",", "::", "NotImplementedError", "## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make", "## a best-effort attempt to intuit relationships from the table and column names.", "##", "columns", "(", "table_name", ")", ".", "map", "do", "|", "column", "|", "id_pattern", "=", "%r{", "}", "next", "unless", "column", ".", "name", "=~", "id_pattern", "target_table", "=", "column", ".", "name", ".", "sub", "(", "id_pattern", ",", "''", ")", "next", "unless", "target_table", ".", "in?", "tables", "target_column", "=", "primary_key", "(", "qualified_name", "(", "target_table", ",", "context", ":", "table_name", ")", ")", "next", "unless", "target_column", ".", "in?", "[", "'id'", ",", "'Id'", ",", "'ID'", ",", "column", ".", "name", "]", "ActiveRecord", "::", "ConnectionAdapters", "::", "ForeignKeyDefinition", ".", "new", "(", "table_name", ".", "split", "(", "'.'", ")", ".", "last", ",", "target_table", ",", "name", ":", "\"FK_#{SecureRandom.uuid.delete('-')}\"", ",", "column", ":", "column", ".", "name", ",", "primary_key", ":", "target_column", ",", "on_update", ":", "nil", ",", "on_delete", ":", "nil", ")", "end", ".", "compact", "end", "end", "end", "end" ]
Returns a list of foreign keys for the given table. If a matching Automodel::SchemaInspector registration is found for the connection's adapter, and that registration specified a `:foreign_keys` Proc, the Proc is called. Otherwise, the standard connection `#foreign_keys` is attempted. If that call to ``#foreign_keys` raises a ::NoMethodError or ::NotImplementedError, a best-effort attempt is made to build a list of foreign keys based on table and column names. @param table_name [String] The table whose foreign keys should be fetched. @return [Array<ActiveRecord::ConnectionAdapters::ForeignKeyDefinition>]
[ "Returns", "a", "list", "of", "foreign", "keys", "for", "the", "given", "table", "." ]
7269224752274f59113ccf8267fc49316062ae22
https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L151-L188
9,612
keita/naming
lib/naming/name-set.rb
Naming.NameSet.others
def others(array) array.select{|elt| not(any?{|name| elt.kind_of?(name)})} end
ruby
def others(array) array.select{|elt| not(any?{|name| elt.kind_of?(name)})} end
[ "def", "others", "(", "array", ")", "array", ".", "select", "{", "|", "elt", "|", "not", "(", "any?", "{", "|", "name", "|", "elt", ".", "kind_of?", "(", "name", ")", "}", ")", "}", "end" ]
Collect objects from the array excluding named objects which have the name in the set. @param array [Array] target of value extraction @example Naming::NameSet(:A, :B).values([ Naming.A(1), Naming.B(2), "abc", Naming.A(3), 123, nil ]) #=> ["abc", 123, nil]
[ "Collect", "objects", "from", "the", "array", "excluding", "named", "objects", "which", "have", "the", "name", "in", "the", "set", "." ]
70393c824982627885e78336491c75b3f13c1dc0
https://github.com/keita/naming/blob/70393c824982627885e78336491c75b3f13c1dc0/lib/naming/name-set.rb#L44-L46
9,613
rixth/tay
lib/tay/manifest_generator.rb
Tay.ManifestGenerator.spec_as_json
def spec_as_json json = { :name => spec.name, :version => spec.version, :manifest_version => calculate_manifest_version } json[:description] = spec.description if spec.description json[:icons] = spec.icons json[:default_locale] = spec.default_locale if spec.default_locale json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action json[:page_action] = action_as_json(spec.page_action) if spec.page_action json[:app] = packaged_app_as_json if spec.packaged_app if spec.background_page json[:background] = { :page => spec.background_page } end unless spec.background_scripts.empty? json[:background] = { :scripts => spec.background_scripts } end json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty? json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty? json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy json[:homepage_url] = spec.homepage if spec.homepage json[:incognito] = spec.incognito_mode if spec.incognito_mode json[:intents] = web_intents_as_json unless spec.web_intents.empty? json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty? json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil? json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword json[:options_page] = spec.options_page if spec.options_page json[:permissions] = spec.permissions unless spec.permissions.empty? json[:requirements] = requirements_as_json if has_requirements? json[:update_url] = spec.update_url if spec.update_url json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty? json end
ruby
def spec_as_json json = { :name => spec.name, :version => spec.version, :manifest_version => calculate_manifest_version } json[:description] = spec.description if spec.description json[:icons] = spec.icons json[:default_locale] = spec.default_locale if spec.default_locale json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action json[:page_action] = action_as_json(spec.page_action) if spec.page_action json[:app] = packaged_app_as_json if spec.packaged_app if spec.background_page json[:background] = { :page => spec.background_page } end unless spec.background_scripts.empty? json[:background] = { :scripts => spec.background_scripts } end json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty? json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty? json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy json[:homepage_url] = spec.homepage if spec.homepage json[:incognito] = spec.incognito_mode if spec.incognito_mode json[:intents] = web_intents_as_json unless spec.web_intents.empty? json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty? json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil? json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword json[:options_page] = spec.options_page if spec.options_page json[:permissions] = spec.permissions unless spec.permissions.empty? json[:requirements] = requirements_as_json if has_requirements? json[:update_url] = spec.update_url if spec.update_url json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty? json end
[ "def", "spec_as_json", "json", "=", "{", ":name", "=>", "spec", ".", "name", ",", ":version", "=>", "spec", ".", "version", ",", ":manifest_version", "=>", "calculate_manifest_version", "}", "json", "[", ":description", "]", "=", "spec", ".", "description", "if", "spec", ".", "description", "json", "[", ":icons", "]", "=", "spec", ".", "icons", "json", "[", ":default_locale", "]", "=", "spec", ".", "default_locale", "if", "spec", ".", "default_locale", "json", "[", ":browser_action", "]", "=", "action_as_json", "(", "spec", ".", "browser_action", ")", "if", "spec", ".", "browser_action", "json", "[", ":page_action", "]", "=", "action_as_json", "(", "spec", ".", "page_action", ")", "if", "spec", ".", "page_action", "json", "[", ":app", "]", "=", "packaged_app_as_json", "if", "spec", ".", "packaged_app", "if", "spec", ".", "background_page", "json", "[", ":background", "]", "=", "{", ":page", "=>", "spec", ".", "background_page", "}", "end", "unless", "spec", ".", "background_scripts", ".", "empty?", "json", "[", ":background", "]", "=", "{", ":scripts", "=>", "spec", ".", "background_scripts", "}", "end", "json", "[", ":chrome_url_overrides", "]", "=", "spec", ".", "overriden_pages", "unless", "spec", ".", "overriden_pages", ".", "empty?", "json", "[", ":content_scripts", "]", "=", "content_scripts_as_json", "unless", "spec", ".", "content_scripts", ".", "empty?", "json", "[", ":content_security_policy", "]", "=", "spec", ".", "content_security_policy", "if", "spec", ".", "content_security_policy", "json", "[", ":homepage_url", "]", "=", "spec", ".", "homepage", "if", "spec", ".", "homepage", "json", "[", ":incognito", "]", "=", "spec", ".", "incognito_mode", "if", "spec", ".", "incognito_mode", "json", "[", ":intents", "]", "=", "web_intents_as_json", "unless", "spec", ".", "web_intents", ".", "empty?", "json", "[", ":minimum_chrome_version", "]", "=", "spec", ".", "minimum_chrome_version", "if", "spec", ".", "minimum_chrome_version", "json", "[", ":nacl_modules", "]", "=", "nacl_modules_as_json", "unless", "spec", ".", "nacl_modules", ".", "empty?", "json", "[", ":offline_enabled", "]", "=", "spec", ".", "offline_enabled", "unless", "spec", ".", "offline_enabled", ".", "nil?", "json", "[", ":omnibox", "]", "=", "spec", ".", "omnibox_keyword", "if", "spec", ".", "omnibox_keyword", "json", "[", ":options_page", "]", "=", "spec", ".", "options_page", "if", "spec", ".", "options_page", "json", "[", ":permissions", "]", "=", "spec", ".", "permissions", "unless", "spec", ".", "permissions", ".", "empty?", "json", "[", ":requirements", "]", "=", "requirements_as_json", "if", "has_requirements?", "json", "[", ":update_url", "]", "=", "spec", ".", "update_url", "if", "spec", ".", "update_url", "json", "[", ":web_accessible_resources", "]", "=", "spec", ".", "web_accessible_resources", "unless", "spec", ".", "web_accessible_resources", ".", "empty?", "json", "end" ]
Return the JSON representation of the specification
[ "Return", "the", "JSON", "representation", "of", "the", "specification" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L19-L55
9,614
rixth/tay
lib/tay/manifest_generator.rb
Tay.ManifestGenerator.action_as_json
def action_as_json(action) json = {} json[:default_title] = action.title if action.title json[:default_icon] = action.icon if action.icon json[:default_popup] = action.popup if action.popup json end
ruby
def action_as_json(action) json = {} json[:default_title] = action.title if action.title json[:default_icon] = action.icon if action.icon json[:default_popup] = action.popup if action.popup json end
[ "def", "action_as_json", "(", "action", ")", "json", "=", "{", "}", "json", "[", ":default_title", "]", "=", "action", ".", "title", "if", "action", ".", "title", "json", "[", ":default_icon", "]", "=", "action", ".", "icon", "if", "action", ".", "icon", "json", "[", ":default_popup", "]", "=", "action", ".", "popup", "if", "action", ".", "popup", "json", "end" ]
Return the manifest representation of a page or browser action
[ "Return", "the", "manifest", "representation", "of", "a", "page", "or", "browser", "action" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L68-L74
9,615
rixth/tay
lib/tay/manifest_generator.rb
Tay.ManifestGenerator.packaged_app_as_json
def packaged_app_as_json app = spec.packaged_app json = { :local_path => app.page } unless app.container.nil? json[:container] = app.container if app.container == 'panel' json[:width] = app.width json[:height] = app.height end end { :launch => json } end
ruby
def packaged_app_as_json app = spec.packaged_app json = { :local_path => app.page } unless app.container.nil? json[:container] = app.container if app.container == 'panel' json[:width] = app.width json[:height] = app.height end end { :launch => json } end
[ "def", "packaged_app_as_json", "app", "=", "spec", ".", "packaged_app", "json", "=", "{", ":local_path", "=>", "app", ".", "page", "}", "unless", "app", ".", "container", ".", "nil?", "json", "[", ":container", "]", "=", "app", ".", "container", "if", "app", ".", "container", "==", "'panel'", "json", "[", ":width", "]", "=", "app", ".", "width", "json", "[", ":height", "]", "=", "app", ".", "height", "end", "end", "{", ":launch", "=>", "json", "}", "end" ]
Return the manifest representation of a packaged app
[ "Return", "the", "manifest", "representation", "of", "a", "packaged", "app" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L78-L93
9,616
rixth/tay
lib/tay/manifest_generator.rb
Tay.ManifestGenerator.content_scripts_as_json
def content_scripts_as_json spec.content_scripts.map do |cs| cs_json = { :matches => cs.include_patterns } cs_json[:exclude_matches] = cs.exclude_patterns unless cs.exclude_patterns.empty? cs_json[:run_at] = cs.run_at if cs.run_at cs_json[:all_frames] = cs.all_frames unless cs.all_frames.nil? cs_json[:css] = cs.stylesheets unless cs.stylesheets.empty? cs_json[:js] = cs.javascripts unless cs.javascripts.empty? cs_json end end
ruby
def content_scripts_as_json spec.content_scripts.map do |cs| cs_json = { :matches => cs.include_patterns } cs_json[:exclude_matches] = cs.exclude_patterns unless cs.exclude_patterns.empty? cs_json[:run_at] = cs.run_at if cs.run_at cs_json[:all_frames] = cs.all_frames unless cs.all_frames.nil? cs_json[:css] = cs.stylesheets unless cs.stylesheets.empty? cs_json[:js] = cs.javascripts unless cs.javascripts.empty? cs_json end end
[ "def", "content_scripts_as_json", "spec", ".", "content_scripts", ".", "map", "do", "|", "cs", "|", "cs_json", "=", "{", ":matches", "=>", "cs", ".", "include_patterns", "}", "cs_json", "[", ":exclude_matches", "]", "=", "cs", ".", "exclude_patterns", "unless", "cs", ".", "exclude_patterns", ".", "empty?", "cs_json", "[", ":run_at", "]", "=", "cs", ".", "run_at", "if", "cs", ".", "run_at", "cs_json", "[", ":all_frames", "]", "=", "cs", ".", "all_frames", "unless", "cs", ".", "all_frames", ".", "nil?", "cs_json", "[", ":css", "]", "=", "cs", ".", "stylesheets", "unless", "cs", ".", "stylesheets", ".", "empty?", "cs_json", "[", ":js", "]", "=", "cs", ".", "javascripts", "unless", "cs", ".", "javascripts", ".", "empty?", "cs_json", "end", "end" ]
Return the manifest representation of the content scripts, if any
[ "Return", "the", "manifest", "representation", "of", "the", "content", "scripts", "if", "any" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L97-L111
9,617
rixth/tay
lib/tay/manifest_generator.rb
Tay.ManifestGenerator.web_intents_as_json
def web_intents_as_json spec.web_intents.map do |wi| { :action => wi.action, :title => wi.title, :href => wi.href, :types => wi.types, :disposition => wi.disposition } end end
ruby
def web_intents_as_json spec.web_intents.map do |wi| { :action => wi.action, :title => wi.title, :href => wi.href, :types => wi.types, :disposition => wi.disposition } end end
[ "def", "web_intents_as_json", "spec", ".", "web_intents", ".", "map", "do", "|", "wi", "|", "{", ":action", "=>", "wi", ".", "action", ",", ":title", "=>", "wi", ".", "title", ",", ":href", "=>", "wi", ".", "href", ",", ":types", "=>", "wi", ".", "types", ",", ":disposition", "=>", "wi", ".", "disposition", "}", "end", "end" ]
Return the manifest representation of handled web intents, if any
[ "Return", "the", "manifest", "representation", "of", "handled", "web", "intents", "if", "any" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/manifest_generator.rb#L115-L125
9,618
redding/logsly
lib/logsly/logging182/appenders/email.rb
Logsly::Logging182::Appenders.Email.canonical_write
def canonical_write( str ) ### build a mail header for RFC 822 rfc822msg = "From: #{@from}\n" rfc822msg << "To: #{@to.join(",")}\n" rfc822msg << "Subject: #{@subject}\n" rfc822msg << "Date: #{Time.new.rfc822}\n" rfc822msg << "Message-Id: <#{"%.8f" % Time.now.to_f}@#{@domain}>\n\n" rfc822msg = rfc822msg.force_encoding(encoding) if encoding and rfc822msg.encoding != encoding rfc822msg << str ### send email smtp = Net::SMTP.new(@address, @port) smtp.enable_starttls_auto if @enable_starttls_auto and smtp.respond_to? :enable_starttls_auto smtp.start(@domain, @user_name, @password, @authentication) { |s| s.sendmail(rfc822msg, @from, @to) } self rescue StandardError, TimeoutError => err self.level = :off ::Logsly::Logging182.log_internal {'e-mail notifications have been disabled'} ::Logsly::Logging182.log_internal(-2) {err} end
ruby
def canonical_write( str ) ### build a mail header for RFC 822 rfc822msg = "From: #{@from}\n" rfc822msg << "To: #{@to.join(",")}\n" rfc822msg << "Subject: #{@subject}\n" rfc822msg << "Date: #{Time.new.rfc822}\n" rfc822msg << "Message-Id: <#{"%.8f" % Time.now.to_f}@#{@domain}>\n\n" rfc822msg = rfc822msg.force_encoding(encoding) if encoding and rfc822msg.encoding != encoding rfc822msg << str ### send email smtp = Net::SMTP.new(@address, @port) smtp.enable_starttls_auto if @enable_starttls_auto and smtp.respond_to? :enable_starttls_auto smtp.start(@domain, @user_name, @password, @authentication) { |s| s.sendmail(rfc822msg, @from, @to) } self rescue StandardError, TimeoutError => err self.level = :off ::Logsly::Logging182.log_internal {'e-mail notifications have been disabled'} ::Logsly::Logging182.log_internal(-2) {err} end
[ "def", "canonical_write", "(", "str", ")", "### build a mail header for RFC 822", "rfc822msg", "=", "\"From: #{@from}\\n\"", "rfc822msg", "<<", "\"To: #{@to.join(\",\")}\\n\"", "rfc822msg", "<<", "\"Subject: #{@subject}\\n\"", "rfc822msg", "<<", "\"Date: #{Time.new.rfc822}\\n\"", "rfc822msg", "<<", "\"Message-Id: <#{\"%.8f\" % Time.now.to_f}@#{@domain}>\\n\\n\"", "rfc822msg", "=", "rfc822msg", ".", "force_encoding", "(", "encoding", ")", "if", "encoding", "and", "rfc822msg", ".", "encoding", "!=", "encoding", "rfc822msg", "<<", "str", "### send email", "smtp", "=", "Net", "::", "SMTP", ".", "new", "(", "@address", ",", "@port", ")", "smtp", ".", "enable_starttls_auto", "if", "@enable_starttls_auto", "and", "smtp", ".", "respond_to?", ":enable_starttls_auto", "smtp", ".", "start", "(", "@domain", ",", "@user_name", ",", "@password", ",", "@authentication", ")", "{", "|", "s", "|", "s", ".", "sendmail", "(", "rfc822msg", ",", "@from", ",", "@to", ")", "}", "self", "rescue", "StandardError", ",", "TimeoutError", "=>", "err", "self", ".", "level", "=", ":off", "::", "Logsly", "::", "Logging182", ".", "log_internal", "{", "'e-mail notifications have been disabled'", "}", "::", "Logsly", "::", "Logging182", ".", "log_internal", "(", "-", "2", ")", "{", "err", "}", "end" ]
This method is called by the buffering code when messages need to be sent out as an email.
[ "This", "method", "is", "called", "by", "the", "buffering", "code", "when", "messages", "need", "to", "be", "sent", "out", "as", "an", "email", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/email.rb#L154-L174
9,619
acro5piano/selenium_standalone_dsl
lib/selenium_standalone_dsl/base.rb
SeleniumStandaloneDSL.Base.click
def click(selector, find_by: :link_text) sleep Random.new.rand(1..2) with_frame do @driver.find_element(find_by, selector).click end sleep Random.new.rand(1..2) end
ruby
def click(selector, find_by: :link_text) sleep Random.new.rand(1..2) with_frame do @driver.find_element(find_by, selector).click end sleep Random.new.rand(1..2) end
[ "def", "click", "(", "selector", ",", "find_by", ":", ":link_text", ")", "sleep", "Random", ".", "new", ".", "rand", "(", "1", "..", "2", ")", "with_frame", "do", "@driver", ".", "find_element", "(", "find_by", ",", "selector", ")", ".", "click", "end", "sleep", "Random", ".", "new", ".", "rand", "(", "1", "..", "2", ")", "end" ]
The following methods are utility methods for SeleniumStandaloneDsl-DSL. You can easily handle driver with this DSL.
[ "The", "following", "methods", "are", "utility", "methods", "for", "SeleniumStandaloneDsl", "-", "DSL", ".", "You", "can", "easily", "handle", "driver", "with", "this", "DSL", "." ]
3eec04012905ef35804ddf362eac69bfbe2c7646
https://github.com/acro5piano/selenium_standalone_dsl/blob/3eec04012905ef35804ddf362eac69bfbe2c7646/lib/selenium_standalone_dsl/base.rb#L31-L37
9,620
bottiger/Blog_Basic
app/models/blog_basic/blog_post.rb
BlogBasic.BlogPost.replace_blog_image_tags
def replace_blog_image_tags @resaving = true self.body.gsub!(/[{]blog_image:upload[0-9]+:[a-zA-Z]+[}]/) do |image_tag| random_id, size = image_tag.scan(/upload([0-9]+)[:]([a-zA-Z]+)/).flatten new_id = random_id matching_image = self.blog_images.reject {|bi| !bi.random_id || bi.random_id != random_id }.first if matching_image new_id = matching_image.id end "{blog_image:#{new_id}:#{size}}" end self.save @resaving = false return true end
ruby
def replace_blog_image_tags @resaving = true self.body.gsub!(/[{]blog_image:upload[0-9]+:[a-zA-Z]+[}]/) do |image_tag| random_id, size = image_tag.scan(/upload([0-9]+)[:]([a-zA-Z]+)/).flatten new_id = random_id matching_image = self.blog_images.reject {|bi| !bi.random_id || bi.random_id != random_id }.first if matching_image new_id = matching_image.id end "{blog_image:#{new_id}:#{size}}" end self.save @resaving = false return true end
[ "def", "replace_blog_image_tags", "@resaving", "=", "true", "self", ".", "body", ".", "gsub!", "(", "/", "/", ")", "do", "|", "image_tag", "|", "random_id", ",", "size", "=", "image_tag", ".", "scan", "(", "/", "/", ")", ".", "flatten", "new_id", "=", "random_id", "matching_image", "=", "self", ".", "blog_images", ".", "reject", "{", "|", "bi", "|", "!", "bi", ".", "random_id", "||", "bi", ".", "random_id", "!=", "random_id", "}", ".", "first", "if", "matching_image", "new_id", "=", "matching_image", ".", "id", "end", "\"{blog_image:#{new_id}:#{size}}\"", "end", "self", ".", "save", "@resaving", "=", "false", "return", "true", "end" ]
For images that haven't been uploaded yet, they get a random image id with 'upload' infront of it. We replace those with their new image id
[ "For", "images", "that", "haven", "t", "been", "uploaded", "yet", "they", "get", "a", "random", "image", "id", "with", "upload", "infront", "of", "it", ".", "We", "replace", "those", "with", "their", "new", "image", "id" ]
9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440
https://github.com/bottiger/Blog_Basic/blob/9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440/app/models/blog_basic/blog_post.rb#L50-L70
9,621
cknadler/versed
lib/versed/schedule.rb
Versed.Schedule.incomplete_tasks
def incomplete_tasks # TODO: refactor with reject incomplete = [] categories.each { |c| incomplete << c if c.incomplete? } incomplete.sort_by { |c| [-c.percent_incomplete, -c.total_min_incomplete] } end
ruby
def incomplete_tasks # TODO: refactor with reject incomplete = [] categories.each { |c| incomplete << c if c.incomplete? } incomplete.sort_by { |c| [-c.percent_incomplete, -c.total_min_incomplete] } end
[ "def", "incomplete_tasks", "# TODO: refactor with reject", "incomplete", "=", "[", "]", "categories", ".", "each", "{", "|", "c", "|", "incomplete", "<<", "c", "if", "c", ".", "incomplete?", "}", "incomplete", ".", "sort_by", "{", "|", "c", "|", "[", "-", "c", ".", "percent_incomplete", ",", "-", "c", ".", "total_min_incomplete", "]", "}", "end" ]
Returns an array of incomplete tasks. This array is sorted first by percentage incomplete, then by total number of minutes incomplete.
[ "Returns", "an", "array", "of", "incomplete", "tasks", ".", "This", "array", "is", "sorted", "first", "by", "percentage", "incomplete", "then", "by", "total", "number", "of", "minutes", "incomplete", "." ]
44273de418686a6fb6f20da3b41c84b6d922cec6
https://github.com/cknadler/versed/blob/44273de418686a6fb6f20da3b41c84b6d922cec6/lib/versed/schedule.rb#L22-L27
9,622
cknadler/versed
lib/versed/schedule.rb
Versed.Schedule.category_ids
def category_ids(entries) category_ids = [] entries.each do |day, tasks| category_ids += tasks.keys end category_ids.uniq end
ruby
def category_ids(entries) category_ids = [] entries.each do |day, tasks| category_ids += tasks.keys end category_ids.uniq end
[ "def", "category_ids", "(", "entries", ")", "category_ids", "=", "[", "]", "entries", ".", "each", "do", "|", "day", ",", "tasks", "|", "category_ids", "+=", "tasks", ".", "keys", "end", "category_ids", ".", "uniq", "end" ]
Finds all unique category ids in a log or a schedule @param entries [Hash] A parsed log or schedule @return [Array, String] Unique category ids
[ "Finds", "all", "unique", "category", "ids", "in", "a", "log", "or", "a", "schedule" ]
44273de418686a6fb6f20da3b41c84b6d922cec6
https://github.com/cknadler/versed/blob/44273de418686a6fb6f20da3b41c84b6d922cec6/lib/versed/schedule.rb#L90-L96
9,623
georgyangelov/vcs-toolkit
lib/vcs_toolkit/merge.rb
VCSToolkit.Merge.combine_diffs
def combine_diffs(diff_one, diff_two) Hash.new { |hash, key| hash[key] = [[], []] }.tap do |combined_diff| diff_one.each do |change| combined_diff[change.old_position].first << change end diff_two.each do |change| combined_diff[change.old_position].last << change end end end
ruby
def combine_diffs(diff_one, diff_two) Hash.new { |hash, key| hash[key] = [[], []] }.tap do |combined_diff| diff_one.each do |change| combined_diff[change.old_position].first << change end diff_two.each do |change| combined_diff[change.old_position].last << change end end end
[ "def", "combine_diffs", "(", "diff_one", ",", "diff_two", ")", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "[", "[", "]", ",", "[", "]", "]", "}", ".", "tap", "do", "|", "combined_diff", "|", "diff_one", ".", "each", "do", "|", "change", "|", "combined_diff", "[", "change", ".", "old_position", "]", ".", "first", "<<", "change", "end", "diff_two", ".", "each", "do", "|", "change", "|", "combined_diff", "[", "change", ".", "old_position", "]", ".", "last", "<<", "change", "end", "end", "end" ]
Group changes by their old index. The structure is as follows: { <line_number_on_ancestor> => [ [ <change>, ... ], # The changes in the first file [ <change>, ... ] # The changes in the second file ] }
[ "Group", "changes", "by", "their", "old", "index", "." ]
9d73735da090a5e0f612aee04f423306fa512f38
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/merge.rb#L83-L93
9,624
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.children_values
def children_values(name = nil) children_values = [] each_child(false, name) { |child| case child.values.size when 0 children_values << nil when 1 children_values << child.value else children_values << child.values end } return children_values end
ruby
def children_values(name = nil) children_values = [] each_child(false, name) { |child| case child.values.size when 0 children_values << nil when 1 children_values << child.value else children_values << child.values end } return children_values end
[ "def", "children_values", "(", "name", "=", "nil", ")", "children_values", "=", "[", "]", "each_child", "(", "false", ",", "name", ")", "{", "|", "child", "|", "case", "child", ".", "values", ".", "size", "when", "0", "children_values", "<<", "nil", "when", "1", "children_values", "<<", "child", ".", "value", "else", "children_values", "<<", "child", ".", "values", "end", "}", "return", "children_values", "end" ]
Returns the values of all the children with the given +name+. If the child has more than one value, all the values will be added as an array. If the child has no value, +nil+ will be added. The search is not recursive. _name_:: if nil, all children are considered (nil by default).
[ "Returns", "the", "values", "of", "all", "the", "children", "with", "the", "given", "+", "name", "+", ".", "If", "the", "child", "has", "more", "than", "one", "value", "all", "the", "values", "will", "be", "added", "as", "an", "array", ".", "If", "the", "child", "has", "no", "value", "+", "nil", "+", "will", "be", "added", ".", "The", "search", "is", "not", "recursive", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L318-L331
9,625
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.each_child
def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block) if name == :DEFAULT name = namespace namespace = nil end @children.each do |child| if (name.nil? or child.name == name) and (namespace.nil? or child.namespace == namespace) yield child end child.children(recursive, namespace, name, &block) if recursive end return nil end
ruby
def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block) if name == :DEFAULT name = namespace namespace = nil end @children.each do |child| if (name.nil? or child.name == name) and (namespace.nil? or child.namespace == namespace) yield child end child.children(recursive, namespace, name, &block) if recursive end return nil end
[ "def", "each_child", "(", "recursive", "=", "false", ",", "namespace", "=", "nil", ",", "name", "=", ":DEFAULT", ",", "&", "block", ")", "if", "name", "==", ":DEFAULT", "name", "=", "namespace", "namespace", "=", "nil", "end", "@children", ".", "each", "do", "|", "child", "|", "if", "(", "name", ".", "nil?", "or", "child", ".", "name", "==", "name", ")", "and", "(", "namespace", ".", "nil?", "or", "child", ".", "namespace", "==", "namespace", ")", "yield", "child", "end", "child", ".", "children", "(", "recursive", ",", "namespace", ",", "name", ",", "block", ")", "if", "recursive", "end", "return", "nil", "end" ]
Enumerates the children +Tag+s of this Tag and calls the given block providing it the child as parameter. _recursive_:: if true, enumerate grand-children, etc, recursively _namespace_:: if not nil, indicates the namespace of the children to enumerate _name_:: if not nil, indicates the name of the children to enumerate
[ "Enumerates", "the", "children", "+", "Tag", "+", "s", "of", "this", "Tag", "and", "calls", "the", "given", "block", "providing", "it", "the", "child", "as", "parameter", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L378-L393
9,626
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.remove_value
def remove_value(v) index = @values.index(v) if index return !@values.delete_at(index).nil? else return false end end
ruby
def remove_value(v) index = @values.index(v) if index return !@values.delete_at(index).nil? else return false end end
[ "def", "remove_value", "(", "v", ")", "index", "=", "@values", ".", "index", "(", "v", ")", "if", "index", "return", "!", "@values", ".", "delete_at", "(", "index", ")", ".", "nil?", "else", "return", "false", "end", "end" ]
Removes the first occurence of the specified value from this Tag. _v_:: The value to remove Returns true If the value exists and is removed
[ "Removes", "the", "first", "occurence", "of", "the", "specified", "value", "from", "this", "Tag", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L457-L464
9,627
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.has_attribute?
def has_attribute?(namespace = nil, key = nil) namespace, key = to_nns namespace, key if namespace or key attributes = @attributesByNamespace[namespace] return attributes.nil? ? false : attributes.has_key?(key) else attributes { return true } return false end end
ruby
def has_attribute?(namespace = nil, key = nil) namespace, key = to_nns namespace, key if namespace or key attributes = @attributesByNamespace[namespace] return attributes.nil? ? false : attributes.has_key?(key) else attributes { return true } return false end end
[ "def", "has_attribute?", "(", "namespace", "=", "nil", ",", "key", "=", "nil", ")", "namespace", ",", "key", "=", "to_nns", "namespace", ",", "key", "if", "namespace", "or", "key", "attributes", "=", "@attributesByNamespace", "[", "namespace", "]", "return", "attributes", ".", "nil?", "?", "false", ":", "attributes", ".", "has_key?", "(", "key", ")", "else", "attributes", "{", "return", "true", "}", "return", "false", "end", "end" ]
Indicates whether there is at least an attribute in this Tag. has_attribute? Indicates whether there is the specified attribute exists in this Tag. has_attribute?(key) has_attribute?(namespace, key)
[ "Indicates", "whether", "there", "is", "at", "least", "an", "attribute", "in", "this", "Tag", ".", "has_attribute?" ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L559-L570
9,628
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.each_attribute
def each_attribute(namespace = nil, &block) # :yields: namespace, key, value if namespace.nil? @attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) } else attributes = @attributesByNamespace[namespace] unless attributes.nil? attributes.each_pair do |key, value| yield namespace, key, value end end end end
ruby
def each_attribute(namespace = nil, &block) # :yields: namespace, key, value if namespace.nil? @attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) } else attributes = @attributesByNamespace[namespace] unless attributes.nil? attributes.each_pair do |key, value| yield namespace, key, value end end end end
[ "def", "each_attribute", "(", "namespace", "=", "nil", ",", "&", "block", ")", "# :yields: namespace, key, value", "if", "namespace", ".", "nil?", "@attributesByNamespace", ".", "each_key", "{", "|", "a_namespace", "|", "each_attribute", "(", "a_namespace", ",", "block", ")", "}", "else", "attributes", "=", "@attributesByNamespace", "[", "namespace", "]", "unless", "attributes", ".", "nil?", "attributes", ".", "each_pair", "do", "|", "key", ",", "value", "|", "yield", "namespace", ",", "key", ",", "value", "end", "end", "end", "end" ]
Enumerates the attributes for the specified +namespace+. Enumerates all the attributes by default.
[ "Enumerates", "the", "attributes", "for", "the", "specified", "+", "namespace", "+", ".", "Enumerates", "all", "the", "attributes", "by", "default", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L635-L647
9,629
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.namespace=
def namespace=(a_namespace) a_namespace = a_namespace.to_s SDL4R.validate_identifier(a_namespace) unless a_namespace.empty? @namespace = a_namespace end
ruby
def namespace=(a_namespace) a_namespace = a_namespace.to_s SDL4R.validate_identifier(a_namespace) unless a_namespace.empty? @namespace = a_namespace end
[ "def", "namespace", "=", "(", "a_namespace", ")", "a_namespace", "=", "a_namespace", ".", "to_s", "SDL4R", ".", "validate_identifier", "(", "a_namespace", ")", "unless", "a_namespace", ".", "empty?", "@namespace", "=", "a_namespace", "end" ]
The namespace to set. +nil+ will be coerced to the empty string. Raises +ArgumentError+ if the namespace is non-blank and is not a legal SDL identifier (see SDL4R#validate_identifier)
[ "The", "namespace", "to", "set", ".", "+", "nil", "+", "will", "be", "coerced", "to", "the", "empty", "string", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L707-L711
9,630
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.read
def read(input) if input.is_a? String read_from_io(true) { StringIO.new(input) } elsif input.is_a? Pathname read_from_io(true) { input.open("r:UTF-8") } elsif input.is_a? URI read_from_io(true) { input.open } else read_from_io(false) { input } end return self end
ruby
def read(input) if input.is_a? String read_from_io(true) { StringIO.new(input) } elsif input.is_a? Pathname read_from_io(true) { input.open("r:UTF-8") } elsif input.is_a? URI read_from_io(true) { input.open } else read_from_io(false) { input } end return self end
[ "def", "read", "(", "input", ")", "if", "input", ".", "is_a?", "String", "read_from_io", "(", "true", ")", "{", "StringIO", ".", "new", "(", "input", ")", "}", "elsif", "input", ".", "is_a?", "Pathname", "read_from_io", "(", "true", ")", "{", "input", ".", "open", "(", "\"r:UTF-8\"", ")", "}", "elsif", "input", ".", "is_a?", "URI", "read_from_io", "(", "true", ")", "{", "input", ".", "open", "}", "else", "read_from_io", "(", "false", ")", "{", "input", "}", "end", "return", "self", "end" ]
Adds all the tags specified in the given IO, String, Pathname or URI to this Tag. Returns this Tag after adding all the children read from +input+.
[ "Adds", "all", "the", "tags", "specified", "in", "the", "given", "IO", "String", "Pathname", "or", "URI", "to", "this", "Tag", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L717-L732
9,631
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.read_from_io
def read_from_io(close_io) io = yield begin Parser.new(io).parse.each do |tag| add_child(tag) end ensure if close_io io.close rescue IOError end end end
ruby
def read_from_io(close_io) io = yield begin Parser.new(io).parse.each do |tag| add_child(tag) end ensure if close_io io.close rescue IOError end end end
[ "def", "read_from_io", "(", "close_io", ")", "io", "=", "yield", "begin", "Parser", ".", "new", "(", "io", ")", ".", "parse", ".", "each", "do", "|", "tag", "|", "add_child", "(", "tag", ")", "end", "ensure", "if", "close_io", "io", ".", "close", "rescue", "IOError", "end", "end", "end" ]
Reads and parses the +io+ returned by the specified block and closes this +io+ if +close_io+ is true.
[ "Reads", "and", "parses", "the", "+", "io", "+", "returned", "by", "the", "specified", "block", "and", "closes", "this", "+", "io", "+", "if", "+", "close_io", "+", "is", "true", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L736-L749
9,632
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.children_to_string
def children_to_string(line_prefix = "", s = "") @children.each do |child| s << child.to_string(line_prefix) << $/ end return s end
ruby
def children_to_string(line_prefix = "", s = "") @children.each do |child| s << child.to_string(line_prefix) << $/ end return s end
[ "def", "children_to_string", "(", "line_prefix", "=", "\"\"", ",", "s", "=", "\"\"", ")", "@children", ".", "each", "do", "|", "child", "|", "s", "<<", "child", ".", "to_string", "(", "line_prefix", ")", "<<", "$/", "end", "return", "s", "end" ]
Returns a string representation of the children tags. _linePrefix_:: A prefix to insert before every line. _s_:: a String that receives the string representation TODO: break up long lines using the backslash
[ "Returns", "a", "string", "representation", "of", "the", "children", "tags", "." ]
1663b9f5aa95d8d6269f060e343c2d2fd9309259
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L858-L864
9,633
charypar/cyclical
lib/cyclical/occurrence.rb
Cyclical.Occurrence.list_occurrences
def list_occurrences(from, direction = :forward, &block) raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time) results = [] n, current = init_loop(from, direction) loop do # Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}") # break on schedule span limits return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0) # break on block condition return results unless yield current results << current # step if direction == :forward current = @rule.next(current, @start_time) else current = @rule.previous(current, @start_time) end end end
ruby
def list_occurrences(from, direction = :forward, &block) raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time) results = [] n, current = init_loop(from, direction) loop do # Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}") # break on schedule span limits return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0) # break on block condition return results unless yield current results << current # step if direction == :forward current = @rule.next(current, @start_time) else current = @rule.previous(current, @start_time) end end end
[ "def", "list_occurrences", "(", "from", ",", "direction", "=", ":forward", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"From #{from} not matching the rule #{@rule} and start time #{@start_time}\"", "unless", "@rule", ".", "match?", "(", "from", ",", "@start_time", ")", "results", "=", "[", "]", "n", ",", "current", "=", "init_loop", "(", "from", ",", "direction", ")", "loop", "do", "# Rails.logger.debug(\"Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}\")", "# break on schedule span limits", "return", "results", "unless", "(", "current", ">=", "@start_time", ")", "&&", "(", "@rule", ".", "stop", ".", "nil?", "||", "current", "<", "@rule", ".", "stop", ")", "&&", "(", "@rule", ".", "count", ".", "nil?", "||", "(", "n", "-=", "1", ")", ">=", "0", ")", "# break on block condition", "return", "results", "unless", "yield", "current", "results", "<<", "current", "# step", "if", "direction", "==", ":forward", "current", "=", "@rule", ".", "next", "(", "current", ",", "@start_time", ")", "else", "current", "=", "@rule", ".", "previous", "(", "current", ",", "@start_time", ")", "end", "end", "end" ]
yields valid occurrences, return false from the block to stop
[ "yields", "valid", "occurrences", "return", "false", "from", "the", "block", "to", "stop" ]
8e45b8f83e2dd59fcad01e220412bb361867f5c6
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/occurrence.rb#L70-L93
9,634
sanichi/icu_tournament
lib/icu_tournament/team.rb
ICU.Team.add_member
def add_member(number) pnum = number.to_i raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/) raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum) @members.push(pnum) end
ruby
def add_member(number) pnum = number.to_i raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/) raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum) @members.push(pnum) end
[ "def", "add_member", "(", "number", ")", "pnum", "=", "number", ".", "to_i", "raise", "\"'#{number}' is not a valid as a team member player number\"", "if", "pnum", "==", "0", "&&", "!", "number", ".", "to_s", ".", "match", "(", "/", "\\d", "/", ")", "raise", "\"can't add duplicate player number #{pnum} to team '#{@name}'\"", "if", "@members", ".", "include?", "(", "pnum", ")", "@members", ".", "push", "(", "pnum", ")", "end" ]
Add a team member referenced by any integer.
[ "Add", "a", "team", "member", "referenced", "by", "any", "integer", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/team.rb#L57-L62
9,635
sanichi/icu_tournament
lib/icu_tournament/team.rb
ICU.Team.renumber
def renumber(map) @members.each_with_index do |pnum, index| raise "player number #{pnum} not found in renumbering hash" unless map[pnum] @members[index] = map[pnum] end self end
ruby
def renumber(map) @members.each_with_index do |pnum, index| raise "player number #{pnum} not found in renumbering hash" unless map[pnum] @members[index] = map[pnum] end self end
[ "def", "renumber", "(", "map", ")", "@members", ".", "each_with_index", "do", "|", "pnum", ",", "index", "|", "raise", "\"player number #{pnum} not found in renumbering hash\"", "unless", "map", "[", "pnum", "]", "@members", "[", "index", "]", "=", "map", "[", "pnum", "]", "end", "self", "end" ]
Renumber the players according to the supplied hash. Return self.
[ "Renumber", "the", "players", "according", "to", "the", "supplied", "hash", ".", "Return", "self", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/team.rb#L65-L71
9,636
mswart/cany
lib/cany/dependency.rb
Cany.Dependency.define_on_distro_release
def define_on_distro_release(distro, release, name, version=nil) distro_releases[[distro, release]] << [name, version] end
ruby
def define_on_distro_release(distro, release, name, version=nil) distro_releases[[distro, release]] << [name, version] end
[ "def", "define_on_distro_release", "(", "distro", ",", "release", ",", "name", ",", "version", "=", "nil", ")", "distro_releases", "[", "[", "distro", ",", "release", "]", "]", "<<", "[", "name", ",", "version", "]", "end" ]
Define the package name and an optional version constraint for a distribution release @param distro[Symbol] The distribution name like :ubuntu, :debian ... @param release[Symbol] The distribution release like :precise for ubuntu 12.04 @param name[String] A package name @param version[String, nil] A version constraint
[ "Define", "the", "package", "name", "and", "an", "optional", "version", "constraint", "for", "a", "distribution", "release" ]
0d2bf4d3704d4e9a222b11f6d764b57234ddf36d
https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/dependency.rb#L51-L53
9,637
jwtd/xively-rb-connector
lib/xively-rb-connector/connection.rb
XivelyConnector.Connection.set_httparty_options
def set_httparty_options(options={}) if options[:ssl_ca_file] ssl_ca_file opts[:ssl_ca_file] if options[:pem_cert_pass] pem File.read(options[:pem_cert]), options[:pem_cert_pass] else pem File.read(options[:pem_cert]) end end end
ruby
def set_httparty_options(options={}) if options[:ssl_ca_file] ssl_ca_file opts[:ssl_ca_file] if options[:pem_cert_pass] pem File.read(options[:pem_cert]), options[:pem_cert_pass] else pem File.read(options[:pem_cert]) end end end
[ "def", "set_httparty_options", "(", "options", "=", "{", "}", ")", "if", "options", "[", ":ssl_ca_file", "]", "ssl_ca_file", "opts", "[", ":ssl_ca_file", "]", "if", "options", "[", ":pem_cert_pass", "]", "pem", "File", ".", "read", "(", "options", "[", ":pem_cert", "]", ")", ",", "options", "[", ":pem_cert_pass", "]", "else", "pem", "File", ".", "read", "(", "options", "[", ":pem_cert", "]", ")", "end", "end", "end" ]
Set HTTParty params that we need to set after initialize is called These params come from @options within initialize and include the following: :ssl_ca_file - SSL CA File for SSL connections :format - 'json', 'xml', 'html', etc. || Defaults to 'xml' :format_header - :format Header string || Defaults to 'application/xml' :pem_cert - /path/to/a/pem_formatted_certificate.pem for SSL connections :pem_cert_pass - plaintext password, not recommended!
[ "Set", "HTTParty", "params", "that", "we", "need", "to", "set", "after", "initialize", "is", "called", "These", "params", "come", "from" ]
014c2e08d2857e67d65103b84ba23a91569baecb
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/connection.rb#L29-L38
9,638
nsi-iff/nsicloudooo-ruby
lib/nsicloudooo/client.rb
NSICloudooo.Client.granulate
def granulate(options = {}) @request_data = Hash.new if options[:doc_link] insert_download_data options else file_data = {:doc => options[:file], :filename => options[:filename]} @request_data.merge! file_data end insert_callback_data options request = prepare_request :POST, @request_data.to_json execute_request(request) end
ruby
def granulate(options = {}) @request_data = Hash.new if options[:doc_link] insert_download_data options else file_data = {:doc => options[:file], :filename => options[:filename]} @request_data.merge! file_data end insert_callback_data options request = prepare_request :POST, @request_data.to_json execute_request(request) end
[ "def", "granulate", "(", "options", "=", "{", "}", ")", "@request_data", "=", "Hash", ".", "new", "if", "options", "[", ":doc_link", "]", "insert_download_data", "options", "else", "file_data", "=", "{", ":doc", "=>", "options", "[", ":file", "]", ",", ":filename", "=>", "options", "[", ":filename", "]", "}", "@request_data", ".", "merge!", "file_data", "end", "insert_callback_data", "options", "request", "=", "prepare_request", ":POST", ",", "@request_data", ".", "to_json", "execute_request", "(", "request", ")", "end" ]
Send a document be granulated by a nsi.cloudooo node @param [Hash] options used to send a document to be graulated @option options [String] file the base64 encoded file to be granulated @option options [String] filename the filename of the document @note the filename is very importante, the cloudooo node will convert the document based on its filename, if necessary @option options [String] doc_link link to the document that'll be granulated @note if provided both doc_link and file options, file will be ignored and the client will download the document instead @option options [String] callback a callback url to the file granulation @option options [String] verb the callback request verb, when not provided, nsi.cloudooo default to POST @example A simple granulation doc = Base64.encode64(File.new('document.odt', 'r').read) nsicloudooo.granulate(:file => doc, :filename => 'document.odt') @example Downloading and granulating from web nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt') @example Sending a callback url doc = Base64.encode64(File.new('document.odt', 'r').read) nsicloudooo.granulate(:file => doc, :filename => 'document.odt', :callback => 'http://google.com') nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt', :callback => 'http://google.com') @example Using a custom verb to the callback doc = Base64.encode64(File.new('document.odt', 'r').read) nsicloudooo.granulate(:file => doc, :filename => 'document.odt', :callback => 'http://google.com', :verb => "PUT") nsicloudooo.granulate(:doc_link => 'http://google.com/document.odt', :callback => 'http://google.com', :verb => "PUT") @return [Hash] response * "key" [String] the key to access the granulated document if the sam node it was stored
[ "Send", "a", "document", "be", "granulated", "by", "a", "nsi", ".", "cloudooo", "node" ]
5cd92a0906187fa7da59d63d32608f99e22fa71d
https://github.com/nsi-iff/nsicloudooo-ruby/blob/5cd92a0906187fa7da59d63d32608f99e22fa71d/lib/nsicloudooo/client.rb#L42-L53
9,639
teodor-pripoae/scalaroid
lib/scalaroid/json_req_list.rb
Scalaroid.JSONReqList.add_write
def add_write(key, value, binary = false) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'write' => {key => JSONConnection.encode_value(value, binary)}} self end
ruby
def add_write(key, value, binary = false) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'write' => {key => JSONConnection.encode_value(value, binary)}} self end
[ "def", "add_write", "(", "key", ",", "value", ",", "binary", "=", "false", ")", "if", "(", "@is_commit", ")", "raise", "RuntimeError", ".", "new", "(", "'No further request supported after a commit!'", ")", "end", "@requests", "<<", "{", "'write'", "=>", "{", "key", "=>", "JSONConnection", ".", "encode_value", "(", "value", ",", "binary", ")", "}", "}", "self", "end" ]
Adds a write operation to the request list.
[ "Adds", "a", "write", "operation", "to", "the", "request", "list", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/json_req_list.rb#L23-L29
9,640
teodor-pripoae/scalaroid
lib/scalaroid/json_req_list.rb
Scalaroid.JSONReqList.add_add_del_on_list
def add_add_del_on_list(key, to_add, to_remove) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'add_del_on_list' => {'key' => key, 'add' => to_add, 'del'=> to_remove}} self end
ruby
def add_add_del_on_list(key, to_add, to_remove) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'add_del_on_list' => {'key' => key, 'add' => to_add, 'del'=> to_remove}} self end
[ "def", "add_add_del_on_list", "(", "key", ",", "to_add", ",", "to_remove", ")", "if", "(", "@is_commit", ")", "raise", "RuntimeError", ".", "new", "(", "'No further request supported after a commit!'", ")", "end", "@requests", "<<", "{", "'add_del_on_list'", "=>", "{", "'key'", "=>", "key", ",", "'add'", "=>", "to_add", ",", "'del'", "=>", "to_remove", "}", "}", "self", "end" ]
Adds a add_del_on_list operation to the request list.
[ "Adds", "a", "add_del_on_list", "operation", "to", "the", "request", "list", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/json_req_list.rb#L32-L38
9,641
mark-d-holmberg/handcart
lib/handcart/controller_additions.rb
Handcart.ControllerAdditions.allow_or_reject
def allow_or_reject # We assume the the rejection action is going to be on the public controller # since we wouldn't want to forward the rejection to the handcart my_rejection_url = main_app.url_for({ # subdomain: '', host: Handcart::DomainConstraint.default_constraint.domain, controller: @rejection_url.split("#").first, action: @rejection_url.split("#").last, trailing_slash: false, }) # See if they have enable IP blocking if they respond to that. if current_handcart.respond_to?(:enable_ip_blocking?) truthiness = current_handcart.enable_ip_blocking? else # Default to true truthiness = true end if truthiness ip_address = current_handcart.ip_addresses.permitted.find_by_address(request.remote_ip) if ip_address if Handcart.ip_authorization.strategy.is_in_range?(ip_address.address, current_handcart) # Do nothing, let them login else # # The strategy doesn't match redirect_to my_rejection_url end else # No IP Address was found redirect_to my_rejection_url end else # Do nothing, blocking mode is disabled end end
ruby
def allow_or_reject # We assume the the rejection action is going to be on the public controller # since we wouldn't want to forward the rejection to the handcart my_rejection_url = main_app.url_for({ # subdomain: '', host: Handcart::DomainConstraint.default_constraint.domain, controller: @rejection_url.split("#").first, action: @rejection_url.split("#").last, trailing_slash: false, }) # See if they have enable IP blocking if they respond to that. if current_handcart.respond_to?(:enable_ip_blocking?) truthiness = current_handcart.enable_ip_blocking? else # Default to true truthiness = true end if truthiness ip_address = current_handcart.ip_addresses.permitted.find_by_address(request.remote_ip) if ip_address if Handcart.ip_authorization.strategy.is_in_range?(ip_address.address, current_handcart) # Do nothing, let them login else # # The strategy doesn't match redirect_to my_rejection_url end else # No IP Address was found redirect_to my_rejection_url end else # Do nothing, blocking mode is disabled end end
[ "def", "allow_or_reject", "# We assume the the rejection action is going to be on the public controller", "# since we wouldn't want to forward the rejection to the handcart", "my_rejection_url", "=", "main_app", ".", "url_for", "(", "{", "# subdomain: '',", "host", ":", "Handcart", "::", "DomainConstraint", ".", "default_constraint", ".", "domain", ",", "controller", ":", "@rejection_url", ".", "split", "(", "\"#\"", ")", ".", "first", ",", "action", ":", "@rejection_url", ".", "split", "(", "\"#\"", ")", ".", "last", ",", "trailing_slash", ":", "false", ",", "}", ")", "# See if they have enable IP blocking if they respond to that.", "if", "current_handcart", ".", "respond_to?", "(", ":enable_ip_blocking?", ")", "truthiness", "=", "current_handcart", ".", "enable_ip_blocking?", "else", "# Default to true", "truthiness", "=", "true", "end", "if", "truthiness", "ip_address", "=", "current_handcart", ".", "ip_addresses", ".", "permitted", ".", "find_by_address", "(", "request", ".", "remote_ip", ")", "if", "ip_address", "if", "Handcart", ".", "ip_authorization", ".", "strategy", ".", "is_in_range?", "(", "ip_address", ".", "address", ",", "current_handcart", ")", "# Do nothing, let them login", "else", "# # The strategy doesn't match", "redirect_to", "my_rejection_url", "end", "else", "# No IP Address was found", "redirect_to", "my_rejection_url", "end", "else", "# Do nothing, blocking mode is disabled", "end", "end" ]
Don't allow unauthorized or blacklisted foreign IP addresses to hit what we assume is the session controller for the franchisee.
[ "Don", "t", "allow", "unauthorized", "or", "blacklisted", "foreign", "IP", "addresses", "to", "hit", "what", "we", "assume", "is", "the", "session", "controller", "for", "the", "franchisee", "." ]
9f9c7484db007066357c71c9c50f3342aab59c11
https://github.com/mark-d-holmberg/handcart/blob/9f9c7484db007066357c71c9c50f3342aab59c11/lib/handcart/controller_additions.rb#L108-L143
9,642
ossuarium/palimpsest
lib/palimpsest/environment.rb
Palimpsest.Environment.copy
def copy(destination: site.path, mirror: false) fail 'Must specify a destination' if destination.nil? exclude = options[:copy_exclude] exclude.concat config[:persistent] unless config[:persistent].nil? Utils.copy_directory directory, destination, exclude: exclude, mirror: mirror self end
ruby
def copy(destination: site.path, mirror: false) fail 'Must specify a destination' if destination.nil? exclude = options[:copy_exclude] exclude.concat config[:persistent] unless config[:persistent].nil? Utils.copy_directory directory, destination, exclude: exclude, mirror: mirror self end
[ "def", "copy", "(", "destination", ":", "site", ".", "path", ",", "mirror", ":", "false", ")", "fail", "'Must specify a destination'", "if", "destination", ".", "nil?", "exclude", "=", "options", "[", ":copy_exclude", "]", "exclude", ".", "concat", "config", "[", ":persistent", "]", "unless", "config", "[", ":persistent", "]", ".", "nil?", "Utils", ".", "copy_directory", "directory", ",", "destination", ",", "exclude", ":", "exclude", ",", "mirror", ":", "mirror", "self", "end" ]
Copy the contents of the working directory. @param destination [String] path to copy environment's files to @param mirror [Boolean] remove any non-excluded paths from destination @return [Environment] the current environment instance
[ "Copy", "the", "contents", "of", "the", "working", "directory", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L211-L217
9,643
ossuarium/palimpsest
lib/palimpsest/environment.rb
Palimpsest.Environment.populate
def populate(from: :auto) return if populated fail "Cannot populate without 'site'" if site.nil? case from when :auto if site.respond_to?(:repository) ? site.repository : nil populate from: :repository else populate from: :source end when :repository fail "Cannot populate without 'reference'" if reference.empty? repo.extract directory, reference: reference @populated = true when :source source = site.source.nil? ? '.' : site.source Utils.copy_directory source, directory, exclude: options[:copy_exclude] @populated = true end self end
ruby
def populate(from: :auto) return if populated fail "Cannot populate without 'site'" if site.nil? case from when :auto if site.respond_to?(:repository) ? site.repository : nil populate from: :repository else populate from: :source end when :repository fail "Cannot populate without 'reference'" if reference.empty? repo.extract directory, reference: reference @populated = true when :source source = site.source.nil? ? '.' : site.source Utils.copy_directory source, directory, exclude: options[:copy_exclude] @populated = true end self end
[ "def", "populate", "(", "from", ":", ":auto", ")", "return", "if", "populated", "fail", "\"Cannot populate without 'site'\"", "if", "site", ".", "nil?", "case", "from", "when", ":auto", "if", "site", ".", "respond_to?", "(", ":repository", ")", "?", "site", ".", "repository", ":", "nil", "populate", "from", ":", ":repository", "else", "populate", "from", ":", ":source", "end", "when", ":repository", "fail", "\"Cannot populate without 'reference'\"", "if", "reference", ".", "empty?", "repo", ".", "extract", "directory", ",", "reference", ":", "reference", "@populated", "=", "true", "when", ":source", "source", "=", "site", ".", "source", ".", "nil?", "?", "'.'", ":", "site", ".", "source", "Utils", ".", "copy_directory", "source", ",", "directory", ",", "exclude", ":", "options", "[", ":copy_exclude", "]", "@populated", "=", "true", "end", "self", "end" ]
Extracts the site's files from repository to the working directory. @return [Environment] the current environment instance
[ "Extracts", "the", "site", "s", "files", "from", "repository", "to", "the", "working", "directory", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L233-L255
9,644
ossuarium/palimpsest
lib/palimpsest/environment.rb
Palimpsest.Environment.validate_config
def validate_config message = 'bad path in config' # Checks the option in the asset key. def validate_asset_options(opts) opts.each do |k, v| fail 'bad option in config' if k == :sprockets_options fail message if k == :output && !Utils.safe_path?(v) end end @config[:excludes].each do |v| fail message unless Utils.safe_path? v end unless @config[:excludes].nil? @config[:external].each do |k, v| next if k == :server v.each do |repo| fail message unless Utils.safe_path? repo[1] end unless v.nil? end unless @config[:external].nil? @config[:components].each do |k, v| # process @config[:components][:base] then go to the next option if k == :base fail message unless Utils.safe_path? v next end unless v.nil? # process @config[:components][:paths] if k == :paths v.each do |path| fail message unless Utils.safe_path? path[0] fail message unless Utils.safe_path? path[1] end end end unless @config[:components].nil? @config[:assets].each do |k, v| # process @config[:assets][:options] then go to the next option if k == :options validate_asset_options v next end unless v.nil? # process @config[:assets][:sources] then go to the next option if k == :sources v.each_with_index do |source, _| fail message unless Utils.safe_path? source end next end # process each asset type in @config[:assets] v.each do |asset_key, asset_value| # process :options if asset_key == :options validate_asset_options asset_value next end unless asset_value.nil? # process each asset path asset_value.each_with_index do |path, _| fail message unless Utils.safe_path? path end if asset_key == :paths end end unless @config[:assets].nil? @config end
ruby
def validate_config message = 'bad path in config' # Checks the option in the asset key. def validate_asset_options(opts) opts.each do |k, v| fail 'bad option in config' if k == :sprockets_options fail message if k == :output && !Utils.safe_path?(v) end end @config[:excludes].each do |v| fail message unless Utils.safe_path? v end unless @config[:excludes].nil? @config[:external].each do |k, v| next if k == :server v.each do |repo| fail message unless Utils.safe_path? repo[1] end unless v.nil? end unless @config[:external].nil? @config[:components].each do |k, v| # process @config[:components][:base] then go to the next option if k == :base fail message unless Utils.safe_path? v next end unless v.nil? # process @config[:components][:paths] if k == :paths v.each do |path| fail message unless Utils.safe_path? path[0] fail message unless Utils.safe_path? path[1] end end end unless @config[:components].nil? @config[:assets].each do |k, v| # process @config[:assets][:options] then go to the next option if k == :options validate_asset_options v next end unless v.nil? # process @config[:assets][:sources] then go to the next option if k == :sources v.each_with_index do |source, _| fail message unless Utils.safe_path? source end next end # process each asset type in @config[:assets] v.each do |asset_key, asset_value| # process :options if asset_key == :options validate_asset_options asset_value next end unless asset_value.nil? # process each asset path asset_value.each_with_index do |path, _| fail message unless Utils.safe_path? path end if asset_key == :paths end end unless @config[:assets].nil? @config end
[ "def", "validate_config", "message", "=", "'bad path in config'", "# Checks the option in the asset key.", "def", "validate_asset_options", "(", "opts", ")", "opts", ".", "each", "do", "|", "k", ",", "v", "|", "fail", "'bad option in config'", "if", "k", "==", ":sprockets_options", "fail", "message", "if", "k", "==", ":output", "&&", "!", "Utils", ".", "safe_path?", "(", "v", ")", "end", "end", "@config", "[", ":excludes", "]", ".", "each", "do", "|", "v", "|", "fail", "message", "unless", "Utils", ".", "safe_path?", "v", "end", "unless", "@config", "[", ":excludes", "]", ".", "nil?", "@config", "[", ":external", "]", ".", "each", "do", "|", "k", ",", "v", "|", "next", "if", "k", "==", ":server", "v", ".", "each", "do", "|", "repo", "|", "fail", "message", "unless", "Utils", ".", "safe_path?", "repo", "[", "1", "]", "end", "unless", "v", ".", "nil?", "end", "unless", "@config", "[", ":external", "]", ".", "nil?", "@config", "[", ":components", "]", ".", "each", "do", "|", "k", ",", "v", "|", "# process @config[:components][:base] then go to the next option", "if", "k", "==", ":base", "fail", "message", "unless", "Utils", ".", "safe_path?", "v", "next", "end", "unless", "v", ".", "nil?", "# process @config[:components][:paths]", "if", "k", "==", ":paths", "v", ".", "each", "do", "|", "path", "|", "fail", "message", "unless", "Utils", ".", "safe_path?", "path", "[", "0", "]", "fail", "message", "unless", "Utils", ".", "safe_path?", "path", "[", "1", "]", "end", "end", "end", "unless", "@config", "[", ":components", "]", ".", "nil?", "@config", "[", ":assets", "]", ".", "each", "do", "|", "k", ",", "v", "|", "# process @config[:assets][:options] then go to the next option", "if", "k", "==", ":options", "validate_asset_options", "v", "next", "end", "unless", "v", ".", "nil?", "# process @config[:assets][:sources] then go to the next option", "if", "k", "==", ":sources", "v", ".", "each_with_index", "do", "|", "source", ",", "_", "|", "fail", "message", "unless", "Utils", ".", "safe_path?", "source", "end", "next", "end", "# process each asset type in @config[:assets]", "v", ".", "each", "do", "|", "asset_key", ",", "asset_value", "|", "# process :options", "if", "asset_key", "==", ":options", "validate_asset_options", "asset_value", "next", "end", "unless", "asset_value", ".", "nil?", "# process each asset path", "asset_value", ".", "each_with_index", "do", "|", "path", ",", "_", "|", "fail", "message", "unless", "Utils", ".", "safe_path?", "path", "end", "if", "asset_key", "==", ":paths", "end", "end", "unless", "@config", "[", ":assets", "]", ".", "nil?", "@config", "end" ]
Checks the config file for invalid settings. @todo Refactor this. - Checks that paths are not absolute or use `../` or `~/`.
[ "Checks", "the", "config", "file", "for", "invalid", "settings", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/environment.rb#L408-L478
9,645
npepinpe/redstruct
lib/redstruct/time_series.rb
Redstruct.TimeSeries.get
def get(options = {}) lower = nil upper = nil if options[:in].nil? lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after]) upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max else lower = coerce_time_milli(options[:in].begin) upper = coerce_time_milli(options[:in].end) upper = "(#{upper}" if options[:in].exclude_end? end argv = [expires_at, lower, upper] unless options[:limit].nil? limit = options[:limit].to_i raise ArgumentError, 'limit must be positive' unless limit.positive? argv.push(limit, [0, options[:offset].to_i].max) end events = get_script(keys: @event_list.key, argv: argv) return events.map(&method(:remove_event_id)) end
ruby
def get(options = {}) lower = nil upper = nil if options[:in].nil? lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after]) upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max else lower = coerce_time_milli(options[:in].begin) upper = coerce_time_milli(options[:in].end) upper = "(#{upper}" if options[:in].exclude_end? end argv = [expires_at, lower, upper] unless options[:limit].nil? limit = options[:limit].to_i raise ArgumentError, 'limit must be positive' unless limit.positive? argv.push(limit, [0, options[:offset].to_i].max) end events = get_script(keys: @event_list.key, argv: argv) return events.map(&method(:remove_event_id)) end
[ "def", "get", "(", "options", "=", "{", "}", ")", "lower", "=", "nil", "upper", "=", "nil", "if", "options", "[", ":in", "]", ".", "nil?", "lower", "=", "options", "[", ":after", "]", ".", "nil?", "?", "'-inf'", ":", "coerce_time_milli", "(", "options", "[", ":after", "]", ")", "upper", "=", "options", "[", ":before", "]", ".", "nil?", "?", "'+inf'", ":", "[", "0", ",", "coerce_time_milli", "(", "options", "[", ":before", "]", ")", "]", ".", "max", "else", "lower", "=", "coerce_time_milli", "(", "options", "[", ":in", "]", ".", "begin", ")", "upper", "=", "coerce_time_milli", "(", "options", "[", ":in", "]", ".", "end", ")", "upper", "=", "\"(#{upper}\"", "if", "options", "[", ":in", "]", ".", "exclude_end?", "end", "argv", "=", "[", "expires_at", ",", "lower", ",", "upper", "]", "unless", "options", "[", ":limit", "]", ".", "nil?", "limit", "=", "options", "[", ":limit", "]", ".", "to_i", "raise", "ArgumentError", ",", "'limit must be positive'", "unless", "limit", ".", "positive?", "argv", ".", "push", "(", "limit", ",", "[", "0", ",", "options", "[", ":offset", "]", ".", "to_i", "]", ".", "max", ")", "end", "events", "=", "get_script", "(", "keys", ":", "@event_list", ".", "key", ",", "argv", ":", "argv", ")", "return", "events", ".", "map", "(", "method", "(", ":remove_event_id", ")", ")", "end" ]
Returns data points from within a given time range. @param [Hash] options @option options [Time] :before optional upper bound to select events (inclusive) @option options [Time] :after optional lower bound to select events (inclusive) @option options [Range<Time>] :in optional range of time to select events (has priority over after/before) @option options [Integer] :limit maximum number of events to return @option options [Integer] :offset offset in the list (use in conjunction with limit for pagination)
[ "Returns", "data", "points", "from", "within", "a", "given", "time", "range", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/time_series.rb#L68-L91
9,646
jimjh/genie-parser
lib/spirit/logger.rb
Spirit.Logger.record
def record(action, *args) msg = '' msg << color(ACTION_COLORS[action]) msg << action_padding(action) + action.to_s msg << color(:clear) msg << ' ' + args.join(' ') info msg end
ruby
def record(action, *args) msg = '' msg << color(ACTION_COLORS[action]) msg << action_padding(action) + action.to_s msg << color(:clear) msg << ' ' + args.join(' ') info msg end
[ "def", "record", "(", "action", ",", "*", "args", ")", "msg", "=", "''", "msg", "<<", "color", "(", "ACTION_COLORS", "[", "action", "]", ")", "msg", "<<", "action_padding", "(", "action", ")", "+", "action", ".", "to_s", "msg", "<<", "color", "(", ":clear", ")", "msg", "<<", "' '", "+", "args", ".", "join", "(", "' '", ")", "info", "msg", "end" ]
Record that an action has occurred.
[ "Record", "that", "an", "action", "has", "occurred", "." ]
d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932
https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/logger.rb#L17-L24
9,647
jimjh/genie-parser
lib/spirit/logger.rb
Spirit.Logger.max_action_length
def max_action_length @max_action_length ||= actions.reduce(0) { |m, a| [m, a.to_s.length].max } end
ruby
def max_action_length @max_action_length ||= actions.reduce(0) { |m, a| [m, a.to_s.length].max } end
[ "def", "max_action_length", "@max_action_length", "||=", "actions", ".", "reduce", "(", "0", ")", "{", "|", "m", ",", "a", "|", "[", "m", ",", "a", ".", "to_s", ".", "length", "]", ".", "max", "}", "end" ]
the maximum length of all the actions known to the logger.
[ "the", "maximum", "length", "of", "all", "the", "actions", "known", "to", "the", "logger", "." ]
d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932
https://github.com/jimjh/genie-parser/blob/d627c1c1cc07c0ea082a2599ee45cd7e7ba9c932/lib/spirit/logger.rb#L38-L40
9,648
jacquescrocker/viewfu
lib/view_fu/browser_detect.rb
ViewFu.BrowserDetect.browser_name
def browser_name @browser_name ||= begin ua = request.user_agent.to_s.downcase if ua.index('msie') && !ua.index('opera') && !ua.index('webtv') 'ie'+ua[ua.index('msie')+5].chr elsif ua.index('gecko/') 'gecko' elsif ua.index('opera') 'opera' elsif ua.index('konqueror') 'konqueror' elsif ua.index('iphone') 'iphone' elsif ua.index('applewebkit/') 'safari' elsif ua.index('mozilla/') 'gecko' else "" end end end
ruby
def browser_name @browser_name ||= begin ua = request.user_agent.to_s.downcase if ua.index('msie') && !ua.index('opera') && !ua.index('webtv') 'ie'+ua[ua.index('msie')+5].chr elsif ua.index('gecko/') 'gecko' elsif ua.index('opera') 'opera' elsif ua.index('konqueror') 'konqueror' elsif ua.index('iphone') 'iphone' elsif ua.index('applewebkit/') 'safari' elsif ua.index('mozilla/') 'gecko' else "" end end end
[ "def", "browser_name", "@browser_name", "||=", "begin", "ua", "=", "request", ".", "user_agent", ".", "to_s", ".", "downcase", "if", "ua", ".", "index", "(", "'msie'", ")", "&&", "!", "ua", ".", "index", "(", "'opera'", ")", "&&", "!", "ua", ".", "index", "(", "'webtv'", ")", "'ie'", "+", "ua", "[", "ua", ".", "index", "(", "'msie'", ")", "+", "5", "]", ".", "chr", "elsif", "ua", ".", "index", "(", "'gecko/'", ")", "'gecko'", "elsif", "ua", ".", "index", "(", "'opera'", ")", "'opera'", "elsif", "ua", ".", "index", "(", "'konqueror'", ")", "'konqueror'", "elsif", "ua", ".", "index", "(", "'iphone'", ")", "'iphone'", "elsif", "ua", ".", "index", "(", "'applewebkit/'", ")", "'safari'", "elsif", "ua", ".", "index", "(", "'mozilla/'", ")", "'gecko'", "else", "\"\"", "end", "end", "end" ]
find the current browser name
[ "find", "the", "current", "browser", "name" ]
a21946e74553a1e83790ba7ea2a2ef4daa729458
https://github.com/jacquescrocker/viewfu/blob/a21946e74553a1e83790ba7ea2a2ef4daa729458/lib/view_fu/browser_detect.rb#L23-L44
9,649
nilsding/Empyrean
lib/empyrean/configloader.rb
Empyrean.ConfigLoader.load
def load(file) if File.exist? file symbolize_keys(YAML.load_file(File.expand_path('.', file))) else {} end end
ruby
def load(file) if File.exist? file symbolize_keys(YAML.load_file(File.expand_path('.', file))) else {} end end
[ "def", "load", "(", "file", ")", "if", "File", ".", "exist?", "file", "symbolize_keys", "(", "YAML", ".", "load_file", "(", "File", ".", "expand_path", "(", "'.'", ",", "file", ")", ")", ")", "else", "{", "}", "end", "end" ]
Loads a YAML file, parses it and returns a hash with symbolized keys.
[ "Loads", "a", "YAML", "file", "parses", "it", "and", "returns", "a", "hash", "with", "symbolized", "keys", "." ]
e652fb8966dfcd32968789af75e8d5a4f63134ec
https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/configloader.rb#L30-L36
9,650
nilsding/Empyrean
lib/empyrean/configloader.rb
Empyrean.ConfigLoader.load_config
def load_config(file = @options.config) config = load(file) config[:timezone_difference] = 0 if config[:timezone_difference].nil? config[:mentions] = {} if config[:mentions].nil? config[:mentions][:enabled] = true if config[:mentions][:enabled].nil? config[:mentions][:top] = 10 if config[:mentions][:top].nil? config[:mentions][:notop] = 20 if config[:mentions][:notop].nil? config[:clients] = {} if config[:clients].nil? config[:clients][:enabled] = true if config[:clients][:enabled].nil? config[:clients][:top] = 10 if config[:clients][:top].nil? config[:clients][:notop] = 20 if config[:clients][:notop].nil? config[:hashtags] = {} if config[:hashtags].nil? config[:hashtags][:enabled] = true if config[:hashtags][:enabled].nil? config[:hashtags][:top] = 10 if config[:hashtags][:top].nil? config[:hashtags][:notop] = 20 if config[:hashtags][:notop].nil? config[:smileys] = {} if config[:smileys].nil? config[:smileys][:enabled] = true if config[:smileys][:enabled].nil? config[:smileys][:top] = 10 if config[:smileys][:top].nil? config[:smileys][:notop] = 0 if config[:smileys][:notop].nil? config[:ignored_users] = [] if config[:ignored_users].nil? config[:renamed_users] = [] if config[:renamed_users].nil? args_override config end
ruby
def load_config(file = @options.config) config = load(file) config[:timezone_difference] = 0 if config[:timezone_difference].nil? config[:mentions] = {} if config[:mentions].nil? config[:mentions][:enabled] = true if config[:mentions][:enabled].nil? config[:mentions][:top] = 10 if config[:mentions][:top].nil? config[:mentions][:notop] = 20 if config[:mentions][:notop].nil? config[:clients] = {} if config[:clients].nil? config[:clients][:enabled] = true if config[:clients][:enabled].nil? config[:clients][:top] = 10 if config[:clients][:top].nil? config[:clients][:notop] = 20 if config[:clients][:notop].nil? config[:hashtags] = {} if config[:hashtags].nil? config[:hashtags][:enabled] = true if config[:hashtags][:enabled].nil? config[:hashtags][:top] = 10 if config[:hashtags][:top].nil? config[:hashtags][:notop] = 20 if config[:hashtags][:notop].nil? config[:smileys] = {} if config[:smileys].nil? config[:smileys][:enabled] = true if config[:smileys][:enabled].nil? config[:smileys][:top] = 10 if config[:smileys][:top].nil? config[:smileys][:notop] = 0 if config[:smileys][:notop].nil? config[:ignored_users] = [] if config[:ignored_users].nil? config[:renamed_users] = [] if config[:renamed_users].nil? args_override config end
[ "def", "load_config", "(", "file", "=", "@options", ".", "config", ")", "config", "=", "load", "(", "file", ")", "config", "[", ":timezone_difference", "]", "=", "0", "if", "config", "[", ":timezone_difference", "]", ".", "nil?", "config", "[", ":mentions", "]", "=", "{", "}", "if", "config", "[", ":mentions", "]", ".", "nil?", "config", "[", ":mentions", "]", "[", ":enabled", "]", "=", "true", "if", "config", "[", ":mentions", "]", "[", ":enabled", "]", ".", "nil?", "config", "[", ":mentions", "]", "[", ":top", "]", "=", "10", "if", "config", "[", ":mentions", "]", "[", ":top", "]", ".", "nil?", "config", "[", ":mentions", "]", "[", ":notop", "]", "=", "20", "if", "config", "[", ":mentions", "]", "[", ":notop", "]", ".", "nil?", "config", "[", ":clients", "]", "=", "{", "}", "if", "config", "[", ":clients", "]", ".", "nil?", "config", "[", ":clients", "]", "[", ":enabled", "]", "=", "true", "if", "config", "[", ":clients", "]", "[", ":enabled", "]", ".", "nil?", "config", "[", ":clients", "]", "[", ":top", "]", "=", "10", "if", "config", "[", ":clients", "]", "[", ":top", "]", ".", "nil?", "config", "[", ":clients", "]", "[", ":notop", "]", "=", "20", "if", "config", "[", ":clients", "]", "[", ":notop", "]", ".", "nil?", "config", "[", ":hashtags", "]", "=", "{", "}", "if", "config", "[", ":hashtags", "]", ".", "nil?", "config", "[", ":hashtags", "]", "[", ":enabled", "]", "=", "true", "if", "config", "[", ":hashtags", "]", "[", ":enabled", "]", ".", "nil?", "config", "[", ":hashtags", "]", "[", ":top", "]", "=", "10", "if", "config", "[", ":hashtags", "]", "[", ":top", "]", ".", "nil?", "config", "[", ":hashtags", "]", "[", ":notop", "]", "=", "20", "if", "config", "[", ":hashtags", "]", "[", ":notop", "]", ".", "nil?", "config", "[", ":smileys", "]", "=", "{", "}", "if", "config", "[", ":smileys", "]", ".", "nil?", "config", "[", ":smileys", "]", "[", ":enabled", "]", "=", "true", "if", "config", "[", ":smileys", "]", "[", ":enabled", "]", ".", "nil?", "config", "[", ":smileys", "]", "[", ":top", "]", "=", "10", "if", "config", "[", ":smileys", "]", "[", ":top", "]", ".", "nil?", "config", "[", ":smileys", "]", "[", ":notop", "]", "=", "0", "if", "config", "[", ":smileys", "]", "[", ":notop", "]", ".", "nil?", "config", "[", ":ignored_users", "]", "=", "[", "]", "if", "config", "[", ":ignored_users", "]", ".", "nil?", "config", "[", ":renamed_users", "]", "=", "[", "]", "if", "config", "[", ":renamed_users", "]", ".", "nil?", "args_override", "config", "end" ]
Loads a YAML file, parses it and checks if all values are given. If a value is missing, it will be set with the default value.
[ "Loads", "a", "YAML", "file", "parses", "it", "and", "checks", "if", "all", "values", "are", "given", ".", "If", "a", "value", "is", "missing", "it", "will", "be", "set", "with", "the", "default", "value", "." ]
e652fb8966dfcd32968789af75e8d5a4f63134ec
https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/configloader.rb#L40-L62
9,651
ecssiah/project-euler-cli
lib/project_euler_cli/archive_viewer.rb
ProjectEulerCli.ArchiveViewer.display_recent
def display_recent load_recent puts (Problem.total).downto(Problem.total - 9) do |i| puts "#{i} - #{Problem[i].title}" end end
ruby
def display_recent load_recent puts (Problem.total).downto(Problem.total - 9) do |i| puts "#{i} - #{Problem[i].title}" end end
[ "def", "display_recent", "load_recent", "puts", "(", "Problem", ".", "total", ")", ".", "downto", "(", "Problem", ".", "total", "-", "9", ")", "do", "|", "i", "|", "puts", "\"#{i} - #{Problem[i].title}\"", "end", "end" ]
Displays the 10 most recently added problems.
[ "Displays", "the", "10", "most", "recently", "added", "problems", "." ]
ae6fb1fb516bd9bcf193e3e1f1c82894198fe997
https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L12-L20
9,652
ecssiah/project-euler-cli
lib/project_euler_cli/archive_viewer.rb
ProjectEulerCli.ArchiveViewer.display_page
def display_page(page) load_page(page) puts start = (page - 1) * Page::LENGTH + 1 start.upto(start + Page::LENGTH - 1) do |i| puts "#{i} - #{Problem[i].title}" unless i >= Problem.total - 9 end end
ruby
def display_page(page) load_page(page) puts start = (page - 1) * Page::LENGTH + 1 start.upto(start + Page::LENGTH - 1) do |i| puts "#{i} - #{Problem[i].title}" unless i >= Problem.total - 9 end end
[ "def", "display_page", "(", "page", ")", "load_page", "(", "page", ")", "puts", "start", "=", "(", "page", "-", "1", ")", "*", "Page", "::", "LENGTH", "+", "1", "start", ".", "upto", "(", "start", "+", "Page", "::", "LENGTH", "-", "1", ")", "do", "|", "i", "|", "puts", "\"#{i} - #{Problem[i].title}\"", "unless", "i", ">=", "Problem", ".", "total", "-", "9", "end", "end" ]
Displays the problem numbers and titles for an individual page of the archive.
[ "Displays", "the", "problem", "numbers", "and", "titles", "for", "an", "individual", "page", "of", "the", "archive", "." ]
ae6fb1fb516bd9bcf193e3e1f1c82894198fe997
https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L24-L33
9,653
ecssiah/project-euler-cli
lib/project_euler_cli/archive_viewer.rb
ProjectEulerCli.ArchiveViewer.display_problem
def display_problem(id) load_problem_details(id) puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" puts puts Problem[id].title.upcase puts "Problem #{id}" puts puts Problem[id].published puts Problem[id].solved_by puts Problem[id].difficulty if id < Problem.total - 9 puts puts "https://projecteuler.net/problem=#{id}" puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" end
ruby
def display_problem(id) load_problem_details(id) puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" puts puts Problem[id].title.upcase puts "Problem #{id}" puts puts Problem[id].published puts Problem[id].solved_by puts Problem[id].difficulty if id < Problem.total - 9 puts puts "https://projecteuler.net/problem=#{id}" puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" end
[ "def", "display_problem", "(", "id", ")", "load_problem_details", "(", "id", ")", "puts", "puts", "\"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\"", "puts", "puts", "Problem", "[", "id", "]", ".", "title", ".", "upcase", "puts", "\"Problem #{id}\"", "puts", "puts", "Problem", "[", "id", "]", ".", "published", "puts", "Problem", "[", "id", "]", ".", "solved_by", "puts", "Problem", "[", "id", "]", ".", "difficulty", "if", "id", "<", "Problem", ".", "total", "-", "9", "puts", "puts", "\"https://projecteuler.net/problem=#{id}\"", "puts", "puts", "\"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\"", "end" ]
Displays the details of an individual problem. * +id+ - ID of the problem to be displayed
[ "Displays", "the", "details", "of", "an", "individual", "problem", "." ]
ae6fb1fb516bd9bcf193e3e1f1c82894198fe997
https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/archive_viewer.rb#L38-L54
9,654
conorh/rfgraph
lib/rfgraph/auth.rb
RFGraph.Auth.authorize
def authorize(callback_url, code) data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read # The expiration date is not necessarily set, as the app might have # requested offline_access to the data match_data = data.match(/expires=([^&]+)/) @expires = match_data && match_data[1] || nil # Extract the access token @access_token = data.match(/access_token=([^&]+)/)[1] end
ruby
def authorize(callback_url, code) data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read # The expiration date is not necessarily set, as the app might have # requested offline_access to the data match_data = data.match(/expires=([^&]+)/) @expires = match_data && match_data[1] || nil # Extract the access token @access_token = data.match(/access_token=([^&]+)/)[1] end
[ "def", "authorize", "(", "callback_url", ",", "code", ")", "data", "=", "open", "(", "\"#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}\"", ")", ".", "read", "# The expiration date is not necessarily set, as the app might have", "# requested offline_access to the data", "match_data", "=", "data", ".", "match", "(", "/", "/", ")", "@expires", "=", "match_data", "&&", "match_data", "[", "1", "]", "||", "nil", "# Extract the access token", "@access_token", "=", "data", ".", "match", "(", "/", "/", ")", "[", "1", "]", "end" ]
Take the oauth2 request token and turn it into an access token which can be used to access private data
[ "Take", "the", "oauth2", "request", "token", "and", "turn", "it", "into", "an", "access", "token", "which", "can", "be", "used", "to", "access", "private", "data" ]
455fff563f0cb0f9e33714d8ce952fd8ec88ac7e
https://github.com/conorh/rfgraph/blob/455fff563f0cb0f9e33714d8ce952fd8ec88ac7e/lib/rfgraph/auth.rb#L33-L43
9,655
xiuxian123/loyals
projects/loyal_devise/lib/devise/rails/routes.rb
ActionDispatch::Routing.Mapper.devise_for
def devise_for(*resources) @devise_finalized = false options = resources.extract_options! options[:as] ||= @scope[:as] if @scope[:as].present? options[:module] ||= @scope[:module] if @scope[:module].present? options[:path_prefix] ||= @scope[:path] if @scope[:path].present? options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {}) options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {}) options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {}) options[:options] = @scope[:options] || {} options[:options][:format] = false if options[:format] == false resources.map!(&:to_sym) resources.each do |resource| mapping = Devise.add_mapping(resource, options) begin raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise) rescue NameError => e raise unless mapping.class_name == resource.to_s.classify warn "[WARNING] You provided devise_for #{resource.inspect} but there is " << "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e raise unless e.message.include?("undefined method `devise'") raise_no_devise_method_error!(mapping.class_name) end routes = mapping.used_routes devise_scope mapping.name do if block_given? ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \ "Please remove the block from devise_for (only the block, the call to " \ "devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \ "with the block instead", caller yield end with_devise_exclusive_scope mapping.fullpath, mapping.name, options do routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) } end end end end
ruby
def devise_for(*resources) @devise_finalized = false options = resources.extract_options! options[:as] ||= @scope[:as] if @scope[:as].present? options[:module] ||= @scope[:module] if @scope[:module].present? options[:path_prefix] ||= @scope[:path] if @scope[:path].present? options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {}) options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {}) options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {}) options[:options] = @scope[:options] || {} options[:options][:format] = false if options[:format] == false resources.map!(&:to_sym) resources.each do |resource| mapping = Devise.add_mapping(resource, options) begin raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise) rescue NameError => e raise unless mapping.class_name == resource.to_s.classify warn "[WARNING] You provided devise_for #{resource.inspect} but there is " << "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e raise unless e.message.include?("undefined method `devise'") raise_no_devise_method_error!(mapping.class_name) end routes = mapping.used_routes devise_scope mapping.name do if block_given? ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \ "Please remove the block from devise_for (only the block, the call to " \ "devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \ "with the block instead", caller yield end with_devise_exclusive_scope mapping.fullpath, mapping.name, options do routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) } end end end end
[ "def", "devise_for", "(", "*", "resources", ")", "@devise_finalized", "=", "false", "options", "=", "resources", ".", "extract_options!", "options", "[", ":as", "]", "||=", "@scope", "[", ":as", "]", "if", "@scope", "[", ":as", "]", ".", "present?", "options", "[", ":module", "]", "||=", "@scope", "[", ":module", "]", "if", "@scope", "[", ":module", "]", ".", "present?", "options", "[", ":path_prefix", "]", "||=", "@scope", "[", ":path", "]", "if", "@scope", "[", ":path", "]", ".", "present?", "options", "[", ":path_names", "]", "=", "(", "@scope", "[", ":path_names", "]", "||", "{", "}", ")", ".", "merge", "(", "options", "[", ":path_names", "]", "||", "{", "}", ")", "options", "[", ":constraints", "]", "=", "(", "@scope", "[", ":constraints", "]", "||", "{", "}", ")", ".", "merge", "(", "options", "[", ":constraints", "]", "||", "{", "}", ")", "options", "[", ":defaults", "]", "=", "(", "@scope", "[", ":defaults", "]", "||", "{", "}", ")", ".", "merge", "(", "options", "[", ":defaults", "]", "||", "{", "}", ")", "options", "[", ":options", "]", "=", "@scope", "[", ":options", "]", "||", "{", "}", "options", "[", ":options", "]", "[", ":format", "]", "=", "false", "if", "options", "[", ":format", "]", "==", "false", "resources", ".", "map!", "(", ":to_sym", ")", "resources", ".", "each", "do", "|", "resource", "|", "mapping", "=", "Devise", ".", "add_mapping", "(", "resource", ",", "options", ")", "begin", "raise_no_devise_method_error!", "(", "mapping", ".", "class_name", ")", "unless", "mapping", ".", "to", ".", "respond_to?", "(", ":devise", ")", "rescue", "NameError", "=>", "e", "raise", "unless", "mapping", ".", "class_name", "==", "resource", ".", "to_s", ".", "classify", "warn", "\"[WARNING] You provided devise_for #{resource.inspect} but there is \"", "<<", "\"no model #{mapping.class_name} defined in your application\"", "next", "rescue", "NoMethodError", "=>", "e", "raise", "unless", "e", ".", "message", ".", "include?", "(", "\"undefined method `devise'\"", ")", "raise_no_devise_method_error!", "(", "mapping", ".", "class_name", ")", "end", "routes", "=", "mapping", ".", "used_routes", "devise_scope", "mapping", ".", "name", "do", "if", "block_given?", "ActiveSupport", "::", "Deprecation", ".", "warn", "\"Passing a block to devise_for is deprecated. \"", "\"Please remove the block from devise_for (only the block, the call to \"", "\"devise_for must still exist) and call devise_scope :#{mapping.name} do ... end \"", "\"with the block instead\"", ",", "caller", "yield", "end", "with_devise_exclusive_scope", "mapping", ".", "fullpath", ",", "mapping", ".", "name", ",", "options", "do", "routes", ".", "each", "{", "|", "mod", "|", "send", "(", "\"devise_#{mod}\"", ",", "mapping", ",", "mapping", ".", "controllers", ")", "}", "end", "end", "end", "end" ]
Includes devise_for method for routes. This method is responsible to generate all needed routes for devise, based on what modules you have defined in your model. ==== Examples Let's say you have an User model configured to use authenticatable, confirmable and recoverable modules. After creating this inside your routes: devise_for :users This method is going to look inside your User model and create the needed routes: # Session routes for Authenticatable (default) new_user_session GET /users/sign_in {:controller=>"devise/sessions", :action=>"new"} user_session POST /users/sign_in {:controller=>"devise/sessions", :action=>"create"} destroy_user_session DELETE /users/sign_out {:controller=>"devise/sessions", :action=>"destroy"} # Password routes for Recoverable, if User model has :recoverable configured new_user_password GET /users/password/new(.:format) {:controller=>"devise/passwords", :action=>"new"} edit_user_password GET /users/password/edit(.:format) {:controller=>"devise/passwords", :action=>"edit"} user_password PUT /users/password(.:format) {:controller=>"devise/passwords", :action=>"update"} POST /users/password(.:format) {:controller=>"devise/passwords", :action=>"create"} # Confirmation routes for Confirmable, if User model has :confirmable configured new_user_confirmation GET /users/confirmation/new(.:format) {:controller=>"devise/confirmations", :action=>"new"} user_confirmation GET /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"show"} POST /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"create"} ==== Options You can configure your routes with some options: * :class_name => setup a different class to be looked up by devise, if it cannot be properly found by the route name. devise_for :users, :class_name => 'Account' * :path => allows you to setup path name that will be used, as rails routes does. The following route configuration would setup your route as /accounts instead of /users: devise_for :users, :path => 'accounts' * :singular => setup the singular name for the given resource. This is used as the instance variable name in controller, as the name in routes and the scope given to warden. devise_for :users, :singular => :user * :path_names => configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up, :password, :confirmation, :unlock. devise_for :users, :path_names => { :sign_in => 'login', :sign_out => 'logout', :password => 'secret', :confirmation => 'verification' } * :controllers => the controller which should be used. All routes by default points to Devise controllers. However, if you want them to point to custom controller, you should do: devise_for :users, :controllers => { :sessions => "users/sessions" } * :failure_app => a rack app which is invoked whenever there is a failure. Strings representing a given are also allowed as parameter. * :sign_out_via => the HTTP method(s) accepted for the :sign_out action (default: :get), if you wish to restrict this to accept only :post or :delete requests you should do: devise_for :users, :sign_out_via => [ :post, :delete ] You need to make sure that your sign_out controls trigger a request with a matching HTTP method. * :module => the namespace to find controllers (default: "devise", thus accessing devise/sessions, devise/registrations, and so on). If you want to namespace all at once, use module: devise_for :users, :module => "users" Notice that whenever you use namespace in the router DSL, it automatically sets the module. So the following setup: namespace :publisher do devise_for :account end Will use publisher/sessions controller instead of devise/sessions controller. You can revert this by providing the :module option to devise_for. Also pay attention that when you use a namespace it will affect all the helpers and methods for controllers and views. For example, using the above setup you'll end with following methods: current_publisher_account, authenticate_publisher_account!, publisher_account_signed_in, etc. * :skip => tell which controller you want to skip routes from being created: devise_for :users, :skip => :sessions * :only => the opposite of :skip, tell which controllers only to generate routes to: devise_for :users, :only => :sessions * :skip_helpers => skip generating Devise url helpers like new_session_path(@user). This is useful to avoid conflicts with previous routes and is false by default. It accepts true as option, meaning it will skip all the helpers for the controllers given in :skip but it also accepts specific helpers to be skipped: devise_for :users, :skip => [:registrations, :confirmations], :skip_helpers => true devise_for :users, :skip_helpers => [:registrations, :confirmations] * :format => include "(.:format)" in the generated routes? true by default, set to false to disable: devise_for :users, :format => false * :constraints => works the same as Rails' constraints * :defaults => works the same as Rails' defaults ==== Scoping Following Rails 3 routes DSL, you can nest devise_for calls inside a scope: scope "/my" do devise_for :users end However, since Devise uses the request path to retrieve the current user, this has one caveat: If you are using a dynamic segment, like so ... scope ":locale" do devise_for :users end you are required to configure default_url_options in your ApplicationController class, so Devise can pick it: class ApplicationController < ActionController::Base def self.default_url_options { :locale => I18n.locale } end end ==== Adding custom actions to override controllers You can pass a block to devise_for that will add any routes defined in the block to Devise's list of known actions. This is important if you add a custom action to a controller that overrides an out of the box Devise controller. For example: class RegistrationsController < Devise::RegistrationsController def update # do something different here end def deactivate # not a standard action # deactivate code here end end In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this: devise_scope :owner do post "deactivate", :to => "registrations#deactivate", :as => "deactivate_registration" end
[ "Includes", "devise_for", "method", "for", "routes", ".", "This", "method", "is", "responsible", "to", "generate", "all", "needed", "routes", "for", "devise", "based", "on", "what", "modules", "you", "have", "defined", "in", "your", "model", "." ]
41f586ca1551f64e5375ad32a406d5fca0afae43
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_devise/lib/devise/rails/routes.rb#L192-L238
9,656
tbuehlmann/ponder
lib/ponder/channel_list.rb
Ponder.ChannelList.remove
def remove(channel_or_channel_name) @mutex.synchronize do if channel_or_channel_name.is_a?(String) channel_or_channel_name = find(channel_or_channel_name) end @channels.delete(channel_or_channel_name) end end
ruby
def remove(channel_or_channel_name) @mutex.synchronize do if channel_or_channel_name.is_a?(String) channel_or_channel_name = find(channel_or_channel_name) end @channels.delete(channel_or_channel_name) end end
[ "def", "remove", "(", "channel_or_channel_name", ")", "@mutex", ".", "synchronize", "do", "if", "channel_or_channel_name", ".", "is_a?", "(", "String", ")", "channel_or_channel_name", "=", "find", "(", "channel_or_channel_name", ")", "end", "@channels", ".", "delete", "(", "channel_or_channel_name", ")", "end", "end" ]
Removes a Channel from the ChannelList.
[ "Removes", "a", "Channel", "from", "the", "ChannelList", "." ]
930912e1b78b41afa1359121aca46197e9edff9c
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L18-L26
9,657
tbuehlmann/ponder
lib/ponder/channel_list.rb
Ponder.ChannelList.remove_user
def remove_user(nick) @mutex.synchronize do channels = Set.new @channels.each do |channel| if channel.remove_user(nick) channels << channel end end channels end end
ruby
def remove_user(nick) @mutex.synchronize do channels = Set.new @channels.each do |channel| if channel.remove_user(nick) channels << channel end end channels end end
[ "def", "remove_user", "(", "nick", ")", "@mutex", ".", "synchronize", "do", "channels", "=", "Set", ".", "new", "@channels", ".", "each", "do", "|", "channel", "|", "if", "channel", ".", "remove_user", "(", "nick", ")", "channels", "<<", "channel", "end", "end", "channels", "end", "end" ]
Removes a User from all Channels from the ChannelList. Returning a Set of Channels in which the User was.
[ "Removes", "a", "User", "from", "all", "Channels", "from", "the", "ChannelList", ".", "Returning", "a", "Set", "of", "Channels", "in", "which", "the", "User", "was", "." ]
930912e1b78b41afa1359121aca46197e9edff9c
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L30-L42
9,658
tbuehlmann/ponder
lib/ponder/channel_list.rb
Ponder.ChannelList.users
def users users = Set.new @channels.each do |channel| users.merge channel.users end users end
ruby
def users users = Set.new @channels.each do |channel| users.merge channel.users end users end
[ "def", "users", "users", "=", "Set", ".", "new", "@channels", ".", "each", "do", "|", "channel", "|", "users", ".", "merge", "channel", ".", "users", "end", "users", "end" ]
Returns a Set of all Users that are in one of the Channels from the ChannelList.
[ "Returns", "a", "Set", "of", "all", "Users", "that", "are", "in", "one", "of", "the", "Channels", "from", "the", "ChannelList", "." ]
930912e1b78b41afa1359121aca46197e9edff9c
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L60-L68
9,659
AndreasWurm/pingback
lib/pingback/client.rb
Pingback.Client.ping
def ping(source_uri, target_uri) header = request_header target_uri pingback_server = header['X-Pingback'] unless pingback_server doc = Nokogiri::HTML(request_all(target_uri).body) link = doc.xpath('//link[@rel="pingback"]/attribute::href').first pingback_server = URI.escape(link.content) if link end raise InvalidTargetException unless pingback_server send_pingback pingback_server, source_uri, target_uri end
ruby
def ping(source_uri, target_uri) header = request_header target_uri pingback_server = header['X-Pingback'] unless pingback_server doc = Nokogiri::HTML(request_all(target_uri).body) link = doc.xpath('//link[@rel="pingback"]/attribute::href').first pingback_server = URI.escape(link.content) if link end raise InvalidTargetException unless pingback_server send_pingback pingback_server, source_uri, target_uri end
[ "def", "ping", "(", "source_uri", ",", "target_uri", ")", "header", "=", "request_header", "target_uri", "pingback_server", "=", "header", "[", "'X-Pingback'", "]", "unless", "pingback_server", "doc", "=", "Nokogiri", "::", "HTML", "(", "request_all", "(", "target_uri", ")", ".", "body", ")", "link", "=", "doc", ".", "xpath", "(", "'//link[@rel=\"pingback\"]/attribute::href'", ")", ".", "first", "pingback_server", "=", "URI", ".", "escape", "(", "link", ".", "content", ")", "if", "link", "end", "raise", "InvalidTargetException", "unless", "pingback_server", "send_pingback", "pingback_server", ",", "source_uri", ",", "target_uri", "end" ]
send an pingback request to the targets associated pingback server. @param [String] source_uri the address of the site containing the link. @param [String] target_uri the target of the link on the source site. @raise [Pingback::InvalidTargetException] raised if the target is not a pingback-enabled resource @raise [XMLRPC::FaultException] raised if the server responds with a faultcode @return [String] message indicating that the request was successful
[ "send", "an", "pingback", "request", "to", "the", "targets", "associated", "pingback", "server", "." ]
44028aa94420b5cb5454ee56d459f0e4ff31194f
https://github.com/AndreasWurm/pingback/blob/44028aa94420b5cb5454ee56d459f0e4ff31194f/lib/pingback/client.rb#L16-L29
9,660
akwiatkowski/simple_metar_parser
lib/simple_metar_parser/metar/wind.rb
SimpleMetarParser.Wind.decode_wind
def decode_wind(s) if s =~ /(\d{3})(\d{2})G?(\d{2})?(KT|MPS|KMH)/ # different units wind = case $4 when "KT" then $2.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $2.to_f when "KMH" then $2.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end wind_max = case $4 when "KT" then $3.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $3.to_f when "KMH" then $3.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end # wind_max is not less than normal wind if wind_max < wind or wind_max.nil? wind_max = wind end @winds << { :wind => wind, :wind_max => wind_max, :wind_direction => $1.to_i } end # variable/unknown direction if s =~ /VRB(\d{2})(KT|MPS|KMH)/ wind = case $2 when "KT" then $1.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $1.to_f when "KMH" then $1.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end @winds << { :wind => wind } end end
ruby
def decode_wind(s) if s =~ /(\d{3})(\d{2})G?(\d{2})?(KT|MPS|KMH)/ # different units wind = case $4 when "KT" then $2.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $2.to_f when "KMH" then $2.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end wind_max = case $4 when "KT" then $3.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $3.to_f when "KMH" then $3.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end # wind_max is not less than normal wind if wind_max < wind or wind_max.nil? wind_max = wind end @winds << { :wind => wind, :wind_max => wind_max, :wind_direction => $1.to_i } end # variable/unknown direction if s =~ /VRB(\d{2})(KT|MPS|KMH)/ wind = case $2 when "KT" then $1.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $1.to_f when "KMH" then $1.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end @winds << { :wind => wind } end end
[ "def", "decode_wind", "(", "s", ")", "if", "s", "=~", "/", "\\d", "\\d", "\\d", "/", "# different units", "wind", "=", "case", "$4", "when", "\"KT\"", "then", "$2", ".", "to_f", "*", "KNOTS_TO_METERS_PER_SECOND", "when", "\"MPS\"", "then", "$2", ".", "to_f", "when", "\"KMH\"", "then", "$2", ".", "to_f", "*", "KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND", "else", "nil", "end", "wind_max", "=", "case", "$4", "when", "\"KT\"", "then", "$3", ".", "to_f", "*", "KNOTS_TO_METERS_PER_SECOND", "when", "\"MPS\"", "then", "$3", ".", "to_f", "when", "\"KMH\"", "then", "$3", ".", "to_f", "*", "KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND", "else", "nil", "end", "# wind_max is not less than normal wind", "if", "wind_max", "<", "wind", "or", "wind_max", ".", "nil?", "wind_max", "=", "wind", "end", "@winds", "<<", "{", ":wind", "=>", "wind", ",", ":wind_max", "=>", "wind_max", ",", ":wind_direction", "=>", "$1", ".", "to_i", "}", "end", "# variable/unknown direction", "if", "s", "=~", "/", "\\d", "/", "wind", "=", "case", "$2", "when", "\"KT\"", "then", "$1", ".", "to_f", "*", "KNOTS_TO_METERS_PER_SECOND", "when", "\"MPS\"", "then", "$1", ".", "to_f", "when", "\"KMH\"", "then", "$1", ".", "to_f", "*", "KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND", "else", "nil", "end", "@winds", "<<", "{", ":wind", "=>", "wind", "}", "end", "end" ]
Wind parameters in meters per second
[ "Wind", "parameters", "in", "meters", "per", "second" ]
ff8ea6162c7be6137c8e56b768784e58d7c8ad01
https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar/wind.rb#L24-L80
9,661
akwiatkowski/simple_metar_parser
lib/simple_metar_parser/metar/wind.rb
SimpleMetarParser.Wind.recalculate_winds
def recalculate_winds wind_sum = @winds.collect { |w| w[:wind] }.inject(0) { |b, i| b + i } @wind = wind_sum.to_f / @winds.size if @winds.size == 1 @wind_direction = @winds.first[:wind_direction] else @wind_direction = nil end end
ruby
def recalculate_winds wind_sum = @winds.collect { |w| w[:wind] }.inject(0) { |b, i| b + i } @wind = wind_sum.to_f / @winds.size if @winds.size == 1 @wind_direction = @winds.first[:wind_direction] else @wind_direction = nil end end
[ "def", "recalculate_winds", "wind_sum", "=", "@winds", ".", "collect", "{", "|", "w", "|", "w", "[", ":wind", "]", "}", ".", "inject", "(", "0", ")", "{", "|", "b", ",", "i", "|", "b", "+", "i", "}", "@wind", "=", "wind_sum", ".", "to_f", "/", "@winds", ".", "size", "if", "@winds", ".", "size", "==", "1", "@wind_direction", "=", "@winds", ".", "first", "[", ":wind_direction", "]", "else", "@wind_direction", "=", "nil", "end", "end" ]
Calculate wind parameters, some metar string has multiple winds recorded
[ "Calculate", "wind", "parameters", "some", "metar", "string", "has", "multiple", "winds", "recorded" ]
ff8ea6162c7be6137c8e56b768784e58d7c8ad01
https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar/wind.rb#L95-L103
9,662
fotonauts/fwissr
lib/fwissr/registry.rb
Fwissr.Registry.add_source
def add_source(source) @semaphore.synchronize do @sources << source end if @registry.frozen? # already frozen, must reload everything self.reload! else @semaphore.synchronize do Fwissr.merge_conf!(@registry, source.get_conf) end end self.ensure_refresh_thread end
ruby
def add_source(source) @semaphore.synchronize do @sources << source end if @registry.frozen? # already frozen, must reload everything self.reload! else @semaphore.synchronize do Fwissr.merge_conf!(@registry, source.get_conf) end end self.ensure_refresh_thread end
[ "def", "add_source", "(", "source", ")", "@semaphore", ".", "synchronize", "do", "@sources", "<<", "source", "end", "if", "@registry", ".", "frozen?", "# already frozen, must reload everything", "self", ".", "reload!", "else", "@semaphore", ".", "synchronize", "do", "Fwissr", ".", "merge_conf!", "(", "@registry", ",", "source", ".", "get_conf", ")", "end", "end", "self", ".", "ensure_refresh_thread", "end" ]
Init Add a source to registry @param source [Fwissr::Source] Concrete source instance
[ "Init", "Add", "a", "source", "to", "registry" ]
10da86492f104e98c11fbcd44e4b3cb1f5ac268f
https://github.com/fotonauts/fwissr/blob/10da86492f104e98c11fbcd44e4b3cb1f5ac268f/lib/fwissr/registry.rb#L33-L48
9,663
fotonauts/fwissr
lib/fwissr/registry.rb
Fwissr.Registry.get
def get(key) # split key key_ary = key.split('/') # remove first empty part key_ary.shift if (key_ary.first == '') cur_hash = self.registry key_ary.each do |key_part| cur_hash = cur_hash[key_part] return nil if cur_hash.nil? end cur_hash end
ruby
def get(key) # split key key_ary = key.split('/') # remove first empty part key_ary.shift if (key_ary.first == '') cur_hash = self.registry key_ary.each do |key_part| cur_hash = cur_hash[key_part] return nil if cur_hash.nil? end cur_hash end
[ "def", "get", "(", "key", ")", "# split key", "key_ary", "=", "key", ".", "split", "(", "'/'", ")", "# remove first empty part", "key_ary", ".", "shift", "if", "(", "key_ary", ".", "first", "==", "''", ")", "cur_hash", "=", "self", ".", "registry", "key_ary", ".", "each", "do", "|", "key_part", "|", "cur_hash", "=", "cur_hash", "[", "key_part", "]", "return", "nil", "if", "cur_hash", ".", "nil?", "end", "cur_hash", "end" ]
Get a registry key value @param key [String] Key @return [Object] Value
[ "Get", "a", "registry", "key", "value" ]
10da86492f104e98c11fbcd44e4b3cb1f5ac268f
https://github.com/fotonauts/fwissr/blob/10da86492f104e98c11fbcd44e4b3cb1f5ac268f/lib/fwissr/registry.rb#L60-L74
9,664
acesuares/validation_hints
lib/active_model/hints.rb
ActiveModel.Hints.hints_for
def hints_for(attribute) result = Array.new @base.class.validators_on(attribute).map do |v| validator = v.class.to_s.split('::').last.underscore.gsub('_validator','') if v.options[:message].is_a?(Symbol) message_key = [validator, v.options[:message]].join('.') # if a message was supplied as a symbol, we use it instead result << generate_message(attribute, message_key, v.options) else message_key = validator message_key = [validator, ".must_be_a_number"].join('.') if validator == 'numericality' # create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality result << generate_message(attribute, message_key, v.options) unless VALIDATORS_WITHOUT_MAIN_KEYS.include?(validator) v.options.each do |o| if MESSAGES_FOR_OPTIONS.include?(o.first.to_s) count = o.last count = (o.last.to_sentence if %w(inclusion exclusion).include?(validator)) rescue o.last result << generate_message(attribute, [ validator, o.first.to_s ].join('.'), { :count => count } ) end end end end result end
ruby
def hints_for(attribute) result = Array.new @base.class.validators_on(attribute).map do |v| validator = v.class.to_s.split('::').last.underscore.gsub('_validator','') if v.options[:message].is_a?(Symbol) message_key = [validator, v.options[:message]].join('.') # if a message was supplied as a symbol, we use it instead result << generate_message(attribute, message_key, v.options) else message_key = validator message_key = [validator, ".must_be_a_number"].join('.') if validator == 'numericality' # create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality result << generate_message(attribute, message_key, v.options) unless VALIDATORS_WITHOUT_MAIN_KEYS.include?(validator) v.options.each do |o| if MESSAGES_FOR_OPTIONS.include?(o.first.to_s) count = o.last count = (o.last.to_sentence if %w(inclusion exclusion).include?(validator)) rescue o.last result << generate_message(attribute, [ validator, o.first.to_s ].join('.'), { :count => count } ) end end end end result end
[ "def", "hints_for", "(", "attribute", ")", "result", "=", "Array", ".", "new", "@base", ".", "class", ".", "validators_on", "(", "attribute", ")", ".", "map", "do", "|", "v", "|", "validator", "=", "v", ".", "class", ".", "to_s", ".", "split", "(", "'::'", ")", ".", "last", ".", "underscore", ".", "gsub", "(", "'_validator'", ",", "''", ")", "if", "v", ".", "options", "[", ":message", "]", ".", "is_a?", "(", "Symbol", ")", "message_key", "=", "[", "validator", ",", "v", ".", "options", "[", ":message", "]", "]", ".", "join", "(", "'.'", ")", "# if a message was supplied as a symbol, we use it instead", "result", "<<", "generate_message", "(", "attribute", ",", "message_key", ",", "v", ".", "options", ")", "else", "message_key", "=", "validator", "message_key", "=", "[", "validator", ",", "\".must_be_a_number\"", "]", ".", "join", "(", "'.'", ")", "if", "validator", "==", "'numericality'", "# create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality", "result", "<<", "generate_message", "(", "attribute", ",", "message_key", ",", "v", ".", "options", ")", "unless", "VALIDATORS_WITHOUT_MAIN_KEYS", ".", "include?", "(", "validator", ")", "v", ".", "options", ".", "each", "do", "|", "o", "|", "if", "MESSAGES_FOR_OPTIONS", ".", "include?", "(", "o", ".", "first", ".", "to_s", ")", "count", "=", "o", ".", "last", "count", "=", "(", "o", ".", "last", ".", "to_sentence", "if", "%w(", "inclusion", "exclusion", ")", ".", "include?", "(", "validator", ")", ")", "rescue", "o", ".", "last", "result", "<<", "generate_message", "(", "attribute", ",", "[", "validator", ",", "o", ".", "first", ".", "to_s", "]", ".", "join", "(", "'.'", ")", ",", "{", ":count", "=>", "count", "}", ")", "end", "end", "end", "end", "result", "end" ]
Pass in the instance of the object that is using the errors object. class Person def initialize @errors = ActiveModel::Errors.new(self) end end
[ "Pass", "in", "the", "instance", "of", "the", "object", "that", "is", "using", "the", "errors", "object", "." ]
d6fde8190b06eb266d78019f48ce1e3fa1a99bfe
https://github.com/acesuares/validation_hints/blob/d6fde8190b06eb266d78019f48ce1e3fa1a99bfe/lib/active_model/hints.rb#L46-L67
9,665
atpsoft/dohmysql
lib/dohmysql/handle.rb
DohDb.Handle.select
def select(statement, build_arg = nil) result_set = generic_query(statement) DohDb.logger.call('result', "selected #{result_set.size} rows") rows = get_row_builder(build_arg).build_rows(result_set) rows end
ruby
def select(statement, build_arg = nil) result_set = generic_query(statement) DohDb.logger.call('result', "selected #{result_set.size} rows") rows = get_row_builder(build_arg).build_rows(result_set) rows end
[ "def", "select", "(", "statement", ",", "build_arg", "=", "nil", ")", "result_set", "=", "generic_query", "(", "statement", ")", "DohDb", ".", "logger", ".", "call", "(", "'result'", ",", "\"selected #{result_set.size} rows\"", ")", "rows", "=", "get_row_builder", "(", "build_arg", ")", ".", "build_rows", "(", "result_set", ")", "rows", "end" ]
The most generic form of select. It calls to_s on the statement object to facilitate the use of sql builder objects.
[ "The", "most", "generic", "form", "of", "select", ".", "It", "calls", "to_s", "on", "the", "statement", "object", "to", "facilitate", "the", "use", "of", "sql", "builder", "objects", "." ]
39ba8e4efdc9e7522d531a4498fa9f977901ddaf
https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L100-L105
9,666
atpsoft/dohmysql
lib/dohmysql/handle.rb
DohDb.Handle.select_row
def select_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 1" unless rows.size == 1 rows[0] end
ruby
def select_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 1" unless rows.size == 1 rows[0] end
[ "def", "select_row", "(", "statement", ",", "build_arg", "=", "nil", ")", "rows", "=", "select", "(", "statement", ",", "build_arg", ")", "raise", "UnexpectedQueryResult", ",", "\"selected #{rows.size} rows; expected 1\"", "unless", "rows", ".", "size", "==", "1", "rows", "[", "0", "]", "end" ]
Simple convenience wrapper around the generic select call. Throws an exception unless the result set is a single row. Returns the row selected.
[ "Simple", "convenience", "wrapper", "around", "the", "generic", "select", "call", ".", "Throws", "an", "exception", "unless", "the", "result", "set", "is", "a", "single", "row", ".", "Returns", "the", "row", "selected", "." ]
39ba8e4efdc9e7522d531a4498fa9f977901ddaf
https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L110-L114
9,667
atpsoft/dohmysql
lib/dohmysql/handle.rb
DohDb.Handle.select_optional_row
def select_optional_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1 if rows.empty? then nil else rows[0] end end
ruby
def select_optional_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1 if rows.empty? then nil else rows[0] end end
[ "def", "select_optional_row", "(", "statement", ",", "build_arg", "=", "nil", ")", "rows", "=", "select", "(", "statement", ",", "build_arg", ")", "raise", "UnexpectedQueryResult", ",", "\"selected #{rows.size} rows; expected 0 or 1\"", "if", "rows", ".", "size", ">", "1", "if", "rows", ".", "empty?", "then", "nil", "else", "rows", "[", "0", "]", "end", "end" ]
Simple convenience wrapper around the generic select call. Throws an exception unless the result set is empty or a single row. Returns nil if the result set is empty, or the row selected.
[ "Simple", "convenience", "wrapper", "around", "the", "generic", "select", "call", ".", "Throws", "an", "exception", "unless", "the", "result", "set", "is", "empty", "or", "a", "single", "row", ".", "Returns", "nil", "if", "the", "result", "set", "is", "empty", "or", "the", "row", "selected", "." ]
39ba8e4efdc9e7522d531a4498fa9f977901ddaf
https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L119-L123
9,668
atpsoft/dohmysql
lib/dohmysql/handle.rb
DohDb.Handle.select_transpose
def select_transpose(statement, build_arg = nil) rows = select(statement, build_arg) return {} if rows.empty? field_count = rows.first.size if field_count < 2 raise UnexpectedQueryResult, "must select at least 2 fields in order to transpose" elsif field_count == 2 Doh.array_to_hash(rows) { |row| [row.at(0), row.at(1)] } else key_field = rows.first.keys.first Doh.array_to_hash(rows) do |row| value = row.to_h value.delete(key_field) [row.at(0), value] end end end
ruby
def select_transpose(statement, build_arg = nil) rows = select(statement, build_arg) return {} if rows.empty? field_count = rows.first.size if field_count < 2 raise UnexpectedQueryResult, "must select at least 2 fields in order to transpose" elsif field_count == 2 Doh.array_to_hash(rows) { |row| [row.at(0), row.at(1)] } else key_field = rows.first.keys.first Doh.array_to_hash(rows) do |row| value = row.to_h value.delete(key_field) [row.at(0), value] end end end
[ "def", "select_transpose", "(", "statement", ",", "build_arg", "=", "nil", ")", "rows", "=", "select", "(", "statement", ",", "build_arg", ")", "return", "{", "}", "if", "rows", ".", "empty?", "field_count", "=", "rows", ".", "first", ".", "size", "if", "field_count", "<", "2", "raise", "UnexpectedQueryResult", ",", "\"must select at least 2 fields in order to transpose\"", "elsif", "field_count", "==", "2", "Doh", ".", "array_to_hash", "(", "rows", ")", "{", "|", "row", "|", "[", "row", ".", "at", "(", "0", ")", ",", "row", ".", "at", "(", "1", ")", "]", "}", "else", "key_field", "=", "rows", ".", "first", ".", "keys", ".", "first", "Doh", ".", "array_to_hash", "(", "rows", ")", "do", "|", "row", "|", "value", "=", "row", ".", "to_h", "value", ".", "delete", "(", "key_field", ")", "[", "row", ".", "at", "(", "0", ")", ",", "value", "]", "end", "end", "end" ]
Rows in the result set must have 2 or more fields. If there are 2 fields, returns a hash where each key is the first field in the result set, and the value is the second field. If there are more than 2 fields, returns a hash where each key is the first field in the result set, and the value is the row itself, as a Hash, and without the field used as a key.
[ "Rows", "in", "the", "result", "set", "must", "have", "2", "or", "more", "fields", ".", "If", "there", "are", "2", "fields", "returns", "a", "hash", "where", "each", "key", "is", "the", "first", "field", "in", "the", "result", "set", "and", "the", "value", "is", "the", "second", "field", ".", "If", "there", "are", "more", "than", "2", "fields", "returns", "a", "hash", "where", "each", "key", "is", "the", "first", "field", "in", "the", "result", "set", "and", "the", "value", "is", "the", "row", "itself", "as", "a", "Hash", "and", "without", "the", "field", "used", "as", "a", "key", "." ]
39ba8e4efdc9e7522d531a4498fa9f977901ddaf
https://github.com/atpsoft/dohmysql/blob/39ba8e4efdc9e7522d531a4498fa9f977901ddaf/lib/dohmysql/handle.rb#L142-L158
9,669
npepinpe/redstruct
lib/redstruct/hash.rb
Redstruct.Hash.get
def get(*keys) return self.connection.hget(@key, keys.first) if keys.size == 1 return self.connection.mapped_hmget(@key, *keys).reject { |_, v| v.nil? } end
ruby
def get(*keys) return self.connection.hget(@key, keys.first) if keys.size == 1 return self.connection.mapped_hmget(@key, *keys).reject { |_, v| v.nil? } end
[ "def", "get", "(", "*", "keys", ")", "return", "self", ".", "connection", ".", "hget", "(", "@key", ",", "keys", ".", "first", ")", "if", "keys", ".", "size", "==", "1", "return", "self", ".", "connection", ".", "mapped_hmget", "(", "@key", ",", "keys", ")", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Returns the value at key @param [Array<#to_s>] keys a list of keys to fetch; can be only one @return [Hash<String, String>] if only one key was passed, then return the value for it; otherwise returns a Ruby hash where each key in the `keys` is mapped to the value returned by redis
[ "Returns", "the", "value", "at", "key" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L22-L25
9,670
npepinpe/redstruct
lib/redstruct/hash.rb
Redstruct.Hash.set
def set(key, value, overwrite: true) result = if overwrite self.connection.hset(@key, key, value) else self.connection.hsetnx(@key, key, value) end return coerce_bool(result) end
ruby
def set(key, value, overwrite: true) result = if overwrite self.connection.hset(@key, key, value) else self.connection.hsetnx(@key, key, value) end return coerce_bool(result) end
[ "def", "set", "(", "key", ",", "value", ",", "overwrite", ":", "true", ")", "result", "=", "if", "overwrite", "self", ".", "connection", ".", "hset", "(", "@key", ",", "key", ",", "value", ")", "else", "self", ".", "connection", ".", "hsetnx", "(", "@key", ",", "key", ",", "value", ")", "end", "return", "coerce_bool", "(", "result", ")", "end" ]
Sets or updates the value at key @param [#to_s] key the hash key @param [#to_s] value the new value to set @return [Boolean] true if the field was set (not updated!), false otherwise
[ "Sets", "or", "updates", "the", "value", "at", "key" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L39-L47
9,671
npepinpe/redstruct
lib/redstruct/hash.rb
Redstruct.Hash.increment
def increment(key, by: 1) if by.is_a?(Float) self.connection.hincrbyfloat(@key, key, by.to_f).to_f else self.connection.hincrby(@key, key, by.to_i).to_i end end
ruby
def increment(key, by: 1) if by.is_a?(Float) self.connection.hincrbyfloat(@key, key, by.to_f).to_f else self.connection.hincrby(@key, key, by.to_i).to_i end end
[ "def", "increment", "(", "key", ",", "by", ":", "1", ")", "if", "by", ".", "is_a?", "(", "Float", ")", "self", ".", "connection", ".", "hincrbyfloat", "(", "@key", ",", "key", ",", "by", ".", "to_f", ")", ".", "to_f", "else", "self", ".", "connection", ".", "hincrby", "(", "@key", ",", "key", ",", "by", ".", "to_i", ")", ".", "to_i", "end", "end" ]
Increments the value at the given key @param [#to_s] key the hash key @param [Integer, Float] by defaults to 1 @return [Integer, Float] returns the incremented value
[ "Increments", "the", "value", "at", "the", "given", "key" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/hash.rb#L74-L80
9,672
ZhKostev/zh_kostev_ext
lib/controller_extensions/url_ext.rb
ControllerExtensions.UrlExt.url_for
def url_for(options = {}) options = case options when String uri = Addressable::URI.new uri.query_values = @hash_of_additional_params options + (options.index('?').nil? ? '?' : '&') + "#{uri.query}" when Hash options.reverse_merge(@hash_of_additional_params || {}) else options end super end
ruby
def url_for(options = {}) options = case options when String uri = Addressable::URI.new uri.query_values = @hash_of_additional_params options + (options.index('?').nil? ? '?' : '&') + "#{uri.query}" when Hash options.reverse_merge(@hash_of_additional_params || {}) else options end super end
[ "def", "url_for", "(", "options", "=", "{", "}", ")", "options", "=", "case", "options", "when", "String", "uri", "=", "Addressable", "::", "URI", ".", "new", "uri", ".", "query_values", "=", "@hash_of_additional_params", "options", "+", "(", "options", ".", "index", "(", "'?'", ")", ".", "nil?", "?", "'?'", ":", "'&'", ")", "+", "\"#{uri.query}\"", "when", "Hash", "options", ".", "reverse_merge", "(", "@hash_of_additional_params", "||", "{", "}", ")", "else", "options", "end", "super", "end" ]
override default url_for method. Add ability to set default params. Example: 'auctions_path' return '/auctions' by default if you set @hash_of_additional_params = {:test => 1, my_param => 2} 'auctions_path' will return '/auctions?test=1&my_param=2' You can use before_filer to do this stuff automatically. Example: in HomeController: before_filter { @hash_of_additional_params = {:test => '1'} } #this will add test param to all urls in home views
[ "override", "default", "url_for", "method", ".", "Add", "ability", "to", "set", "default", "params", "." ]
5233a0896e9a2ffd7414ff09f5e4549099ace2fa
https://github.com/ZhKostev/zh_kostev_ext/blob/5233a0896e9a2ffd7414ff09f5e4549099ace2fa/lib/controller_extensions/url_ext.rb#L15-L28
9,673
NUBIC/aker
lib/aker/group.rb
Aker.Group.include?
def include?(other) other_name = case other when Group; other.name; else other.to_s; end self.find { |g| g.name.downcase == other_name.downcase } end
ruby
def include?(other) other_name = case other when Group; other.name; else other.to_s; end self.find { |g| g.name.downcase == other_name.downcase } end
[ "def", "include?", "(", "other", ")", "other_name", "=", "case", "other", "when", "Group", ";", "other", ".", "name", ";", "else", "other", ".", "to_s", ";", "end", "self", ".", "find", "{", "|", "g", "|", "g", ".", "name", ".", "downcase", "==", "other_name", ".", "downcase", "}", "end" ]
Creates a new group with the given name. You can add children using `<<`. @param [#to_s] name the desired name @param [Array,nil] args additional arguments. Included for marshalling compatibility with the base class. Determines whether this group or any of its children matches the given parameter for authorization purposes. @param [#to_s,Group] other the thing to compare this group to @return [Boolean] true if the name of this group or any of its children is a case-insensitive match for the other.
[ "Creates", "a", "new", "group", "with", "the", "given", "name", ".", "You", "can", "add", "children", "using", "<<", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/group.rb#L33-L40
9,674
NUBIC/aker
lib/aker/group.rb
Aker.Group.marshal_load
def marshal_load(dumped_tree_array) nodes = { } for node_hash in dumped_tree_array do name = node_hash[:name] parent_name = node_hash[:parent] content = Marshal.load(node_hash[:content]) if parent_name then nodes[name] = current_node = self.class.new(name, content) nodes[parent_name].add current_node else # This is the root node, hence initialize self. initialize(name, content) nodes[name] = self # Add self to the list of nodes end end end
ruby
def marshal_load(dumped_tree_array) nodes = { } for node_hash in dumped_tree_array do name = node_hash[:name] parent_name = node_hash[:parent] content = Marshal.load(node_hash[:content]) if parent_name then nodes[name] = current_node = self.class.new(name, content) nodes[parent_name].add current_node else # This is the root node, hence initialize self. initialize(name, content) nodes[name] = self # Add self to the list of nodes end end end
[ "def", "marshal_load", "(", "dumped_tree_array", ")", "nodes", "=", "{", "}", "for", "node_hash", "in", "dumped_tree_array", "do", "name", "=", "node_hash", "[", ":name", "]", "parent_name", "=", "node_hash", "[", ":parent", "]", "content", "=", "Marshal", ".", "load", "(", "node_hash", "[", ":content", "]", ")", "if", "parent_name", "then", "nodes", "[", "name", "]", "=", "current_node", "=", "self", ".", "class", ".", "new", "(", "name", ",", "content", ")", "nodes", "[", "parent_name", "]", ".", "add", "current_node", "else", "# This is the root node, hence initialize self.", "initialize", "(", "name", ",", "content", ")", "nodes", "[", "name", "]", "=", "self", "# Add self to the list of nodes", "end", "end", "end" ]
Copy-pasted from parent in order to use appropriate class when deserializing children. @private
[ "Copy", "-", "pasted", "from", "parent", "in", "order", "to", "use", "appropriate", "class", "when", "deserializing", "children", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/group.rb#L47-L65
9,675
sugaryourcoffee/syclink
lib/syclink/chrome.rb
SycLink.Chrome.read
def read serialized = File.read(path) extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a end
ruby
def read serialized = File.read(path) extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a end
[ "def", "read", "serialized", "=", "File", ".", "read", "(", "path", ")", "extract_links", "(", "JSON", ".", "parse", "(", "serialized", ")", ")", ".", "flatten", ".", "each_slice", "(", "4", ")", ".", "to_a", "end" ]
Reads the content of the Google Chrome bookmarks file
[ "Reads", "the", "content", "of", "the", "Google", "Chrome", "bookmarks", "file" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/chrome.rb#L10-L13
9,676
sugaryourcoffee/syclink
lib/syclink/chrome.rb
SycLink.Chrome.extract_children
def extract_children(tag, children) children.map do |child| if child["children"] extract_children("#{tag},#{child['name']}", child["children"]) else [child["url"], child["name"], "", tag] end end end
ruby
def extract_children(tag, children) children.map do |child| if child["children"] extract_children("#{tag},#{child['name']}", child["children"]) else [child["url"], child["name"], "", tag] end end end
[ "def", "extract_children", "(", "tag", ",", "children", ")", "children", ".", "map", "do", "|", "child", "|", "if", "child", "[", "\"children\"", "]", "extract_children", "(", "\"#{tag},#{child['name']}\"", ",", "child", "[", "\"children\"", "]", ")", "else", "[", "child", "[", "\"url\"", "]", ",", "child", "[", "\"name\"", "]", ",", "\"\"", ",", "tag", "]", "end", "end", "end" ]
Extracts the children from the JSON file
[ "Extracts", "the", "children", "from", "the", "JSON", "file" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/chrome.rb#L25-L33
9,677
zohararad/handlebarer
lib/handlebarer/template.rb
Handlebarer.Template.evaluate
def evaluate(scope, locals, &block) c = Handlebarer::Compiler.new c.compile(data) end
ruby
def evaluate(scope, locals, &block) c = Handlebarer::Compiler.new c.compile(data) end
[ "def", "evaluate", "(", "scope", ",", "locals", ",", "&", "block", ")", "c", "=", "Handlebarer", "::", "Compiler", ".", "new", "c", ".", "compile", "(", "data", ")", "end" ]
Evaluate the template. Compiles the template for JST @return [String] JST-compliant compiled version of the Handlebars template being rendered
[ "Evaluate", "the", "template", ".", "Compiles", "the", "template", "for", "JST" ]
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/template.rb#L24-L27
9,678
mntnorv/puttext
lib/puttext/cmdline.rb
PutText.Cmdline.run
def run(args) options = parse_args(args) po_file = Extractor.new.extract(options[:path]) if options[:output_file] with_output_file(options[:output_file]) { |f| po_file.write_to(f) } else po_file.write_to(STDOUT) end rescue => e error(e) end
ruby
def run(args) options = parse_args(args) po_file = Extractor.new.extract(options[:path]) if options[:output_file] with_output_file(options[:output_file]) { |f| po_file.write_to(f) } else po_file.write_to(STDOUT) end rescue => e error(e) end
[ "def", "run", "(", "args", ")", "options", "=", "parse_args", "(", "args", ")", "po_file", "=", "Extractor", ".", "new", ".", "extract", "(", "options", "[", ":path", "]", ")", "if", "options", "[", ":output_file", "]", "with_output_file", "(", "options", "[", ":output_file", "]", ")", "{", "|", "f", "|", "po_file", ".", "write_to", "(", "f", ")", "}", "else", "po_file", ".", "write_to", "(", "STDOUT", ")", "end", "rescue", "=>", "e", "error", "(", "e", ")", "end" ]
Run the commmand line tool puttext. @param [Array<String>] args the command line arguments.
[ "Run", "the", "commmand", "line", "tool", "puttext", "." ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/cmdline.rb#L18-L29
9,679
groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby
lib/groupdocs_comparison_cloud/api/changes_api.rb
GroupDocsComparisonCloud.ChangesApi.put_changes_document_stream_with_http_info
def put_changes_document_stream_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/stream' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'File') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
def put_changes_document_stream_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/stream' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'File') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
[ "def", "put_changes_document_stream_with_http_info", "(", "request", ")", "raise", "ArgumentError", ",", "'Incorrect request type'", "unless", "request", ".", "is_a?", "PutChangesDocumentStreamRequest", "@api_client", ".", "config", ".", "logger", ".", "debug", "'Calling API: ChangesApi.put_changes_document_stream ...'", "if", "@api_client", ".", "config", ".", "debugging", "# resource path", "local_var_path", "=", "'/comparison/compareDocuments/changes/stream'", "# query parameters", "query_params", "=", "{", "}", "# header parameters", "header_params", "=", "{", "}", "# HTTP header 'Accept' (if needed)", "header_params", "[", "'Accept'", "]", "=", "@api_client", ".", "select_header_accept", "(", "[", "'application/json'", ",", "'application/xml'", "]", ")", "# HTTP header 'Content-Type'", "header_params", "[", "'Content-Type'", "]", "=", "@api_client", ".", "select_header_content_type", "(", "[", "'application/json'", ",", "'application/xml'", "]", ")", "# form parameters", "form_params", "=", "{", "}", "# http body (model)", "post_body", "=", "@api_client", ".", "object_to_http_body", "(", "request", ".", "request", ")", "data", ",", "status_code", ",", "headers", "=", "@api_client", ".", "call_api", "(", ":PUT", ",", "local_var_path", ",", "header_params", ":", "header_params", ",", "query_params", ":", "query_params", ",", "form_params", ":", "form_params", ",", "body", ":", "post_body", ",", "access_token", ":", "get_access_token", ",", "return_type", ":", "'File'", ")", "if", "@api_client", ".", "config", ".", "debugging", "@api_client", ".", "config", ".", "logger", ".", "debug", "\"API called:\n ChangesApi#put_changes_document_stream\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"", "end", "[", "data", ",", "status_code", ",", "headers", "]", "end" ]
Applies changes to the document and returns stream of document with the result of comparison @param request put_changes_document_stream_request @return [Array<(File, Fixnum, Hash)>] File data, response status code and response headers
[ "Applies", "changes", "to", "the", "document", "and", "returns", "stream", "of", "document", "with", "the", "result", "of", "comparison" ]
c39ed1a23dd7808f98e4a4029031c8d6014f9287
https://github.com/groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby/blob/c39ed1a23dd7808f98e4a4029031c8d6014f9287/lib/groupdocs_comparison_cloud/api/changes_api.rb#L243-L277
9,680
groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby
lib/groupdocs_comparison_cloud/api/changes_api.rb
GroupDocsComparisonCloud.ChangesApi.put_changes_images_with_http_info
def put_changes_images_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesImagesRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/images' # query parameters query_params = {} if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s) else query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil? end # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'Array<Link>') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
def put_changes_images_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesImagesRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/images' # query parameters query_params = {} if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s) else query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil? end # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'Array<Link>') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
[ "def", "put_changes_images_with_http_info", "(", "request", ")", "raise", "ArgumentError", ",", "'Incorrect request type'", "unless", "request", ".", "is_a?", "PutChangesImagesRequest", "@api_client", ".", "config", ".", "logger", ".", "debug", "'Calling API: ChangesApi.put_changes_images ...'", "if", "@api_client", ".", "config", ".", "debugging", "# resource path", "local_var_path", "=", "'/comparison/compareDocuments/changes/images'", "# query parameters", "query_params", "=", "{", "}", "if", "local_var_path", ".", "include?", "(", "'{'", "+", "downcase_first_letter", "(", "'OutFolder'", ")", "+", "'}'", ")", "local_var_path", "=", "local_var_path", ".", "sub", "(", "'{'", "+", "downcase_first_letter", "(", "'OutFolder'", ")", "+", "'}'", ",", "request", ".", "out_folder", ".", "to_s", ")", "else", "query_params", "[", "downcase_first_letter", "(", "'OutFolder'", ")", "]", "=", "request", ".", "out_folder", "unless", "request", ".", "out_folder", ".", "nil?", "end", "# header parameters", "header_params", "=", "{", "}", "# HTTP header 'Accept' (if needed)", "header_params", "[", "'Accept'", "]", "=", "@api_client", ".", "select_header_accept", "(", "[", "'application/json'", ",", "'application/xml'", "]", ")", "# HTTP header 'Content-Type'", "header_params", "[", "'Content-Type'", "]", "=", "@api_client", ".", "select_header_content_type", "(", "[", "'application/json'", ",", "'application/xml'", "]", ")", "# form parameters", "form_params", "=", "{", "}", "# http body (model)", "post_body", "=", "@api_client", ".", "object_to_http_body", "(", "request", ".", "request", ")", "data", ",", "status_code", ",", "headers", "=", "@api_client", ".", "call_api", "(", ":PUT", ",", "local_var_path", ",", "header_params", ":", "header_params", ",", "query_params", ":", "query_params", ",", "form_params", ":", "form_params", ",", "body", ":", "post_body", ",", "access_token", ":", "get_access_token", ",", "return_type", ":", "'Array<Link>'", ")", "if", "@api_client", ".", "config", ".", "debugging", "@api_client", ".", "config", ".", "logger", ".", "debug", "\"API called:\n ChangesApi#put_changes_images\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"", "end", "[", "data", ",", "status_code", ",", "headers", "]", "end" ]
Applies changes to the document and returns images of document with the result of comparison @param request put_changes_images_request @return [Array<(Array<Link>, Fixnum, Hash)>] Array<Link> data, response status code and response headers
[ "Applies", "changes", "to", "the", "document", "and", "returns", "images", "of", "document", "with", "the", "result", "of", "comparison" ]
c39ed1a23dd7808f98e4a4029031c8d6014f9287
https://github.com/groupdocs-comparison-cloud/groupdocs-comparison-cloud-ruby/blob/c39ed1a23dd7808f98e4a4029031c8d6014f9287/lib/groupdocs_comparison_cloud/api/changes_api.rb#L293-L332
9,681
boxgrinder/boxgrinder-core
lib/boxgrinder-core/helpers/appliance-definition-helper.rb
BoxGrinder.ApplianceDefinitionHelper.read_definitions
def read_definitions(definition, content_type = nil) @appliance_parser.load_schemas if File.exists?(definition) definition_file_extension = File.extname(definition) appliance_config = case definition_file_extension when '.appl', '.yml', '.yaml' @appliance_parser.parse_definition(definition) else unless content_type.nil? case content_type when 'application/x-yaml', 'text/yaml' @appliance_parser.parse_definition(definition) end end end return if appliance_config.nil? @appliance_configs << appliance_config appliances = [] @appliance_configs.each { |config| appliances << config.name } appliance_config.appliances.reverse.each do |appliance_name| read_definitions("#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}") unless appliances.include?(appliance_name) end unless appliance_config.appliances.nil? or !appliance_config.appliances.is_a?(Array) else # Assuming that the definition is provided as string @appliance_configs << @appliance_parser.parse_definition(definition, false) end end
ruby
def read_definitions(definition, content_type = nil) @appliance_parser.load_schemas if File.exists?(definition) definition_file_extension = File.extname(definition) appliance_config = case definition_file_extension when '.appl', '.yml', '.yaml' @appliance_parser.parse_definition(definition) else unless content_type.nil? case content_type when 'application/x-yaml', 'text/yaml' @appliance_parser.parse_definition(definition) end end end return if appliance_config.nil? @appliance_configs << appliance_config appliances = [] @appliance_configs.each { |config| appliances << config.name } appliance_config.appliances.reverse.each do |appliance_name| read_definitions("#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}") unless appliances.include?(appliance_name) end unless appliance_config.appliances.nil? or !appliance_config.appliances.is_a?(Array) else # Assuming that the definition is provided as string @appliance_configs << @appliance_parser.parse_definition(definition, false) end end
[ "def", "read_definitions", "(", "definition", ",", "content_type", "=", "nil", ")", "@appliance_parser", ".", "load_schemas", "if", "File", ".", "exists?", "(", "definition", ")", "definition_file_extension", "=", "File", ".", "extname", "(", "definition", ")", "appliance_config", "=", "case", "definition_file_extension", "when", "'.appl'", ",", "'.yml'", ",", "'.yaml'", "@appliance_parser", ".", "parse_definition", "(", "definition", ")", "else", "unless", "content_type", ".", "nil?", "case", "content_type", "when", "'application/x-yaml'", ",", "'text/yaml'", "@appliance_parser", ".", "parse_definition", "(", "definition", ")", "end", "end", "end", "return", "if", "appliance_config", ".", "nil?", "@appliance_configs", "<<", "appliance_config", "appliances", "=", "[", "]", "@appliance_configs", ".", "each", "{", "|", "config", "|", "appliances", "<<", "config", ".", "name", "}", "appliance_config", ".", "appliances", ".", "reverse", ".", "each", "do", "|", "appliance_name", "|", "read_definitions", "(", "\"#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}\"", ")", "unless", "appliances", ".", "include?", "(", "appliance_name", ")", "end", "unless", "appliance_config", ".", "appliances", ".", "nil?", "or", "!", "appliance_config", ".", "appliances", ".", "is_a?", "(", "Array", ")", "else", "# Assuming that the definition is provided as string", "@appliance_configs", "<<", "@appliance_parser", ".", "parse_definition", "(", "definition", ",", "false", ")", "end", "end" ]
Reads definition provided as string. This string can be a YAML document. In this case definition is parsed and an ApplianceConfig object is returned. In other cases it tries to search for a file with provided name.
[ "Reads", "definition", "provided", "as", "string", ".", "This", "string", "can", "be", "a", "YAML", "document", ".", "In", "this", "case", "definition", "is", "parsed", "and", "an", "ApplianceConfig", "object", "is", "returned", ".", "In", "other", "cases", "it", "tries", "to", "search", "for", "a", "file", "with", "provided", "name", "." ]
7d54ad1ddf040078b6bab0a4dc94392b2492bde5
https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-definition-helper.rb#L37-L69
9,682
NUBIC/aker
lib/aker/rack/authenticate.rb
Aker::Rack.Authenticate.call
def call(env) configuration = configuration(env) warden = env['warden'] if interactive?(env) warden.authenticate(configuration.ui_mode) else warden.authenticate(*configuration.api_modes) end env['aker.check'] = Facade.new(configuration, warden.user) @app.call(env) end
ruby
def call(env) configuration = configuration(env) warden = env['warden'] if interactive?(env) warden.authenticate(configuration.ui_mode) else warden.authenticate(*configuration.api_modes) end env['aker.check'] = Facade.new(configuration, warden.user) @app.call(env) end
[ "def", "call", "(", "env", ")", "configuration", "=", "configuration", "(", "env", ")", "warden", "=", "env", "[", "'warden'", "]", "if", "interactive?", "(", "env", ")", "warden", ".", "authenticate", "(", "configuration", ".", "ui_mode", ")", "else", "warden", ".", "authenticate", "(", "configuration", ".", "api_modes", ")", "end", "env", "[", "'aker.check'", "]", "=", "Facade", ".", "new", "(", "configuration", ",", "warden", ".", "user", ")", "@app", ".", "call", "(", "env", ")", "end" ]
Authenticates incoming requests using Warden. Additionally, this class exposes the `aker.check` environment variable to downstream middleware and the app. It is an instance of {Aker::Rack::Facade} permitting authentication and authorization queries about the current user (if any).
[ "Authenticates", "incoming", "requests", "using", "Warden", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/authenticate.rb#L22-L35
9,683
kot-begemot/localization-middleware
lib/localization-middleware.rb
Localization.Middleware.locale_from_url
def locale_from_url path_info = nil @locale_set ||= begin @locale ||= (match = (path_info || @env['PATH_INFO']).match(locale_pattern)) ? match[1] : nil @env['PATH_INFO'] = match[2] if match && @env.try(:fetch, 'PATH_INFO') true end @locale end
ruby
def locale_from_url path_info = nil @locale_set ||= begin @locale ||= (match = (path_info || @env['PATH_INFO']).match(locale_pattern)) ? match[1] : nil @env['PATH_INFO'] = match[2] if match && @env.try(:fetch, 'PATH_INFO') true end @locale end
[ "def", "locale_from_url", "path_info", "=", "nil", "@locale_set", "||=", "begin", "@locale", "||=", "(", "match", "=", "(", "path_info", "||", "@env", "[", "'PATH_INFO'", "]", ")", ".", "match", "(", "locale_pattern", ")", ")", "?", "match", "[", "1", "]", ":", "nil", "@env", "[", "'PATH_INFO'", "]", "=", "match", "[", "2", "]", "if", "match", "&&", "@env", ".", "try", "(", ":fetch", ",", "'PATH_INFO'", ")", "true", "end", "@locale", "end" ]
Determine locale from the request URL and return it as a string, it it is matching any of provided locales If locale matching failed an empty String will be returned. Examples: #http://www.example.com/se locale_from_url # => 'se' #http://www.example.com/de/posts locale_from_url # => 'se' #http://www.example.com/ursers locale_from_url # => ''
[ "Determine", "locale", "from", "the", "request", "URL", "and", "return", "it", "as", "a", "string", "it", "it", "is", "matching", "any", "of", "provided", "locales", "If", "locale", "matching", "failed", "an", "empty", "String", "will", "be", "returned", "." ]
90df50b28f2b15bfda7d18faf9220d37814da86f
https://github.com/kot-begemot/localization-middleware/blob/90df50b28f2b15bfda7d18faf9220d37814da86f/lib/localization-middleware.rb#L66-L73
9,684
maxim/has_price
lib/has_price/price.rb
HasPrice.Price.method_missing
def method_missing(meth, *args, &blk) value = select{|k,v| k.underscore == meth.to_s}.first if !value super elsif value.last.is_a?(Hash) self.class[value.last] else value.last end end
ruby
def method_missing(meth, *args, &blk) value = select{|k,v| k.underscore == meth.to_s}.first if !value super elsif value.last.is_a?(Hash) self.class[value.last] else value.last end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "blk", ")", "value", "=", "select", "{", "|", "k", ",", "v", "|", "k", ".", "underscore", "==", "meth", ".", "to_s", "}", ".", "first", "if", "!", "value", "super", "elsif", "value", ".", "last", ".", "is_a?", "(", "Hash", ")", "self", ".", "class", "[", "value", ".", "last", "]", "else", "value", ".", "last", "end", "end" ]
Provides access to price items and groups using magic methods and chaining. @example class Product has_price do item 400, "base" group "tax" do item 100, "federal" item 50, "state" end end end product = Product.new product.price # => Full Price object product.price.base # => 400 product.price.tax # => Price object on group tax product.price.tax.federal # => 100 product.price.tax.total # => 150 @return [Price, Fixnum] Price object if method matches a group, Fixnum if method matches an item.
[ "Provides", "access", "to", "price", "items", "and", "groups", "using", "magic", "methods", "and", "chaining", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price.rb#L32-L42
9,685
qtcloudservices/qtc-sdk-ruby
lib/qtc/client.rb
Qtc.Client.get
def get(path, params = nil, headers = {}) response = http_client.get(request_uri(path), params, request_headers(headers)) if response.status == 200 parse_response(response) else handle_error_response(response) end end
ruby
def get(path, params = nil, headers = {}) response = http_client.get(request_uri(path), params, request_headers(headers)) if response.status == 200 parse_response(response) else handle_error_response(response) end end
[ "def", "get", "(", "path", ",", "params", "=", "nil", ",", "headers", "=", "{", "}", ")", "response", "=", "http_client", ".", "get", "(", "request_uri", "(", "path", ")", ",", "params", ",", "request_headers", "(", "headers", ")", ")", "if", "response", ".", "status", "==", "200", "parse_response", "(", "response", ")", "else", "handle_error_response", "(", "response", ")", "end", "end" ]
Initialize api client @param [String] api_url @param [Hash] default_headers Get request @param [String] path @param [Hash,NilClass] params @return [Hash]
[ "Initialize", "api", "client" ]
42c4f7e2188b63be7e67eca281dd1978809c3886
https://github.com/qtcloudservices/qtc-sdk-ruby/blob/42c4f7e2188b63be7e67eca281dd1978809c3886/lib/qtc/client.rb#L26-L33
9,686
mixflame/Hokkaido
chronic/lib/chronic/handler.rb
Chronic.Handler.match
def match(tokens, definitions) token_index = 0 @pattern.each do |element| name = element.to_s optional = name[-1, 1] == '?' name = name.chop if optional case element when Symbol if tags_match?(name, tokens, token_index) token_index += 1 next else if optional next else return false end end when String return true if optional && token_index == tokens.size if definitions.key?(name.to_sym) sub_handlers = definitions[name.to_sym] else raise ChronicPain, "Invalid subset #{name} specified" end sub_handlers.each do |sub_handler| return true if sub_handler.match(tokens[token_index..tokens.size], definitions) end else raise ChronicPain, "Invalid match type: #{element.class}" end end return false if token_index != tokens.size return true end
ruby
def match(tokens, definitions) token_index = 0 @pattern.each do |element| name = element.to_s optional = name[-1, 1] == '?' name = name.chop if optional case element when Symbol if tags_match?(name, tokens, token_index) token_index += 1 next else if optional next else return false end end when String return true if optional && token_index == tokens.size if definitions.key?(name.to_sym) sub_handlers = definitions[name.to_sym] else raise ChronicPain, "Invalid subset #{name} specified" end sub_handlers.each do |sub_handler| return true if sub_handler.match(tokens[token_index..tokens.size], definitions) end else raise ChronicPain, "Invalid match type: #{element.class}" end end return false if token_index != tokens.size return true end
[ "def", "match", "(", "tokens", ",", "definitions", ")", "token_index", "=", "0", "@pattern", ".", "each", "do", "|", "element", "|", "name", "=", "element", ".", "to_s", "optional", "=", "name", "[", "-", "1", ",", "1", "]", "==", "'?'", "name", "=", "name", ".", "chop", "if", "optional", "case", "element", "when", "Symbol", "if", "tags_match?", "(", "name", ",", "tokens", ",", "token_index", ")", "token_index", "+=", "1", "next", "else", "if", "optional", "next", "else", "return", "false", "end", "end", "when", "String", "return", "true", "if", "optional", "&&", "token_index", "==", "tokens", ".", "size", "if", "definitions", ".", "key?", "(", "name", ".", "to_sym", ")", "sub_handlers", "=", "definitions", "[", "name", ".", "to_sym", "]", "else", "raise", "ChronicPain", ",", "\"Invalid subset #{name} specified\"", "end", "sub_handlers", ".", "each", "do", "|", "sub_handler", "|", "return", "true", "if", "sub_handler", ".", "match", "(", "tokens", "[", "token_index", "..", "tokens", ".", "size", "]", ",", "definitions", ")", "end", "else", "raise", "ChronicPain", ",", "\"Invalid match type: #{element.class}\"", "end", "end", "return", "false", "if", "token_index", "!=", "tokens", ".", "size", "return", "true", "end" ]
pattern - An Array of patterns to match tokens against. handler_method - A Symbole representing the method to be invoked when patterns are matched. tokens - An Array of tokens to process. definitions - A Hash of definitions to check against. Returns true if a match is found.
[ "pattern", "-", "An", "Array", "of", "patterns", "to", "match", "tokens", "against", ".", "handler_method", "-", "A", "Symbole", "representing", "the", "method", "to", "be", "invoked", "when", "patterns", "are", "matched", ".", "tokens", "-", "An", "Array", "of", "tokens", "to", "process", ".", "definitions", "-", "A", "Hash", "of", "definitions", "to", "check", "against", "." ]
bf21e7915044576ef74495ccd70d7ff5ee1bcd4b
https://github.com/mixflame/Hokkaido/blob/bf21e7915044576ef74495ccd70d7ff5ee1bcd4b/chronic/lib/chronic/handler.rb#L20-L59
9,687
cdarne/triton
lib/triton/messenger.rb
Triton.Messenger.add_listener
def add_listener(type, once=false, &callback) listener = Listener.new(type, callback, once) listeners[type] ||= [] listeners[type] << listener emit(:new_listener, self, type, once, callback) listener end
ruby
def add_listener(type, once=false, &callback) listener = Listener.new(type, callback, once) listeners[type] ||= [] listeners[type] << listener emit(:new_listener, self, type, once, callback) listener end
[ "def", "add_listener", "(", "type", ",", "once", "=", "false", ",", "&", "callback", ")", "listener", "=", "Listener", ".", "new", "(", "type", ",", "callback", ",", "once", ")", "listeners", "[", "type", "]", "||=", "[", "]", "listeners", "[", "type", "]", "<<", "listener", "emit", "(", ":new_listener", ",", "self", ",", "type", ",", "once", ",", "callback", ")", "listener", "end" ]
Register the given block to be called when the events of type +type+ will be emitted. if +once+, the block will be called once
[ "Register", "the", "given", "block", "to", "be", "called", "when", "the", "events", "of", "type", "+", "type", "+", "will", "be", "emitted", ".", "if", "+", "once", "+", "the", "block", "will", "be", "called", "once" ]
196ce7784fc414d9751a3492427b506054203185
https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L20-L26
9,688
cdarne/triton
lib/triton/messenger.rb
Triton.Messenger.remove_listener
def remove_listener(listener) type = listener.type if listeners.has_key? type listeners[type].delete(listener) listeners.delete(type) if listeners[type].empty? end end
ruby
def remove_listener(listener) type = listener.type if listeners.has_key? type listeners[type].delete(listener) listeners.delete(type) if listeners[type].empty? end end
[ "def", "remove_listener", "(", "listener", ")", "type", "=", "listener", ".", "type", "if", "listeners", ".", "has_key?", "type", "listeners", "[", "type", "]", ".", "delete", "(", "listener", ")", "listeners", ".", "delete", "(", "type", ")", "if", "listeners", "[", "type", "]", ".", "empty?", "end", "end" ]
Unregister the given block. It won't be call then went an event is emitted.
[ "Unregister", "the", "given", "block", ".", "It", "won", "t", "be", "call", "then", "went", "an", "event", "is", "emitted", "." ]
196ce7784fc414d9751a3492427b506054203185
https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L36-L42
9,689
cdarne/triton
lib/triton/messenger.rb
Triton.Messenger.emit
def emit(type, sender=nil, *args) listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type end
ruby
def emit(type, sender=nil, *args) listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type end
[ "def", "emit", "(", "type", ",", "sender", "=", "nil", ",", "*", "args", ")", "listeners", "[", "type", "]", ".", "each", "{", "|", "l", "|", "l", ".", "fire", "(", "sender", ",", "args", ")", "}", "if", "listeners", ".", "has_key?", "type", "end" ]
Emit an event of type +type+ and call all the registered listeners to this event. The +sender+ param will help the listener to identify who is emitting the event. You can pass then every additional arguments you'll need
[ "Emit", "an", "event", "of", "type", "+", "type", "+", "and", "call", "all", "the", "registered", "listeners", "to", "this", "event", ".", "The", "+", "sender", "+", "param", "will", "help", "the", "listener", "to", "identify", "who", "is", "emitting", "the", "event", ".", "You", "can", "pass", "then", "every", "additional", "arguments", "you", "ll", "need" ]
196ce7784fc414d9751a3492427b506054203185
https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L57-L59
9,690
yipdw/analysand
lib/analysand/change_watcher.rb
Analysand.ChangeWatcher.changes_feed_uri
def changes_feed_uri query = { 'feed' => 'continuous', 'heartbeat' => '10000' } customize_query(query) uri = (@db.respond_to?(:uri) ? @db.uri : URI(@db)).dup uri.path += '/_changes' uri.query = build_query(query) uri end
ruby
def changes_feed_uri query = { 'feed' => 'continuous', 'heartbeat' => '10000' } customize_query(query) uri = (@db.respond_to?(:uri) ? @db.uri : URI(@db)).dup uri.path += '/_changes' uri.query = build_query(query) uri end
[ "def", "changes_feed_uri", "query", "=", "{", "'feed'", "=>", "'continuous'", ",", "'heartbeat'", "=>", "'10000'", "}", "customize_query", "(", "query", ")", "uri", "=", "(", "@db", ".", "respond_to?", "(", ":uri", ")", "?", "@db", ".", "uri", ":", "URI", "(", "@db", ")", ")", ".", "dup", "uri", ".", "path", "+=", "'/_changes'", "uri", ".", "query", "=", "build_query", "(", "query", ")", "uri", "end" ]
Checks services. If all services pass muster, enters a read loop. The database parameter may be either a URL-as-string or a Analysand::Database. If overriding the initializer, you MUST call super. The URI of the changes feed. This URI incorporates any changes made by customize_query.
[ "Checks", "services", ".", "If", "all", "services", "pass", "muster", "enters", "a", "read", "loop", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/change_watcher.rb#L93-L105
9,691
yipdw/analysand
lib/analysand/change_watcher.rb
Analysand.ChangeWatcher.waiter_for
def waiter_for(id) @waiting[id] = true Waiter.new do loop do break true if !@waiting[id] sleep 0.1 end end end
ruby
def waiter_for(id) @waiting[id] = true Waiter.new do loop do break true if !@waiting[id] sleep 0.1 end end end
[ "def", "waiter_for", "(", "id", ")", "@waiting", "[", "id", "]", "=", "true", "Waiter", ".", "new", "do", "loop", "do", "break", "true", "if", "!", "@waiting", "[", "id", "]", "sleep", "0.1", "end", "end", "end" ]
Returns an object that can be used to block a thread until a document with the given ID has been processed. Intended for testing.
[ "Returns", "an", "object", "that", "can", "be", "used", "to", "block", "a", "thread", "until", "a", "document", "with", "the", "given", "ID", "has", "been", "processed", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/change_watcher.rb#L208-L217
9,692
netzpirat/guard-rspectacle
lib/guard/rspectacle.rb
Guard.RSpectacle.reload
def reload Dir.glob('**/*.rb').each { |file| Reloader.reload_file(file) } self.last_run_passed = true self.rerun_specs = [] end
ruby
def reload Dir.glob('**/*.rb').each { |file| Reloader.reload_file(file) } self.last_run_passed = true self.rerun_specs = [] end
[ "def", "reload", "Dir", ".", "glob", "(", "'**/*.rb'", ")", ".", "each", "{", "|", "file", "|", "Reloader", ".", "reload_file", "(", "file", ")", "}", "self", ".", "last_run_passed", "=", "true", "self", ".", "rerun_specs", "=", "[", "]", "end" ]
Gets called when the Guard should reload itself. @raise [:task_has_failed] when run_on_change has failed
[ "Gets", "called", "when", "the", "Guard", "should", "reload", "itself", "." ]
e71dacfa8ab0a2d7f3ec8c0933190268ed17344a
https://github.com/netzpirat/guard-rspectacle/blob/e71dacfa8ab0a2d7f3ec8c0933190268ed17344a/lib/guard/rspectacle.rb#L66-L71
9,693
ktonon/code_node
spec/fixtures/activerecord/src/active_record/counter_cache.rb
ActiveRecord.CounterCache.reset_counters
def reset_counters(id, *counters) object = find(id) counters.each do |association| has_many_association = reflect_on_association(association.to_sym) if has_many_association.options[:as] has_many_association.options[:as].to_s.classify else self.name end if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection has_many_association = has_many_association.through_reflection end foreign_key = has_many_association.foreign_key.to_s child_class = has_many_association.klass belongs_to = child_class.reflect_on_all_associations(:belongs_to) reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? } counter_name = reflection.counter_cache_column stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({ arel_table[counter_name] => object.send(association).count }) connection.update stmt end return true end
ruby
def reset_counters(id, *counters) object = find(id) counters.each do |association| has_many_association = reflect_on_association(association.to_sym) if has_many_association.options[:as] has_many_association.options[:as].to_s.classify else self.name end if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection has_many_association = has_many_association.through_reflection end foreign_key = has_many_association.foreign_key.to_s child_class = has_many_association.klass belongs_to = child_class.reflect_on_all_associations(:belongs_to) reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? } counter_name = reflection.counter_cache_column stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({ arel_table[counter_name] => object.send(association).count }) connection.update stmt end return true end
[ "def", "reset_counters", "(", "id", ",", "*", "counters", ")", "object", "=", "find", "(", "id", ")", "counters", ".", "each", "do", "|", "association", "|", "has_many_association", "=", "reflect_on_association", "(", "association", ".", "to_sym", ")", "if", "has_many_association", ".", "options", "[", ":as", "]", "has_many_association", ".", "options", "[", ":as", "]", ".", "to_s", ".", "classify", "else", "self", ".", "name", "end", "if", "has_many_association", ".", "is_a?", "ActiveRecord", "::", "Reflection", "::", "ThroughReflection", "has_many_association", "=", "has_many_association", ".", "through_reflection", "end", "foreign_key", "=", "has_many_association", ".", "foreign_key", ".", "to_s", "child_class", "=", "has_many_association", ".", "klass", "belongs_to", "=", "child_class", ".", "reflect_on_all_associations", "(", ":belongs_to", ")", "reflection", "=", "belongs_to", ".", "find", "{", "|", "e", "|", "e", ".", "foreign_key", ".", "to_s", "==", "foreign_key", "&&", "e", ".", "options", "[", ":counter_cache", "]", ".", "present?", "}", "counter_name", "=", "reflection", ".", "counter_cache_column", "stmt", "=", "unscoped", ".", "where", "(", "arel_table", "[", "primary_key", "]", ".", "eq", "(", "object", ".", "id", ")", ")", ".", "arel", ".", "compile_update", "(", "{", "arel_table", "[", "counter_name", "]", "=>", "object", ".", "send", "(", "association", ")", ".", "count", "}", ")", "connection", ".", "update", "stmt", "end", "return", "true", "end" ]
Resets one or more counter caches to their correct value using an SQL count query. This is useful when adding new counter caches, or if the counter has been corrupted or modified directly by SQL. ==== Parameters * +id+ - The id of the object you wish to reset a counter on. * +counters+ - One or more counter names to reset ==== Examples # For Post with id #1 records reset the comments_count Post.reset_counters(1, :comments)
[ "Resets", "one", "or", "more", "counter", "caches", "to", "their", "correct", "value", "using", "an", "SQL", "count", "query", ".", "This", "is", "useful", "when", "adding", "new", "counter", "caches", "or", "if", "the", "counter", "has", "been", "corrupted", "or", "modified", "directly", "by", "SQL", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/counter_cache.rb#L17-L44
9,694
iamcutler/deal-redemptions
app/controllers/deal_redemptions/admin/redeem_codes_controller.rb
DealRedemptions.Admin::RedeemCodesController.build_search_query
def build_search_query string = params[:search].split ' ' redeem_codes = DealRedemptions::RedeemCode.arel_table companies = DealRedemptions::Company.arel_table query = redeem_codes.project( redeem_codes[:id], redeem_codes[:company_id], redeem_codes[:code], redeem_codes[:status], redeem_codes[:created_at] ) .join(companies) .on(redeem_codes[:company_id] .eq(companies[:id])) string.each do |s| query.where(redeem_codes[:code].matches("%#{s}%")) end query.to_sql end
ruby
def build_search_query string = params[:search].split ' ' redeem_codes = DealRedemptions::RedeemCode.arel_table companies = DealRedemptions::Company.arel_table query = redeem_codes.project( redeem_codes[:id], redeem_codes[:company_id], redeem_codes[:code], redeem_codes[:status], redeem_codes[:created_at] ) .join(companies) .on(redeem_codes[:company_id] .eq(companies[:id])) string.each do |s| query.where(redeem_codes[:code].matches("%#{s}%")) end query.to_sql end
[ "def", "build_search_query", "string", "=", "params", "[", ":search", "]", ".", "split", "' '", "redeem_codes", "=", "DealRedemptions", "::", "RedeemCode", ".", "arel_table", "companies", "=", "DealRedemptions", "::", "Company", ".", "arel_table", "query", "=", "redeem_codes", ".", "project", "(", "redeem_codes", "[", ":id", "]", ",", "redeem_codes", "[", ":company_id", "]", ",", "redeem_codes", "[", ":code", "]", ",", "redeem_codes", "[", ":status", "]", ",", "redeem_codes", "[", ":created_at", "]", ")", ".", "join", "(", "companies", ")", ".", "on", "(", "redeem_codes", "[", ":company_id", "]", ".", "eq", "(", "companies", "[", ":id", "]", ")", ")", "string", ".", "each", "do", "|", "s", "|", "query", ".", "where", "(", "redeem_codes", "[", ":code", "]", ".", "matches", "(", "\"%#{s}%\"", ")", ")", "end", "query", ".", "to_sql", "end" ]
Search redemption codes
[ "Search", "redemption", "codes" ]
b9b06df288c84a5bb0c0588ad0beca80b14edd31
https://github.com/iamcutler/deal-redemptions/blob/b9b06df288c84a5bb0c0588ad0beca80b14edd31/app/controllers/deal_redemptions/admin/redeem_codes_controller.rb#L80-L100
9,695
ryansobol/mango
lib/mango/runner.rb
Mango.Runner.create
def create(path) self.destination_root = path copy_file(".gitignore") copy_file("config.ru") copy_file("Gemfile") copy_file("Procfile") copy_file("README.md") copy_content copy_themes end
ruby
def create(path) self.destination_root = path copy_file(".gitignore") copy_file("config.ru") copy_file("Gemfile") copy_file("Procfile") copy_file("README.md") copy_content copy_themes end
[ "def", "create", "(", "path", ")", "self", ".", "destination_root", "=", "path", "copy_file", "(", "\".gitignore\"", ")", "copy_file", "(", "\"config.ru\"", ")", "copy_file", "(", "\"Gemfile\"", ")", "copy_file", "(", "\"Procfile\"", ")", "copy_file", "(", "\"README.md\"", ")", "copy_content", "copy_themes", "end" ]
Creates a new Mango application at the specified path @param [String] path
[ "Creates", "a", "new", "Mango", "application", "at", "the", "specified", "path" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/runner.rb#L18-L29
9,696
conversation/raca
lib/raca/server.rb
Raca.Server.details
def details data = servers_client.get(server_path, json_headers).body JSON.parse(data)['server'] end
ruby
def details data = servers_client.get(server_path, json_headers).body JSON.parse(data)['server'] end
[ "def", "details", "data", "=", "servers_client", ".", "get", "(", "server_path", ",", "json_headers", ")", ".", "body", "JSON", ".", "parse", "(", "data", ")", "[", "'server'", "]", "end" ]
A Hash of various matadata about the server
[ "A", "Hash", "of", "various", "matadata", "about", "the", "server" ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/server.rb#L51-L54
9,697
brianmichel/Crate-API
lib/crate_api/crates.rb
CrateAPI.Crates.add
def add(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}})) raise CrateLimitReachedError, response["message"] unless response["status"] != "failure" end
ruby
def add(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}})) raise CrateLimitReachedError, response["message"] unless response["status"] != "failure" end
[ "def", "add", "(", "name", ")", "response", "=", "JSON", ".", "parse", "(", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}\"", ",", ":post", ",", "{", ":body", "=>", "{", ":name", "=>", "name", "}", "}", ")", ")", "raise", "CrateLimitReachedError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Add a new crate. @param [String] name of the crate to add. @return [nil] no output from this method is expected if everything goes right.
[ "Add", "a", "new", "crate", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crates.rb#L20-L23
9,698
OSHPark/ruby-api-client
lib/oshpark/client.rb
Oshpark.Client.authenticate
def authenticate email, credentials={} if password = credentials[:with_password] refresh_token email: email, password: password elsif secret = credentials[:with_api_secret] api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s refresh_token email: email, api_key: api_key else raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments." end end
ruby
def authenticate email, credentials={} if password = credentials[:with_password] refresh_token email: email, password: password elsif secret = credentials[:with_api_secret] api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s refresh_token email: email, api_key: api_key else raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments." end end
[ "def", "authenticate", "email", ",", "credentials", "=", "{", "}", "if", "password", "=", "credentials", "[", ":with_password", "]", "refresh_token", "email", ":", "email", ",", "password", ":", "password", "elsif", "secret", "=", "credentials", "[", ":with_api_secret", "]", "api_key", "=", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", "(", "\"#{email}:#{secret}:#{token.token}\"", ")", ".", "to_s", "refresh_token", "email", ":", "email", ",", "api_key", ":", "api_key", "else", "raise", "ArgumentError", ",", "\"Must provide either `with_password` or `with_api_secret` arguments.\"", "end", "end" ]
Create an new Client object. @param connection: pass in a subclass of connection which implements the `request` method with whichever HTTP client library you prefer. Default is Net::HTTP. Authenticate to the API using a email and password. @param email @param credentials A hash with either the `with_password` or `with_api_secret` key.
[ "Create", "an", "new", "Client", "object", "." ]
629c633c6c2189e2634b4b8721e6f0711209703b
https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L30-L39
9,699
OSHPark/ruby-api-client
lib/oshpark/client.rb
Oshpark.Client.pricing
def pricing width, height, pcb_layers, quantity = nil post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity} end
ruby
def pricing width, height, pcb_layers, quantity = nil post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity} end
[ "def", "pricing", "width", ",", "height", ",", "pcb_layers", ",", "quantity", "=", "nil", "post_request", "\"pricing\"", ",", "{", "width_in_mils", ":", "width", ",", "height_in_mils", ":", "height", ",", "pcb_layers", ":", "pcb_layers", ",", "quantity", ":", "quantity", "}", "end" ]
Request a price estimate @param width In thousands of an Inch @param height In thousands of an Inch @param layers @param quantity Optional Defaults to the minimum quantity
[ "Request", "a", "price", "estimate" ]
629c633c6c2189e2634b4b8721e6f0711209703b
https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L91-L93