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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
1,500
rightscale/right_api_client
lib/right_api_client/client.rb
RightApi.Client.do_get
def do_get(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request(true) do # Return content type so the resulting resource object knows what kind of resource it is. resource_type, body = @rest_client[path].get(headers) do |response, request, result, &block| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 # Get the resource_type from the content_type, the resource_type # will be used later to add relevant methods to relevant resources type = if result.content_type.index('rightscale') get_resource_type(result.content_type) elsif result.content_type.index('text/plain') 'text' else '' end # work around getting ASCII-8BIT from some resources like audit entry detail charset = get_charset(response.headers) if charset && response.body.encoding != charset response.body.force_encoding(charset) end # raise an error if the API is misbehaving and returning an empty response when it shouldn't if type != 'text' && response.body.empty? raise EmptyBodyError.new(request, response) end [type, response.body] when 301, 302 update_api_url(response) response.follow_redirection(request, result, &block) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :get, path, params, req, res) end data = if resource_type == 'text' { 'text' => body } else JSON.parse(body, :allow_nan => true) end [resource_type, path, data] end
ruby
def do_get(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request(true) do # Return content type so the resulting resource object knows what kind of resource it is. resource_type, body = @rest_client[path].get(headers) do |response, request, result, &block| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 # Get the resource_type from the content_type, the resource_type # will be used later to add relevant methods to relevant resources type = if result.content_type.index('rightscale') get_resource_type(result.content_type) elsif result.content_type.index('text/plain') 'text' else '' end # work around getting ASCII-8BIT from some resources like audit entry detail charset = get_charset(response.headers) if charset && response.body.encoding != charset response.body.force_encoding(charset) end # raise an error if the API is misbehaving and returning an empty response when it shouldn't if type != 'text' && response.body.empty? raise EmptyBodyError.new(request, response) end [type, response.body] when 301, 302 update_api_url(response) response.follow_redirection(request, result, &block) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :get, path, params, req, res) end data = if resource_type == 'text' { 'text' => body } else JSON.parse(body, :allow_nan => true) end [resource_type, path, data] end
[ "def", "do_get", "(", "path", ",", "params", "=", "{", "}", ")", "login", "if", "need_login?", "# Resource id is a special param as it needs to be added to the path", "path", "=", "add_id_and_params_to_path", "(", "path", ",", "params", ")", "req", ",", "res", ",", "resource_type", ",", "body", "=", "nil", "begin", "retry_request", "(", "true", ")", "do", "# Return content type so the resulting resource object knows what kind of resource it is.", "resource_type", ",", "body", "=", "@rest_client", "[", "path", "]", ".", "get", "(", "headers", ")", "do", "|", "response", ",", "request", ",", "result", ",", "&", "block", "|", "req", ",", "res", "=", "request", ",", "response", "update_cookies", "(", "response", ")", "update_last_request", "(", "request", ",", "response", ")", "case", "response", ".", "code", "when", "200", "# Get the resource_type from the content_type, the resource_type", "# will be used later to add relevant methods to relevant resources", "type", "=", "if", "result", ".", "content_type", ".", "index", "(", "'rightscale'", ")", "get_resource_type", "(", "result", ".", "content_type", ")", "elsif", "result", ".", "content_type", ".", "index", "(", "'text/plain'", ")", "'text'", "else", "''", "end", "# work around getting ASCII-8BIT from some resources like audit entry detail", "charset", "=", "get_charset", "(", "response", ".", "headers", ")", "if", "charset", "&&", "response", ".", "body", ".", "encoding", "!=", "charset", "response", ".", "body", ".", "force_encoding", "(", "charset", ")", "end", "# raise an error if the API is misbehaving and returning an empty response when it shouldn't", "if", "type", "!=", "'text'", "&&", "response", ".", "body", ".", "empty?", "raise", "EmptyBodyError", ".", "new", "(", "request", ",", "response", ")", "end", "[", "type", ",", "response", ".", "body", "]", "when", "301", ",", "302", "update_api_url", "(", "response", ")", "response", ".", "follow_redirection", "(", "request", ",", "result", ",", "block", ")", "when", "404", "raise", "UnknownRouteError", ".", "new", "(", "request", ",", "response", ")", "else", "raise", "ApiError", ".", "new", "(", "request", ",", "response", ")", "end", "end", "end", "rescue", "=>", "e", "raise", "wrap", "(", "e", ",", ":get", ",", "path", ",", "params", ",", "req", ",", "res", ")", "end", "data", "=", "if", "resource_type", "==", "'text'", "{", "'text'", "=>", "body", "}", "else", "JSON", ".", "parse", "(", "body", ",", ":allow_nan", "=>", "true", ")", "end", "[", "resource_type", ",", "path", ",", "data", "]", "end" ]
Generic get params are NOT read only
[ "Generic", "get", "params", "are", "NOT", "read", "only" ]
29534dcebbc96fc0727e2d57bac73e349a910f08
https://github.com/rightscale/right_api_client/blob/29534dcebbc96fc0727e2d57bac73e349a910f08/lib/right_api_client/client.rb#L351-L412
1,501
rightscale/right_api_client
lib/right_api_client/client.rb
RightApi.Client.re_login?
def re_login?(e) auth_error = (e.response_code == 403 && e.message =~ %r(.*cookie is expired or invalid)) || e.response_code == 401 renewable_creds = (@instance_token || (@email && (@password || @password_base64)) || @refresh_token) auth_error && renewable_creds end
ruby
def re_login?(e) auth_error = (e.response_code == 403 && e.message =~ %r(.*cookie is expired or invalid)) || e.response_code == 401 renewable_creds = (@instance_token || (@email && (@password || @password_base64)) || @refresh_token) auth_error && renewable_creds end
[ "def", "re_login?", "(", "e", ")", "auth_error", "=", "(", "e", ".", "response_code", "==", "403", "&&", "e", ".", "message", "=~", "%r(", ")", ")", "||", "e", ".", "response_code", "==", "401", "renewable_creds", "=", "(", "@instance_token", "||", "(", "@email", "&&", "(", "@password", "||", "@password_base64", ")", ")", "||", "@refresh_token", ")", "auth_error", "&&", "renewable_creds", "end" ]
Determine whether an exception can be fixed by logging in again. @param e [ApiError] the exception to check @return [Boolean] true if re-login is appropriate
[ "Determine", "whether", "an", "exception", "can", "be", "fixed", "by", "logging", "in", "again", "." ]
29534dcebbc96fc0727e2d57bac73e349a910f08
https://github.com/rightscale/right_api_client/blob/29534dcebbc96fc0727e2d57bac73e349a910f08/lib/right_api_client/client.rb#L576-L585
1,502
voxpupuli/ra10ke
lib/ra10ke/solve.rb
Ra10ke::Solve.RakeTask.get_version_req
def get_version_req(dep) req = get_key_or_sym(dep, :version_requirement) req = get_key_or_sym(dep, :version_range) unless req req end
ruby
def get_version_req(dep) req = get_key_or_sym(dep, :version_requirement) req = get_key_or_sym(dep, :version_range) unless req req end
[ "def", "get_version_req", "(", "dep", ")", "req", "=", "get_key_or_sym", "(", "dep", ",", ":version_requirement", ")", "req", "=", "get_key_or_sym", "(", "dep", ",", ":version_range", ")", "unless", "req", "req", "end" ]
At least puppet-extlib has malformed metadata
[ "At", "least", "puppet", "-", "extlib", "has", "malformed", "metadata" ]
b3955a76ee4f9200e5bfd046eb5a1dfdbd46f897
https://github.com/voxpupuli/ra10ke/blob/b3955a76ee4f9200e5bfd046eb5a1dfdbd46f897/lib/ra10ke/solve.rb#L148-L152
1,503
prometheus-ev/jekyll-rendering
lib/jekyll/rendering.rb
Jekyll.Convertible.do_layout
def do_layout(payload, layouts) info = { :filters => [Jekyll::Filters], :registers => { :site => site } } payload['pygments_prefix'] = converter.pygments_prefix payload['pygments_suffix'] = converter.pygments_suffix # render and transform content (this becomes the final content of the object) self.content = engine.render(payload, content, info, data) transform # output keeps track of what will finally be written self.output = content # recursively render layouts layout = self while layout = layouts[layout.data['layout']] payload = payload.deep_merge('content' => output, 'page' => layout.data) self.output = engine.render(payload, output, info, data, layout.content) end end
ruby
def do_layout(payload, layouts) info = { :filters => [Jekyll::Filters], :registers => { :site => site } } payload['pygments_prefix'] = converter.pygments_prefix payload['pygments_suffix'] = converter.pygments_suffix # render and transform content (this becomes the final content of the object) self.content = engine.render(payload, content, info, data) transform # output keeps track of what will finally be written self.output = content # recursively render layouts layout = self while layout = layouts[layout.data['layout']] payload = payload.deep_merge('content' => output, 'page' => layout.data) self.output = engine.render(payload, output, info, data, layout.content) end end
[ "def", "do_layout", "(", "payload", ",", "layouts", ")", "info", "=", "{", ":filters", "=>", "[", "Jekyll", "::", "Filters", "]", ",", ":registers", "=>", "{", ":site", "=>", "site", "}", "}", "payload", "[", "'pygments_prefix'", "]", "=", "converter", ".", "pygments_prefix", "payload", "[", "'pygments_suffix'", "]", "=", "converter", ".", "pygments_suffix", "# render and transform content (this becomes the final content of the object)", "self", ".", "content", "=", "engine", ".", "render", "(", "payload", ",", "content", ",", "info", ",", "data", ")", "transform", "# output keeps track of what will finally be written", "self", ".", "output", "=", "content", "# recursively render layouts", "layout", "=", "self", "while", "layout", "=", "layouts", "[", "layout", ".", "data", "[", "'layout'", "]", "]", "payload", "=", "payload", ".", "deep_merge", "(", "'content'", "=>", "output", ",", "'page'", "=>", "layout", ".", "data", ")", "self", ".", "output", "=", "engine", ".", "render", "(", "payload", ",", "output", ",", "info", ",", "data", ",", "layout", ".", "content", ")", "end", "end" ]
Overwrites the original method to use the configured rendering engine.
[ "Overwrites", "the", "original", "method", "to", "use", "the", "configured", "rendering", "engine", "." ]
977c1ac2260f9e12a7eeb803ed52bf1bef57ff21
https://github.com/prometheus-ev/jekyll-rendering/blob/977c1ac2260f9e12a7eeb803ed52bf1bef57ff21/lib/jekyll/rendering.rb#L55-L75
1,504
socketry/lightio
lib/lightio/watchers/io.rb
LightIO::Watchers.IO.monitor
def monitor(interests=:rw) @monitor ||= begin raise @error if @error monitor = @ioloop.add_io_wait(@io, interests) {callback_on_waiting} ObjectSpace.define_finalizer(self, self.class.finalizer(monitor)) monitor end end
ruby
def monitor(interests=:rw) @monitor ||= begin raise @error if @error monitor = @ioloop.add_io_wait(@io, interests) {callback_on_waiting} ObjectSpace.define_finalizer(self, self.class.finalizer(monitor)) monitor end end
[ "def", "monitor", "(", "interests", "=", ":rw", ")", "@monitor", "||=", "begin", "raise", "@error", "if", "@error", "monitor", "=", "@ioloop", ".", "add_io_wait", "(", "@io", ",", "interests", ")", "{", "callback_on_waiting", "}", "ObjectSpace", ".", "define_finalizer", "(", "self", ",", "self", ".", "class", ".", "finalizer", "(", "monitor", ")", ")", "monitor", "end", "end" ]
Create a io watcher @param [Socket] io An IO-able object @param [Symbol] interests :r, :w, :rw - Is io readable? writeable? or both @return [LightIO::Watchers::IO] NIO::Monitor
[ "Create", "a", "io", "watcher" ]
dd99c751a003d68234dd5ce1e3ecf1b7530b98b4
https://github.com/socketry/lightio/blob/dd99c751a003d68234dd5ce1e3ecf1b7530b98b4/lib/lightio/watchers/io.rb#L31-L38
1,505
socketry/lightio
lib/lightio/watchers/io.rb
LightIO::Watchers.IO.wait_in_ioloop
def wait_in_ioloop raise LightIO::Error, "Watchers::IO can't cross threads" if @ioloop != LightIO::Core::IOloop.current raise EOFError, "can't wait closed IO watcher" if @monitor.closed? @ioloop.wait(self) end
ruby
def wait_in_ioloop raise LightIO::Error, "Watchers::IO can't cross threads" if @ioloop != LightIO::Core::IOloop.current raise EOFError, "can't wait closed IO watcher" if @monitor.closed? @ioloop.wait(self) end
[ "def", "wait_in_ioloop", "raise", "LightIO", "::", "Error", ",", "\"Watchers::IO can't cross threads\"", "if", "@ioloop", "!=", "LightIO", "::", "Core", "::", "IOloop", ".", "current", "raise", "EOFError", ",", "\"can't wait closed IO watcher\"", "if", "@monitor", ".", "closed?", "@ioloop", ".", "wait", "(", "self", ")", "end" ]
Blocking until io interests is satisfied
[ "Blocking", "until", "io", "interests", "is", "satisfied" ]
dd99c751a003d68234dd5ce1e3ecf1b7530b98b4
https://github.com/socketry/lightio/blob/dd99c751a003d68234dd5ce1e3ecf1b7530b98b4/lib/lightio/watchers/io.rb#L155-L159
1,506
code-and-effect/effective_orders
app/models/effective/order.rb
Effective.Order.assign_confirmed_if_valid!
def assign_confirmed_if_valid! return unless pending? self.state = EffectiveOrders::CONFIRMED return true if valid? self.errors.clear self.state = EffectiveOrders::PENDING false end
ruby
def assign_confirmed_if_valid! return unless pending? self.state = EffectiveOrders::CONFIRMED return true if valid? self.errors.clear self.state = EffectiveOrders::PENDING false end
[ "def", "assign_confirmed_if_valid!", "return", "unless", "pending?", "self", ".", "state", "=", "EffectiveOrders", "::", "CONFIRMED", "return", "true", "if", "valid?", "self", ".", "errors", ".", "clear", "self", ".", "state", "=", "EffectiveOrders", "::", "PENDING", "false", "end" ]
This lets us skip to the confirmed workflow for an admin...
[ "This", "lets", "us", "skip", "to", "the", "confirmed", "workflow", "for", "an", "admin", "..." ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/models/effective/order.rb#L300-L309
1,507
code-and-effect/effective_orders
app/models/effective/subscripter.rb
Effective.Subscripter.create_stripe_token!
def create_stripe_token! return if stripe_token.blank? Rails.logger.info "[STRIPE] update source: #{stripe_token}" customer.stripe_customer.source = stripe_token customer.stripe_customer.save return if customer.stripe_customer.default_source.blank? card = customer.stripe_customer.sources.retrieve(customer.stripe_customer.default_source) customer.active_card = "**** **** **** #{card.last4} #{card.brand} #{card.exp_month}/#{card.exp_year}" customer.save! end
ruby
def create_stripe_token! return if stripe_token.blank? Rails.logger.info "[STRIPE] update source: #{stripe_token}" customer.stripe_customer.source = stripe_token customer.stripe_customer.save return if customer.stripe_customer.default_source.blank? card = customer.stripe_customer.sources.retrieve(customer.stripe_customer.default_source) customer.active_card = "**** **** **** #{card.last4} #{card.brand} #{card.exp_month}/#{card.exp_year}" customer.save! end
[ "def", "create_stripe_token!", "return", "if", "stripe_token", ".", "blank?", "Rails", ".", "logger", ".", "info", "\"[STRIPE] update source: #{stripe_token}\"", "customer", ".", "stripe_customer", ".", "source", "=", "stripe_token", "customer", ".", "stripe_customer", ".", "save", "return", "if", "customer", ".", "stripe_customer", ".", "default_source", ".", "blank?", "card", "=", "customer", ".", "stripe_customer", ".", "sources", ".", "retrieve", "(", "customer", ".", "stripe_customer", ".", "default_source", ")", "customer", ".", "active_card", "=", "\"**** **** **** #{card.last4} #{card.brand} #{card.exp_month}/#{card.exp_year}\"", "customer", ".", "save!", "end" ]
Update stripe customer card
[ "Update", "stripe", "customer", "card" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/models/effective/subscripter.rb#L87-L99
1,508
code-and-effect/effective_orders
app/models/effective/subscripter.rb
Effective.Subscripter.metadata
def metadata { :user_id => user.id.to_s, :user => user.to_s.truncate(500), (subscription.subscribable_type.downcase + '_id').to_sym => subscription.subscribable.id.to_s, subscription.subscribable_type.downcase.to_sym => subscription.subscribable.to_s } end
ruby
def metadata { :user_id => user.id.to_s, :user => user.to_s.truncate(500), (subscription.subscribable_type.downcase + '_id').to_sym => subscription.subscribable.id.to_s, subscription.subscribable_type.downcase.to_sym => subscription.subscribable.to_s } end
[ "def", "metadata", "{", ":user_id", "=>", "user", ".", "id", ".", "to_s", ",", ":user", "=>", "user", ".", "to_s", ".", "truncate", "(", "500", ")", ",", "(", "subscription", ".", "subscribable_type", ".", "downcase", "+", "'_id'", ")", ".", "to_sym", "=>", "subscription", ".", "subscribable", ".", "id", ".", "to_s", ",", "subscription", ".", "subscribable_type", ".", "downcase", ".", "to_sym", "=>", "subscription", ".", "subscribable", ".", "to_s", "}", "end" ]
The stripe metadata limit is 500 characters
[ "The", "stripe", "metadata", "limit", "is", "500", "characters" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/models/effective/subscripter.rb#L176-L183
1,509
futurechimp/plissken
lib/plissken/methods.rb
Plissken.Methods.to_snake_keys
def to_snake_keys(value = self) case value when Array value.map { |v| to_snake_keys(v) } when Hash snake_hash(value) else value end end
ruby
def to_snake_keys(value = self) case value when Array value.map { |v| to_snake_keys(v) } when Hash snake_hash(value) else value end end
[ "def", "to_snake_keys", "(", "value", "=", "self", ")", "case", "value", "when", "Array", "value", ".", "map", "{", "|", "v", "|", "to_snake_keys", "(", "v", ")", "}", "when", "Hash", "snake_hash", "(", "value", ")", "else", "value", "end", "end" ]
Recursively converts CamelCase and camelBack JSON-style hash keys to Rubyish snake_case, suitable for use during instantiation of Ruby model attributes.
[ "Recursively", "converts", "CamelCase", "and", "camelBack", "JSON", "-", "style", "hash", "keys", "to", "Rubyish", "snake_case", "suitable", "for", "use", "during", "instantiation", "of", "Ruby", "model", "attributes", "." ]
ec4cc2f9005e2b4bde421243918d7c75be04b679
https://github.com/futurechimp/plissken/blob/ec4cc2f9005e2b4bde421243918d7c75be04b679/lib/plissken/methods.rb#L9-L18
1,510
code-and-effect/effective_orders
app/controllers/effective/orders_controller.rb
Effective.OrdersController.new
def new @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :new, @order) unless @order.valid? flash[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." redirect_to(effective_orders.cart_path) return end end
ruby
def new @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :new, @order) unless @order.valid? flash[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." redirect_to(effective_orders.cart_path) return end end
[ "def", "new", "@order", "||=", "Effective", "::", "Order", ".", "new", "(", "view_context", ".", "current_cart", ")", "EffectiveOrders", ".", "authorize!", "(", "self", ",", ":new", ",", "@order", ")", "unless", "@order", ".", "valid?", "flash", "[", ":danger", "]", "=", "\"Unable to proceed: #{flash_errors(@order)}. Please try again.\"", "redirect_to", "(", "effective_orders", ".", "cart_path", ")", "return", "end", "end" ]
If you want to use the Add to Cart -> Checkout flow Add one or more items however you do. redirect_to effective_orders.new_order_path, which is here. This is the entry point for any Checkout button. It displayes an order based on the cart Always step1
[ "If", "you", "want", "to", "use", "the", "Add", "to", "Cart", "-", ">", "Checkout", "flow", "Add", "one", "or", "more", "items", "however", "you", "do", ".", "redirect_to", "effective_orders", ".", "new_order_path", "which", "is", "here", ".", "This", "is", "the", "entry", "point", "for", "any", "Checkout", "button", ".", "It", "displayes", "an", "order", "based", "on", "the", "cart", "Always", "step1" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/controllers/effective/orders_controller.rb#L25-L35
1,511
code-and-effect/effective_orders
app/controllers/effective/orders_controller.rb
Effective.OrdersController.create
def create @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :create, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :new end end
ruby
def create @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :create, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :new end end
[ "def", "create", "@order", "||=", "Effective", "::", "Order", ".", "new", "(", "view_context", ".", "current_cart", ")", "EffectiveOrders", ".", "authorize!", "(", "self", ",", ":create", ",", "@order", ")", "@order", ".", "assign_attributes", "(", "checkout_params", ")", "if", "(", "@order", ".", "confirm!", "rescue", "false", ")", "redirect_to", "(", "effective_orders", ".", "order_path", "(", "@order", ")", ")", "else", "flash", ".", "now", "[", ":danger", "]", "=", "\"Unable to proceed: #{flash_errors(@order)}. Please try again.\"", "render", ":new", "end", "end" ]
Confirms an order from the cart.
[ "Confirms", "an", "order", "from", "the", "cart", "." ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/controllers/effective/orders_controller.rb#L38-L50
1,512
code-and-effect/effective_orders
app/controllers/effective/orders_controller.rb
Effective.OrdersController.update
def update @order ||= Effective::Order.find(params[:id]) EffectiveOrders.authorize!(self, :update, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :edit end end
ruby
def update @order ||= Effective::Order.find(params[:id]) EffectiveOrders.authorize!(self, :update, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :edit end end
[ "def", "update", "@order", "||=", "Effective", "::", "Order", ".", "find", "(", "params", "[", ":id", "]", ")", "EffectiveOrders", ".", "authorize!", "(", "self", ",", ":update", ",", "@order", ")", "@order", ".", "assign_attributes", "(", "checkout_params", ")", "if", "(", "@order", ".", "confirm!", "rescue", "false", ")", "redirect_to", "(", "effective_orders", ".", "order_path", "(", "@order", ")", ")", "else", "flash", ".", "now", "[", ":danger", "]", "=", "\"Unable to proceed: #{flash_errors(@order)}. Please try again.\"", "render", ":edit", "end", "end" ]
Confirms the order from existing order
[ "Confirms", "the", "order", "from", "existing", "order" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/controllers/effective/orders_controller.rb#L71-L83
1,513
code-and-effect/effective_orders
app/controllers/effective/orders_controller.rb
Effective.OrdersController.index
def index @orders = Effective::Order.deep.purchased.where(user: current_user) @pending_orders = Effective::Order.deep.pending.where(user: current_user) EffectiveOrders.authorize!(self, :index, Effective::Order.new(user: current_user)) end
ruby
def index @orders = Effective::Order.deep.purchased.where(user: current_user) @pending_orders = Effective::Order.deep.pending.where(user: current_user) EffectiveOrders.authorize!(self, :index, Effective::Order.new(user: current_user)) end
[ "def", "index", "@orders", "=", "Effective", "::", "Order", ".", "deep", ".", "purchased", ".", "where", "(", "user", ":", "current_user", ")", "@pending_orders", "=", "Effective", "::", "Order", ".", "deep", ".", "pending", ".", "where", "(", "user", ":", "current_user", ")", "EffectiveOrders", ".", "authorize!", "(", "self", ",", ":index", ",", "Effective", "::", "Order", ".", "new", "(", "user", ":", "current_user", ")", ")", "end" ]
My Orders History
[ "My", "Orders", "History" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/controllers/effective/orders_controller.rb#L86-L91
1,514
code-and-effect/effective_orders
app/controllers/effective/orders_controller.rb
Effective.OrdersController.purchased
def purchased # Thank You! @order = if params[:id].present? Effective::Order.find(params[:id]) elsif current_user.present? Effective::Order.sorted.purchased_by(current_user).last end if @order.blank? redirect_to(effective_orders.orders_path) and return end EffectiveOrders.authorize!(self, :show, @order) redirect_to(effective_orders.order_path(@order)) unless @order.purchased? end
ruby
def purchased # Thank You! @order = if params[:id].present? Effective::Order.find(params[:id]) elsif current_user.present? Effective::Order.sorted.purchased_by(current_user).last end if @order.blank? redirect_to(effective_orders.orders_path) and return end EffectiveOrders.authorize!(self, :show, @order) redirect_to(effective_orders.order_path(@order)) unless @order.purchased? end
[ "def", "purchased", "# Thank You!", "@order", "=", "if", "params", "[", ":id", "]", ".", "present?", "Effective", "::", "Order", ".", "find", "(", "params", "[", ":id", "]", ")", "elsif", "current_user", ".", "present?", "Effective", "::", "Order", ".", "sorted", ".", "purchased_by", "(", "current_user", ")", ".", "last", "end", "if", "@order", ".", "blank?", "redirect_to", "(", "effective_orders", ".", "orders_path", ")", "and", "return", "end", "EffectiveOrders", ".", "authorize!", "(", "self", ",", ":show", ",", "@order", ")", "redirect_to", "(", "effective_orders", ".", "order_path", "(", "@order", ")", ")", "unless", "@order", ".", "purchased?", "end" ]
Thank you for Purchasing this Order. This is where a successfully purchased order ends up
[ "Thank", "you", "for", "Purchasing", "this", "Order", ".", "This", "is", "where", "a", "successfully", "purchased", "order", "ends", "up" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/controllers/effective/orders_controller.rb#L94-L108
1,515
code-and-effect/effective_orders
app/models/effective/cart.rb
Effective.Cart.add
def add(item, quantity: 1, unique: true) raise 'expecting an acts_as_purchasable object' unless item.kind_of?(ActsAsPurchasable) existing = ( if unique.kind_of?(Proc) cart_items.find { |cart_item| instance_exec(item, cart_item.purchasable, &unique) } elsif unique.kind_of?(Symbol) || (unique.kind_of?(String) && unique != 'true') raise "expected item to respond to unique #{unique}" unless item.respond_to?(unique) cart_items.find { |cart_item| cart_item.purchasable.respond_to?(unique) && item.send(unique) == cart_item.purchasable.send(unique) } elsif unique.present? find(item) end ) if existing if unique || (existing.unique.present?) existing.assign_attributes(purchasable: item, quantity: quantity, unique: existing.unique) else existing.quantity = existing.quantity + quantity end end if item.quantity_enabled? && (existing ? existing.quantity : quantity) > item.quantity_remaining raise EffectiveOrders::SoldOutException, "#{item.purchasable_name} is sold out" end existing ||= cart_items.build(purchasable: item, quantity: quantity, unique: (unique.to_s unless unique.kind_of?(Proc))) save! end
ruby
def add(item, quantity: 1, unique: true) raise 'expecting an acts_as_purchasable object' unless item.kind_of?(ActsAsPurchasable) existing = ( if unique.kind_of?(Proc) cart_items.find { |cart_item| instance_exec(item, cart_item.purchasable, &unique) } elsif unique.kind_of?(Symbol) || (unique.kind_of?(String) && unique != 'true') raise "expected item to respond to unique #{unique}" unless item.respond_to?(unique) cart_items.find { |cart_item| cart_item.purchasable.respond_to?(unique) && item.send(unique) == cart_item.purchasable.send(unique) } elsif unique.present? find(item) end ) if existing if unique || (existing.unique.present?) existing.assign_attributes(purchasable: item, quantity: quantity, unique: existing.unique) else existing.quantity = existing.quantity + quantity end end if item.quantity_enabled? && (existing ? existing.quantity : quantity) > item.quantity_remaining raise EffectiveOrders::SoldOutException, "#{item.purchasable_name} is sold out" end existing ||= cart_items.build(purchasable: item, quantity: quantity, unique: (unique.to_s unless unique.kind_of?(Proc))) save! end
[ "def", "add", "(", "item", ",", "quantity", ":", "1", ",", "unique", ":", "true", ")", "raise", "'expecting an acts_as_purchasable object'", "unless", "item", ".", "kind_of?", "(", "ActsAsPurchasable", ")", "existing", "=", "(", "if", "unique", ".", "kind_of?", "(", "Proc", ")", "cart_items", ".", "find", "{", "|", "cart_item", "|", "instance_exec", "(", "item", ",", "cart_item", ".", "purchasable", ",", "unique", ")", "}", "elsif", "unique", ".", "kind_of?", "(", "Symbol", ")", "||", "(", "unique", ".", "kind_of?", "(", "String", ")", "&&", "unique", "!=", "'true'", ")", "raise", "\"expected item to respond to unique #{unique}\"", "unless", "item", ".", "respond_to?", "(", "unique", ")", "cart_items", ".", "find", "{", "|", "cart_item", "|", "cart_item", ".", "purchasable", ".", "respond_to?", "(", "unique", ")", "&&", "item", ".", "send", "(", "unique", ")", "==", "cart_item", ".", "purchasable", ".", "send", "(", "unique", ")", "}", "elsif", "unique", ".", "present?", "find", "(", "item", ")", "end", ")", "if", "existing", "if", "unique", "||", "(", "existing", ".", "unique", ".", "present?", ")", "existing", ".", "assign_attributes", "(", "purchasable", ":", "item", ",", "quantity", ":", "quantity", ",", "unique", ":", "existing", ".", "unique", ")", "else", "existing", ".", "quantity", "=", "existing", ".", "quantity", "+", "quantity", "end", "end", "if", "item", ".", "quantity_enabled?", "&&", "(", "existing", "?", "existing", ".", "quantity", ":", "quantity", ")", ">", "item", ".", "quantity_remaining", "raise", "EffectiveOrders", "::", "SoldOutException", ",", "\"#{item.purchasable_name} is sold out\"", "end", "existing", "||=", "cart_items", ".", "build", "(", "purchasable", ":", "item", ",", "quantity", ":", "quantity", ",", "unique", ":", "(", "unique", ".", "to_s", "unless", "unique", ".", "kind_of?", "(", "Proc", ")", ")", ")", "save!", "end" ]
cart.add(@product, unique: -> (a, b) { a.kind_of?(Product) && b.kind_of?(Product) && a.category == b.category }) cart.add(@product, unique: :category) cart.add(@product, unique: false) # Add as many as you want
[ "cart", ".", "add", "(" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/models/effective/cart.rb#L19-L47
1,516
code-and-effect/effective_orders
app/mailers/effective/orders_mailer.rb
Effective.OrdersMailer.pending_order_invoice_to_buyer
def pending_order_invoice_to_buyer(order_param) return true unless EffectiveOrders.mailer[:send_pending_order_invoice_to_buyer] @order = (order_param.kind_of?(Effective::Order) ? order_param : Effective::Order.find(order_param)) @user = @order.user @subject = subject_for(@order, :pending_order_invoice_to_buyer, "Pending Order: ##{@order.to_param}") mail(to: @order.user.email, subject: @subject) end
ruby
def pending_order_invoice_to_buyer(order_param) return true unless EffectiveOrders.mailer[:send_pending_order_invoice_to_buyer] @order = (order_param.kind_of?(Effective::Order) ? order_param : Effective::Order.find(order_param)) @user = @order.user @subject = subject_for(@order, :pending_order_invoice_to_buyer, "Pending Order: ##{@order.to_param}") mail(to: @order.user.email, subject: @subject) end
[ "def", "pending_order_invoice_to_buyer", "(", "order_param", ")", "return", "true", "unless", "EffectiveOrders", ".", "mailer", "[", ":send_pending_order_invoice_to_buyer", "]", "@order", "=", "(", "order_param", ".", "kind_of?", "(", "Effective", "::", "Order", ")", "?", "order_param", ":", "Effective", "::", "Order", ".", "find", "(", "order_param", ")", ")", "@user", "=", "@order", ".", "user", "@subject", "=", "subject_for", "(", "@order", ",", ":pending_order_invoice_to_buyer", ",", "\"Pending Order: ##{@order.to_param}\"", ")", "mail", "(", "to", ":", "@order", ".", "user", ".", "email", ",", "subject", ":", "@subject", ")", "end" ]
This is sent when someone chooses to Pay by Cheque
[ "This", "is", "sent", "when", "someone", "chooses", "to", "Pay", "by", "Cheque" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/mailers/effective/orders_mailer.rb#L44-L53
1,517
code-and-effect/effective_orders
app/mailers/effective/orders_mailer.rb
Effective.OrdersMailer.subscription_payment_succeeded
def subscription_payment_succeeded(customer_param) return true unless EffectiveOrders.mailer[:send_subscription_payment_succeeded] @customer = (customer_param.kind_of?(Effective::Customer) ? customer_param : Effective::Customer.find(customer_param)) @subscriptions = @customer.subscriptions @user = @customer.user @subject = subject_for(@customer, :subscription_payment_succeeded, 'Thank you for your payment') mail(to: @customer.user.email, subject: @subject) end
ruby
def subscription_payment_succeeded(customer_param) return true unless EffectiveOrders.mailer[:send_subscription_payment_succeeded] @customer = (customer_param.kind_of?(Effective::Customer) ? customer_param : Effective::Customer.find(customer_param)) @subscriptions = @customer.subscriptions @user = @customer.user @subject = subject_for(@customer, :subscription_payment_succeeded, 'Thank you for your payment') mail(to: @customer.user.email, subject: @subject) end
[ "def", "subscription_payment_succeeded", "(", "customer_param", ")", "return", "true", "unless", "EffectiveOrders", ".", "mailer", "[", ":send_subscription_payment_succeeded", "]", "@customer", "=", "(", "customer_param", ".", "kind_of?", "(", "Effective", "::", "Customer", ")", "?", "customer_param", ":", "Effective", "::", "Customer", ".", "find", "(", "customer_param", ")", ")", "@subscriptions", "=", "@customer", ".", "subscriptions", "@user", "=", "@customer", ".", "user", "@subject", "=", "subject_for", "(", "@customer", ",", ":subscription_payment_succeeded", ",", "'Thank you for your payment'", ")", "mail", "(", "to", ":", "@customer", ".", "user", ".", "email", ",", "subject", ":", "@subject", ")", "end" ]
Sent by the invoice.payment_succeeded webhook event
[ "Sent", "by", "the", "invoice", ".", "payment_succeeded", "webhook", "event" ]
60eb8570b41080795448ae9c75e7da4da9edae9b
https://github.com/code-and-effect/effective_orders/blob/60eb8570b41080795448ae9c75e7da4da9edae9b/app/mailers/effective/orders_mailer.rb#L56-L66
1,518
molybdenum-99/infoboxer
lib/infoboxer/media_wiki.rb
Infoboxer.MediaWiki.get
def get(*titles, interwiki: nil, &processor) return interwikis(interwiki).get(*titles, &processor) if interwiki pages = get_h(*titles, &processor).values.compact titles.count == 1 ? pages.first : Tree::Nodes[*pages] end
ruby
def get(*titles, interwiki: nil, &processor) return interwikis(interwiki).get(*titles, &processor) if interwiki pages = get_h(*titles, &processor).values.compact titles.count == 1 ? pages.first : Tree::Nodes[*pages] end
[ "def", "get", "(", "*", "titles", ",", "interwiki", ":", "nil", ",", "&", "processor", ")", "return", "interwikis", "(", "interwiki", ")", ".", "get", "(", "titles", ",", "processor", ")", "if", "interwiki", "pages", "=", "get_h", "(", "titles", ",", "processor", ")", ".", "values", ".", "compact", "titles", ".", "count", "==", "1", "?", "pages", ".", "first", ":", "Tree", "::", "Nodes", "[", "pages", "]", "end" ]
Receive list of parsed MediaWiki pages for list of titles provided. All pages are received with single query to MediaWiki API. **NB**: if you are requesting more than 50 titles at once (MediaWiki limitation for single request), Infoboxer will do as many queries as necessary to extract them all (it will be like `(titles.count / 50.0).ceil` requests) @param titles [Array<String>] List of page titles to get. @param interwiki [Symbol] Identifier of other wiki, related to current, to fetch pages from. @param processor [Proc] Optional block to preprocess MediaWiktory query. Refer to [MediaWiktory::Actions::Query](http://www.rubydoc.info/gems/mediawiktory/MediaWiktory/Wikipedia/Actions/Query) for its API. Infoboxer assumes that the block returns new instance of `Query`, so be careful while using it. @return [Page, Tree::Nodes<Page>] array of parsed pages. Notes: * if you call `get` with only one title, one page will be returned instead of an array * if some of pages are not in wiki, they will not be returned, therefore resulting array can be shorter than titles array; you can always check `pages.map(&:title)` to see what you've really received; this approach allows you to write absent-minded code like this: ```ruby Infoboxer.wp.get('Argentina', 'Chile', 'Something non-existing'). infobox.fetch('some value') ``` and obtain meaningful results instead of `NoMethodError` or `SomethingNotFound`.
[ "Receive", "list", "of", "parsed", "MediaWiki", "pages", "for", "list", "of", "titles", "provided", ".", "All", "pages", "are", "received", "with", "single", "query", "to", "MediaWiki", "API", "." ]
17038b385dbd2ee6e8e8b3744d0c908ef9abdd38
https://github.com/molybdenum-99/infoboxer/blob/17038b385dbd2ee6e8e8b3744d0c908ef9abdd38/lib/infoboxer/media_wiki.rb#L128-L133
1,519
molybdenum-99/infoboxer
lib/infoboxer/media_wiki.rb
Infoboxer.MediaWiki.category
def category(title, limit: 'max', &processor) title = normalize_category_title(title) list(@api.query.generator(:categorymembers).title(title), limit, &processor) end
ruby
def category(title, limit: 'max', &processor) title = normalize_category_title(title) list(@api.query.generator(:categorymembers).title(title), limit, &processor) end
[ "def", "category", "(", "title", ",", "limit", ":", "'max'", ",", "&", "processor", ")", "title", "=", "normalize_category_title", "(", "title", ")", "list", "(", "@api", ".", "query", ".", "generator", "(", ":categorymembers", ")", ".", "title", "(", "title", ")", ",", "limit", ",", "processor", ")", "end" ]
Receive list of parsed MediaWiki pages from specified category. @param title [String] Category title. You can use namespaceless title (like `"Countries in South America"`), title with namespace (like `"Category:Countries in South America"`) or title with local namespace (like `"Catégorie:Argentine"` for French Wikipedia) @param limit [Integer, "max"] @param processor [Proc] Optional block to preprocess MediaWiktory query. Refer to [MediaWiktory::Actions::Query](http://www.rubydoc.info/gems/mediawiktory/MediaWiktory/Wikipedia/Actions/Query) for its API. Infoboxer assumes that the block returns new instance of `Query`, so be careful while using it. @return [Tree::Nodes<Page>] array of parsed pages.
[ "Receive", "list", "of", "parsed", "MediaWiki", "pages", "from", "specified", "category", "." ]
17038b385dbd2ee6e8e8b3744d0c908ef9abdd38
https://github.com/molybdenum-99/infoboxer/blob/17038b385dbd2ee6e8e8b3744d0c908ef9abdd38/lib/infoboxer/media_wiki.rb#L176-L180
1,520
socketry/lightio
lib/lightio/core/beam.rb
LightIO::Core.Beam.join
def join(limit=nil) # try directly get result if !alive? || limit.nil? || limit <= 0 # call value to raise error value return self end # return to current beam if beam done within time limit origin_parent = parent self.parent = Beam.current # set a transfer back timer timer = LightIO::Watchers::Timer.new(limit) timer.set_callback do if alive? caller_beam = parent # resume to origin parent self.parent = origin_parent caller_beam.transfer end end ioloop.add_timer(timer) ioloop.transfer if alive? nil else check_and_raise_error self end end
ruby
def join(limit=nil) # try directly get result if !alive? || limit.nil? || limit <= 0 # call value to raise error value return self end # return to current beam if beam done within time limit origin_parent = parent self.parent = Beam.current # set a transfer back timer timer = LightIO::Watchers::Timer.new(limit) timer.set_callback do if alive? caller_beam = parent # resume to origin parent self.parent = origin_parent caller_beam.transfer end end ioloop.add_timer(timer) ioloop.transfer if alive? nil else check_and_raise_error self end end
[ "def", "join", "(", "limit", "=", "nil", ")", "# try directly get result", "if", "!", "alive?", "||", "limit", ".", "nil?", "||", "limit", "<=", "0", "# call value to raise error", "value", "return", "self", "end", "# return to current beam if beam done within time limit", "origin_parent", "=", "parent", "self", ".", "parent", "=", "Beam", ".", "current", "# set a transfer back timer", "timer", "=", "LightIO", "::", "Watchers", "::", "Timer", ".", "new", "(", "limit", ")", "timer", ".", "set_callback", "do", "if", "alive?", "caller_beam", "=", "parent", "# resume to origin parent", "self", ".", "parent", "=", "origin_parent", "caller_beam", ".", "transfer", "end", "end", "ioloop", ".", "add_timer", "(", "timer", ")", "ioloop", ".", "transfer", "if", "alive?", "nil", "else", "check_and_raise_error", "self", "end", "end" ]
Block and wait beam dead @param [Numeric] limit wait limit seconds if limit > 0, return nil if beam still alive, else return beam self @return [Beam, nil]
[ "Block", "and", "wait", "beam", "dead" ]
dd99c751a003d68234dd5ce1e3ecf1b7530b98b4
https://github.com/socketry/lightio/blob/dd99c751a003d68234dd5ce1e3ecf1b7530b98b4/lib/lightio/core/beam.rb#L83-L113
1,521
socketry/lightio
lib/lightio/core/beam.rb
LightIO::Core.Beam.raise
def raise(error, message=nil, backtrace=nil) unless error.is_a?(BeamError) message ||= error.respond_to?(:message) ? error.message : nil backtrace ||= error.respond_to?(:backtrace) ? error.backtrace : nil super(error, message, backtrace) end self.parent = error.parent if error.parent if Beam.current == self raise(error.error, message, backtrace) else @error ||= error end end
ruby
def raise(error, message=nil, backtrace=nil) unless error.is_a?(BeamError) message ||= error.respond_to?(:message) ? error.message : nil backtrace ||= error.respond_to?(:backtrace) ? error.backtrace : nil super(error, message, backtrace) end self.parent = error.parent if error.parent if Beam.current == self raise(error.error, message, backtrace) else @error ||= error end end
[ "def", "raise", "(", "error", ",", "message", "=", "nil", ",", "backtrace", "=", "nil", ")", "unless", "error", ".", "is_a?", "(", "BeamError", ")", "message", "||=", "error", ".", "respond_to?", "(", ":message", ")", "?", "error", ".", "message", ":", "nil", "backtrace", "||=", "error", ".", "respond_to?", "(", ":backtrace", ")", "?", "error", ".", "backtrace", ":", "nil", "super", "(", "error", ",", "message", ",", "backtrace", ")", "end", "self", ".", "parent", "=", "error", ".", "parent", "if", "error", ".", "parent", "if", "Beam", ".", "current", "==", "self", "raise", "(", "error", ".", "error", ",", "message", ",", "backtrace", ")", "else", "@error", "||=", "error", "end", "end" ]
Fiber not provide raise method, so we have to simulate one @param [BeamError] error currently only support raise BeamError
[ "Fiber", "not", "provide", "raise", "method", "so", "we", "have", "to", "simulate", "one" ]
dd99c751a003d68234dd5ce1e3ecf1b7530b98b4
https://github.com/socketry/lightio/blob/dd99c751a003d68234dd5ce1e3ecf1b7530b98b4/lib/lightio/core/beam.rb#L126-L138
1,522
socketry/lightio
lib/lightio/wrap.rb
LightIO::Wrap.IOWrapper.wait_nonblock
def wait_nonblock(method, *args) loop do result = __send__(method, *args, exception: false) case result when :wait_readable io_watcher.wait_readable when :wait_writable io_watcher.wait_writable else return result end end end
ruby
def wait_nonblock(method, *args) loop do result = __send__(method, *args, exception: false) case result when :wait_readable io_watcher.wait_readable when :wait_writable io_watcher.wait_writable else return result end end end
[ "def", "wait_nonblock", "(", "method", ",", "*", "args", ")", "loop", "do", "result", "=", "__send__", "(", "method", ",", "args", ",", "exception", ":", "false", ")", "case", "result", "when", ":wait_readable", "io_watcher", ".", "wait_readable", "when", ":wait_writable", "io_watcher", ".", "wait_writable", "else", "return", "result", "end", "end", "end" ]
wait io nonblock method @param [Symbol] method method name, example: wait_nonblock @param [args] args arguments pass to method
[ "wait", "io", "nonblock", "method" ]
dd99c751a003d68234dd5ce1e3ecf1b7530b98b4
https://github.com/socketry/lightio/blob/dd99c751a003d68234dd5ce1e3ecf1b7530b98b4/lib/lightio/wrap.rb#L37-L49
1,523
sosedoff/app-config
lib/app-config/processor.rb
AppConfig.Processor.process_array
def process_array(value) value.split("\n").map { |s| s.to_s.strip }.compact.select { |s| !s.empty? } end
ruby
def process_array(value) value.split("\n").map { |s| s.to_s.strip }.compact.select { |s| !s.empty? } end
[ "def", "process_array", "(", "value", ")", "value", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "s", "|", "s", ".", "to_s", ".", "strip", "}", ".", "compact", ".", "select", "{", "|", "s", "|", "!", "s", ".", "empty?", "}", "end" ]
Process array of strings
[ "Process", "array", "of", "strings" ]
3349f64539b8896da226060ca7263f929173b1e0
https://github.com/sosedoff/app-config/blob/3349f64539b8896da226060ca7263f929173b1e0/lib/app-config/processor.rb#L9-L11
1,524
sosedoff/app-config
lib/app-config/processor.rb
AppConfig.Processor.process
def process(data, type) raise InvalidType, 'Type is invalid!' unless FORMATS.include?(type) send("process_#{type}".to_sym, data.to_s) end
ruby
def process(data, type) raise InvalidType, 'Type is invalid!' unless FORMATS.include?(type) send("process_#{type}".to_sym, data.to_s) end
[ "def", "process", "(", "data", ",", "type", ")", "raise", "InvalidType", ",", "'Type is invalid!'", "unless", "FORMATS", ".", "include?", "(", "type", ")", "send", "(", "\"process_#{type}\"", ".", "to_sym", ",", "data", ".", "to_s", ")", "end" ]
Process data value for the format
[ "Process", "data", "value", "for", "the", "format" ]
3349f64539b8896da226060ca7263f929173b1e0
https://github.com/sosedoff/app-config/blob/3349f64539b8896da226060ca7263f929173b1e0/lib/app-config/processor.rb#L33-L36
1,525
StemboltHQ/solidus-adyen
lib/solidus_adyen/account_locator.rb
SolidusAdyen.AccountLocator.by_reference
def by_reference(psp_reference) code = Spree::Store. joins(orders: :payments). find_by(spree_payments: { response_code: psp_reference }). try!(:code) by_store_code(code) end
ruby
def by_reference(psp_reference) code = Spree::Store. joins(orders: :payments). find_by(spree_payments: { response_code: psp_reference }). try!(:code) by_store_code(code) end
[ "def", "by_reference", "(", "psp_reference", ")", "code", "=", "Spree", "::", "Store", ".", "joins", "(", "orders", ":", ":payments", ")", ".", "find_by", "(", "spree_payments", ":", "{", "response_code", ":", "psp_reference", "}", ")", ".", "try!", "(", ":code", ")", "by_store_code", "(", "code", ")", "end" ]
Creates a new merchant account locator. @param store_account_map [Hash] a hash mapping store codes to merchant accounts @param default_account [String] the default merchant account to use Tries to find a store that has a payment with the given psp reference. If one exists, returns the merchant account for that store. Otherwise, returns the default merchant acount. @param psp_reference [String] the psp reference for the payment @return merchant account [String] the name of the merchant account
[ "Creates", "a", "new", "merchant", "account", "locator", "." ]
68dd710b0a23435eedc3cc0b4b0ec5b45aa37180
https://github.com/StemboltHQ/solidus-adyen/blob/68dd710b0a23435eedc3cc0b4b0ec5b45aa37180/lib/solidus_adyen/account_locator.rb#L28-L35
1,526
robertwahler/win32-autogui
lib/win32/autogui/window.rb
Autogui.Window.close
def close(options={}) PostMessage(handle, WM_SYSCOMMAND, SC_CLOSE, 0) wait_for_close(options) if (options[:wait_for_close] == true) end
ruby
def close(options={}) PostMessage(handle, WM_SYSCOMMAND, SC_CLOSE, 0) wait_for_close(options) if (options[:wait_for_close] == true) end
[ "def", "close", "(", "options", "=", "{", "}", ")", "PostMessage", "(", "handle", ",", "WM_SYSCOMMAND", ",", "SC_CLOSE", ",", "0", ")", "wait_for_close", "(", "options", ")", "if", "(", "options", "[", ":wait_for_close", "]", "==", "true", ")", "end" ]
PostMessage SC_CLOSE and optionally wait for the window to close @param [Hash] options @option options [Boolean] :wait_for_close (true) sleep while waiting for timeout or close @option options [Boolean] :timeout (5) wait_for_close timeout in seconds
[ "PostMessage", "SC_CLOSE", "and", "optionally", "wait", "for", "the", "window", "to", "close" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/window.rb#L116-L119
1,527
robertwahler/win32-autogui
lib/win32/autogui/window.rb
Autogui.Window.wait_for_close
def wait_for_close(options={}) seconds = options[:timeout] || 5 timeout(seconds) do begin yield if block_given? sleep 0.05 end until 0 == IsWindow(handle) end end
ruby
def wait_for_close(options={}) seconds = options[:timeout] || 5 timeout(seconds) do begin yield if block_given? sleep 0.05 end until 0 == IsWindow(handle) end end
[ "def", "wait_for_close", "(", "options", "=", "{", "}", ")", "seconds", "=", "options", "[", ":timeout", "]", "||", "5", "timeout", "(", "seconds", ")", "do", "begin", "yield", "if", "block_given?", "sleep", "0.05", "end", "until", "0", "==", "IsWindow", "(", "handle", ")", "end", "end" ]
Wait for the window to close @param [Hash] options @option options [Boolean] :timeout (5) timeout in seconds
[ "Wait", "for", "the", "window", "to", "close" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/window.rb#L126-L134
1,528
robertwahler/win32-autogui
lib/win32/autogui/window.rb
Autogui.Window.set_focus
def set_focus if is_window? # if current process was the last to receive input, we can be sure that # SetForegroundWindow will be allowed. Send the shift key to whatever has # the focus now. This allows IRB to set_focus. keystroke(VK_SHIFT) ret = SetForegroundWindow(handle) logger.warn("SetForegroundWindow failed") if ret == 0 end end
ruby
def set_focus if is_window? # if current process was the last to receive input, we can be sure that # SetForegroundWindow will be allowed. Send the shift key to whatever has # the focus now. This allows IRB to set_focus. keystroke(VK_SHIFT) ret = SetForegroundWindow(handle) logger.warn("SetForegroundWindow failed") if ret == 0 end end
[ "def", "set_focus", "if", "is_window?", "# if current process was the last to receive input, we can be sure that", "# SetForegroundWindow will be allowed. Send the shift key to whatever has", "# the focus now. This allows IRB to set_focus.", "keystroke", "(", "VK_SHIFT", ")", "ret", "=", "SetForegroundWindow", "(", "handle", ")", "logger", ".", "warn", "(", "\"SetForegroundWindow failed\"", ")", "if", "ret", "==", "0", "end", "end" ]
Brings the window into the foreground and activates it. Keyboard input is directed to the window, and various visual cues are changed for the user. A process can set the foreground window only if one of the following conditions is true: * The process is the foreground process. * The process was started by the foreground process. * The process received the last input event. * There is no foreground process. * The foreground process is being debugged. * The foreground is not locked. * The foreground lock time-out has expired. * No menus are active. @return [Number] nonzero number if sucessful, nil or zero if failed
[ "Brings", "the", "window", "into", "the", "foreground", "and", "activates", "it", ".", "Keyboard", "input", "is", "directed", "to", "the", "window", "and", "various", "visual", "cues", "are", "changed", "for", "the", "user", "." ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/window.rb#L203-L212
1,529
robertwahler/win32-autogui
lib/win32/autogui/window.rb
Autogui.Window.combined_text
def combined_text return unless is_window? t = [] t << text unless text == '' children.each do |w| t << w.combined_text unless w.combined_text == '' end t.join("\n") end
ruby
def combined_text return unless is_window? t = [] t << text unless text == '' children.each do |w| t << w.combined_text unless w.combined_text == '' end t.join("\n") end
[ "def", "combined_text", "return", "unless", "is_window?", "t", "=", "[", "]", "t", "<<", "text", "unless", "text", "==", "''", "children", ".", "each", "do", "|", "w", "|", "t", "<<", "w", ".", "combined_text", "unless", "w", ".", "combined_text", "==", "''", "end", "t", ".", "join", "(", "\"\\n\"", ")", "end" ]
The window text including all child windows joined together with newlines. Faciliates matching text. Text from any given window is limited to 2048 characters @example partial match of the Window's calulator's about dialog copywrite text dialog_about = @calculator.dialog_about dialog_about.title.should == "About Calculator" dialog_about.combined_text.should match(/Microsoft . Calculator/) @return [String] with newlines
[ "The", "window", "text", "including", "all", "child", "windows", "joined", "together", "with", "newlines", ".", "Faciliates", "matching", "text", ".", "Text", "from", "any", "given", "window", "is", "limited", "to", "2048", "characters" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/window.rb#L246-L254
1,530
StemboltHQ/solidus-adyen
app/controllers/spree/adyen_redirect_controller.rb
Spree.AdyenRedirectController.authorise3d
def authorise3d payment = Spree::Adyen::RedirectResponse.find_by(md: params[:MD]).payment payment.request_env = request.env payment_method = payment.payment_method @order = payment.order payment_method.authorize_3d_secure_payment(payment, adyen_3d_params) payment.capture! if payment_method.auto_capture if complete redirect_to_order else redirect_to checkout_state_path(@order.state) end rescue Spree::Core::GatewayError handle_failed_redirect end
ruby
def authorise3d payment = Spree::Adyen::RedirectResponse.find_by(md: params[:MD]).payment payment.request_env = request.env payment_method = payment.payment_method @order = payment.order payment_method.authorize_3d_secure_payment(payment, adyen_3d_params) payment.capture! if payment_method.auto_capture if complete redirect_to_order else redirect_to checkout_state_path(@order.state) end rescue Spree::Core::GatewayError handle_failed_redirect end
[ "def", "authorise3d", "payment", "=", "Spree", "::", "Adyen", "::", "RedirectResponse", ".", "find_by", "(", "md", ":", "params", "[", ":MD", "]", ")", ".", "payment", "payment", ".", "request_env", "=", "request", ".", "env", "payment_method", "=", "payment", ".", "payment_method", "@order", "=", "payment", ".", "order", "payment_method", ".", "authorize_3d_secure_payment", "(", "payment", ",", "adyen_3d_params", ")", "payment", ".", "capture!", "if", "payment_method", ".", "auto_capture", "if", "complete", "redirect_to_order", "else", "redirect_to", "checkout_state_path", "(", "@order", ".", "state", ")", "end", "rescue", "Spree", "::", "Core", "::", "GatewayError", "handle_failed_redirect", "end" ]
This is the entry point after returning from the 3DS page for credit cards that support it. MD is a unique payment session identifier returned by the card issuer.
[ "This", "is", "the", "entry", "point", "after", "returning", "from", "the", "3DS", "page", "for", "credit", "cards", "that", "support", "it", ".", "MD", "is", "a", "unique", "payment", "session", "identifier", "returned", "by", "the", "card", "issuer", "." ]
68dd710b0a23435eedc3cc0b4b0ec5b45aa37180
https://github.com/StemboltHQ/solidus-adyen/blob/68dd710b0a23435eedc3cc0b4b0ec5b45aa37180/app/controllers/spree/adyen_redirect_controller.rb#L27-L44
1,531
StemboltHQ/solidus-adyen
app/controllers/spree/adyen_redirect_controller.rb
Spree.AdyenRedirectController.confirm_order_already_completed
def confirm_order_already_completed if psp_reference payment = @order.payments.find_by!(response_code: psp_reference) else # If no psp_reference is present but the order is complete then the # notification must have completed the order and created the payment. # Therefore select the last Adyen payment. payment = @order.payments.where(source_type: "Spree::Adyen::HppSource").last end payment.source.update(source_params) redirect_to_order end
ruby
def confirm_order_already_completed if psp_reference payment = @order.payments.find_by!(response_code: psp_reference) else # If no psp_reference is present but the order is complete then the # notification must have completed the order and created the payment. # Therefore select the last Adyen payment. payment = @order.payments.where(source_type: "Spree::Adyen::HppSource").last end payment.source.update(source_params) redirect_to_order end
[ "def", "confirm_order_already_completed", "if", "psp_reference", "payment", "=", "@order", ".", "payments", ".", "find_by!", "(", "response_code", ":", "psp_reference", ")", "else", "# If no psp_reference is present but the order is complete then the", "# notification must have completed the order and created the payment.", "# Therefore select the last Adyen payment.", "payment", "=", "@order", ".", "payments", ".", "where", "(", "source_type", ":", "\"Spree::Adyen::HppSource\"", ")", ".", "last", "end", "payment", ".", "source", ".", "update", "(", "source_params", ")", "redirect_to_order", "end" ]
If an authorization notification is received before the redirection the payment is created there. In this case we just need to assign the addition parameters received about the source. We do this because there is a chance that we never get redirected back so we need to make sure we complete the payment and order.
[ "If", "an", "authorization", "notification", "is", "received", "before", "the", "redirection", "the", "payment", "is", "created", "there", ".", "In", "this", "case", "we", "just", "need", "to", "assign", "the", "addition", "parameters", "received", "about", "the", "source", "." ]
68dd710b0a23435eedc3cc0b4b0ec5b45aa37180
https://github.com/StemboltHQ/solidus-adyen/blob/68dd710b0a23435eedc3cc0b4b0ec5b45aa37180/app/controllers/spree/adyen_redirect_controller.rb#L83-L97
1,532
StemboltHQ/solidus-adyen
app/controllers/spree/adyen_redirect_controller.rb
Spree.AdyenRedirectController.restore_session
def restore_session guest_token, payment_method_id = params.fetch(:merchantReturnData).split("|") cookies.permanent.signed[:guest_token] = guest_token @payment_method = Spree::PaymentMethod.find(payment_method_id) @order = Spree::Order.find_by!(number: order_number) end
ruby
def restore_session guest_token, payment_method_id = params.fetch(:merchantReturnData).split("|") cookies.permanent.signed[:guest_token] = guest_token @payment_method = Spree::PaymentMethod.find(payment_method_id) @order = Spree::Order.find_by!(number: order_number) end
[ "def", "restore_session", "guest_token", ",", "payment_method_id", "=", "params", ".", "fetch", "(", ":merchantReturnData", ")", ".", "split", "(", "\"|\"", ")", "cookies", ".", "permanent", ".", "signed", "[", ":guest_token", "]", "=", "guest_token", "@payment_method", "=", "Spree", "::", "PaymentMethod", ".", "find", "(", "payment_method_id", ")", "@order", "=", "Spree", "::", "Order", ".", "find_by!", "(", "number", ":", "order_number", ")", "end" ]
We pass the guest token and payment method id in, pipe seperated in the merchantReturnData parameter so that we can recover the session.
[ "We", "pass", "the", "guest", "token", "and", "payment", "method", "id", "in", "pipe", "seperated", "in", "the", "merchantReturnData", "parameter", "so", "that", "we", "can", "recover", "the", "session", "." ]
68dd710b0a23435eedc3cc0b4b0ec5b45aa37180
https://github.com/StemboltHQ/solidus-adyen/blob/68dd710b0a23435eedc3cc0b4b0ec5b45aa37180/app/controllers/spree/adyen_redirect_controller.rb#L114-L123
1,533
smacgaha/chromedriver-screenshot
lib/chromedriver-screenshot/tile.rb
ChromedriverScreenshot.Tile.get_offset
def get_offset platform = ChromedriverScreenshot::Platforms.platform offset_x = @x - platform.window_x offset_y = @y - platform.window_y [offset_x, offset_y] end
ruby
def get_offset platform = ChromedriverScreenshot::Platforms.platform offset_x = @x - platform.window_x offset_y = @y - platform.window_y [offset_x, offset_y] end
[ "def", "get_offset", "platform", "=", "ChromedriverScreenshot", "::", "Platforms", ".", "platform", "offset_x", "=", "@x", "-", "platform", ".", "window_x", "offset_y", "=", "@y", "-", "platform", ".", "window_y", "[", "offset_x", ",", "offset_y", "]", "end" ]
can't scroll past ends of page, so sometimes position won't be accurate
[ "can", "t", "scroll", "past", "ends", "of", "page", "so", "sometimes", "position", "won", "t", "be", "accurate" ]
0d768ecc325706f9603fc7b62a45995960464b23
https://github.com/smacgaha/chromedriver-screenshot/blob/0d768ecc325706f9603fc7b62a45995960464b23/lib/chromedriver-screenshot/tile.rb#L34-L39
1,534
enzinia/hangouts-chat
lib/hangouts_chat.rb
HangoutsChat.Sender.card
def card(header, sections) payload = { cards: [header: header, sections: sections] } send_request(payload) end
ruby
def card(header, sections) payload = { cards: [header: header, sections: sections] } send_request(payload) end
[ "def", "card", "(", "header", ",", "sections", ")", "payload", "=", "{", "cards", ":", "[", "header", ":", "header", ",", "sections", ":", "sections", "]", "}", "send_request", "(", "payload", ")", "end" ]
Sends Card Message @since 0.0.4 @param header [Hash] card header content @param sections [Array<Hash>] card widgets array @return [Net::HTTPResponse] response object
[ "Sends", "Card", "Message" ]
fea2fccdc2d1142746a88943d5f9c4f6af2af5a8
https://github.com/enzinia/hangouts-chat/blob/fea2fccdc2d1142746a88943d5f9c4f6af2af5a8/lib/hangouts_chat.rb#L32-L35
1,535
enzinia/hangouts-chat
lib/hangouts_chat.rb
HangoutsChat.Sender.send_request
def send_request(payload) response = @http.post payload raise APIError, response unless response.is_a?(Net::HTTPSuccess) response end
ruby
def send_request(payload) response = @http.post payload raise APIError, response unless response.is_a?(Net::HTTPSuccess) response end
[ "def", "send_request", "(", "payload", ")", "response", "=", "@http", ".", "post", "payload", "raise", "APIError", ",", "response", "unless", "response", ".", "is_a?", "(", "Net", "::", "HTTPSuccess", ")", "response", "end" ]
Sends payload and check response @param payload [Hash] data to send by POST @return [Net::HTTPResponse] response object @raise [APIError] if got unsuccessful response
[ "Sends", "payload", "and", "check", "response" ]
fea2fccdc2d1142746a88943d5f9c4f6af2af5a8
https://github.com/enzinia/hangouts-chat/blob/fea2fccdc2d1142746a88943d5f9c4f6af2af5a8/lib/hangouts_chat.rb#L43-L47
1,536
nthj/ignorable
lib/ignorable.rb
Ignorable.ClassMethods.ignore_columns
def ignore_columns(*columns) self.ignored_columns ||= [] self.ignored_columns += columns.map(&:to_s) reset_column_information descendants.each(&:reset_column_information) self.ignored_columns.tap(&:uniq!) end
ruby
def ignore_columns(*columns) self.ignored_columns ||= [] self.ignored_columns += columns.map(&:to_s) reset_column_information descendants.each(&:reset_column_information) self.ignored_columns.tap(&:uniq!) end
[ "def", "ignore_columns", "(", "*", "columns", ")", "self", ".", "ignored_columns", "||=", "[", "]", "self", ".", "ignored_columns", "+=", "columns", ".", "map", "(", ":to_s", ")", "reset_column_information", "descendants", ".", "each", "(", ":reset_column_information", ")", "self", ".", "ignored_columns", ".", "tap", "(", ":uniq!", ")", "end" ]
Prevent Rails from loading a table column. Useful for legacy database schemas with problematic column names, like 'class' or 'attributes'. class Topic < ActiveRecord::Base ignore_columns :attributes, :class end Topic.new.respond_to?(:attributes) => false
[ "Prevent", "Rails", "from", "loading", "a", "table", "column", ".", "Useful", "for", "legacy", "database", "schemas", "with", "problematic", "column", "names", "like", "class", "or", "attributes", "." ]
1fa6dada7ae0e2c4d4ae5c78f62234a2a1cae94e
https://github.com/nthj/ignorable/blob/1fa6dada7ae0e2c4d4ae5c78f62234a2a1cae94e/lib/ignorable.rb#L29-L35
1,537
robertwahler/win32-autogui
lib/win32/autogui/input.rb
Autogui.Input.keystroke
def keystroke(*keys) return if keys.empty? keybd_event keys.first, 0, KEYBD_EVENT_KEYDOWN, 0 sleep KEYBD_KEYDELAY keystroke *keys[1..-1] sleep KEYBD_KEYDELAY keybd_event keys.first, 0, KEYBD_EVENT_KEYUP, 0 end
ruby
def keystroke(*keys) return if keys.empty? keybd_event keys.first, 0, KEYBD_EVENT_KEYDOWN, 0 sleep KEYBD_KEYDELAY keystroke *keys[1..-1] sleep KEYBD_KEYDELAY keybd_event keys.first, 0, KEYBD_EVENT_KEYUP, 0 end
[ "def", "keystroke", "(", "*", "keys", ")", "return", "if", "keys", ".", "empty?", "keybd_event", "keys", ".", "first", ",", "0", ",", "KEYBD_EVENT_KEYDOWN", ",", "0", "sleep", "KEYBD_KEYDELAY", "keystroke", "keys", "[", "1", "..", "-", "1", "]", "sleep", "KEYBD_KEYDELAY", "keybd_event", "keys", ".", "first", ",", "0", ",", "KEYBD_EVENT_KEYUP", ",", "0", "end" ]
Send keystroke to the focused window, keystrokes are virtual keycodes @example send 2+2<CR> keystroke(VK_2, VK_ADD, VK_2, VK_RETURN)
[ "Send", "keystroke", "to", "the", "focused", "window", "keystrokes", "are", "virtual", "keycodes" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/input.rb#L156-L164
1,538
robertwahler/win32-autogui
lib/win32/autogui/input.rb
Autogui.Input.char_to_virtual_keycode
def char_to_virtual_keycode(char) unless char.size == 1 raise "virtual keycode conversion is for single characters only" end code = char.unpack('U')[0] case char when '0'..'9' [code - ?0.ord + 0x30] when 'A'..'Z' [VK_SHIFT, code] when 'a'..'z' [code - ?a.ord + ?A.ord] when ' ' [code] when '+' [VK_ADD] when '=' [VK_OEM_PLUS] when ',' [VK_OEM_COMMA] when '.' [VK_OEM_PERIOD] when '-' [VK_OEM_MINUS] when '_' [VK_SHIFT, VK_OEM_MINUS] when ';' [VK_OEM_1] when ':' [VK_SHIFT, VK_OEM_1] when '/' [VK_OEM_2] when '?' [VK_SHIFT, VK_OEM_2] when '`' [VK_OEM_3] when '~' [VK_SHIFT, VK_OEM_3] when '[' [VK_OEM_4] when '{' [VK_SHIFT, VK_OEM_4] when '\\' [VK_OEM_5] when '|' [VK_SHIFT, VK_OEM_5] when ']' [VK_OEM_6] when '}' [VK_SHIFT, VK_OEM_6] when "'" [VK_OEM_7] when '"' [VK_SHIFT, VK_OEM_7] when '!' [VK_SHIFT, VK_1] when '@' [VK_SHIFT, VK_2] when '#' [VK_SHIFT, VK_3] when '$' [VK_SHIFT, VK_4] when '%' [VK_SHIFT, VK_5] when '^' [VK_SHIFT, VK_6] when '&' [VK_SHIFT, VK_7] when '*' [VK_SHIFT, VK_8] when '(' [VK_SHIFT, VK_9] when ')' [VK_SHIFT, VK_0] when "\n" [VK_RETURN] else raise "No conversion exists for character #{char}" end end
ruby
def char_to_virtual_keycode(char) unless char.size == 1 raise "virtual keycode conversion is for single characters only" end code = char.unpack('U')[0] case char when '0'..'9' [code - ?0.ord + 0x30] when 'A'..'Z' [VK_SHIFT, code] when 'a'..'z' [code - ?a.ord + ?A.ord] when ' ' [code] when '+' [VK_ADD] when '=' [VK_OEM_PLUS] when ',' [VK_OEM_COMMA] when '.' [VK_OEM_PERIOD] when '-' [VK_OEM_MINUS] when '_' [VK_SHIFT, VK_OEM_MINUS] when ';' [VK_OEM_1] when ':' [VK_SHIFT, VK_OEM_1] when '/' [VK_OEM_2] when '?' [VK_SHIFT, VK_OEM_2] when '`' [VK_OEM_3] when '~' [VK_SHIFT, VK_OEM_3] when '[' [VK_OEM_4] when '{' [VK_SHIFT, VK_OEM_4] when '\\' [VK_OEM_5] when '|' [VK_SHIFT, VK_OEM_5] when ']' [VK_OEM_6] when '}' [VK_SHIFT, VK_OEM_6] when "'" [VK_OEM_7] when '"' [VK_SHIFT, VK_OEM_7] when '!' [VK_SHIFT, VK_1] when '@' [VK_SHIFT, VK_2] when '#' [VK_SHIFT, VK_3] when '$' [VK_SHIFT, VK_4] when '%' [VK_SHIFT, VK_5] when '^' [VK_SHIFT, VK_6] when '&' [VK_SHIFT, VK_7] when '*' [VK_SHIFT, VK_8] when '(' [VK_SHIFT, VK_9] when ')' [VK_SHIFT, VK_0] when "\n" [VK_RETURN] else raise "No conversion exists for character #{char}" end end
[ "def", "char_to_virtual_keycode", "(", "char", ")", "unless", "char", ".", "size", "==", "1", "raise", "\"virtual keycode conversion is for single characters only\"", "end", "code", "=", "char", ".", "unpack", "(", "'U'", ")", "[", "0", "]", "case", "char", "when", "'0'", "..", "'9'", "[", "code", "-", "?0", ".", "ord", "+", "0x30", "]", "when", "'A'", "..", "'Z'", "[", "VK_SHIFT", ",", "code", "]", "when", "'a'", "..", "'z'", "[", "code", "-", "?a", ".", "ord", "+", "?A", ".", "ord", "]", "when", "' '", "[", "code", "]", "when", "'+'", "[", "VK_ADD", "]", "when", "'='", "[", "VK_OEM_PLUS", "]", "when", "','", "[", "VK_OEM_COMMA", "]", "when", "'.'", "[", "VK_OEM_PERIOD", "]", "when", "'-'", "[", "VK_OEM_MINUS", "]", "when", "'_'", "[", "VK_SHIFT", ",", "VK_OEM_MINUS", "]", "when", "';'", "[", "VK_OEM_1", "]", "when", "':'", "[", "VK_SHIFT", ",", "VK_OEM_1", "]", "when", "'/'", "[", "VK_OEM_2", "]", "when", "'?'", "[", "VK_SHIFT", ",", "VK_OEM_2", "]", "when", "'`'", "[", "VK_OEM_3", "]", "when", "'~'", "[", "VK_SHIFT", ",", "VK_OEM_3", "]", "when", "'['", "[", "VK_OEM_4", "]", "when", "'{'", "[", "VK_SHIFT", ",", "VK_OEM_4", "]", "when", "'\\\\'", "[", "VK_OEM_5", "]", "when", "'|'", "[", "VK_SHIFT", ",", "VK_OEM_5", "]", "when", "']'", "[", "VK_OEM_6", "]", "when", "'}'", "[", "VK_SHIFT", ",", "VK_OEM_6", "]", "when", "\"'\"", "[", "VK_OEM_7", "]", "when", "'\"'", "[", "VK_SHIFT", ",", "VK_OEM_7", "]", "when", "'!'", "[", "VK_SHIFT", ",", "VK_1", "]", "when", "'@'", "[", "VK_SHIFT", ",", "VK_2", "]", "when", "'#'", "[", "VK_SHIFT", ",", "VK_3", "]", "when", "'$'", "[", "VK_SHIFT", ",", "VK_4", "]", "when", "'%'", "[", "VK_SHIFT", ",", "VK_5", "]", "when", "'^'", "[", "VK_SHIFT", ",", "VK_6", "]", "when", "'&'", "[", "VK_SHIFT", ",", "VK_7", "]", "when", "'*'", "[", "VK_SHIFT", ",", "VK_8", "]", "when", "'('", "[", "VK_SHIFT", ",", "VK_9", "]", "when", "')'", "[", "VK_SHIFT", ",", "VK_0", "]", "when", "\"\\n\"", "[", "VK_RETURN", "]", "else", "raise", "\"No conversion exists for character #{char}\"", "end", "end" ]
convert a single character to a virtual keycode @param [Char] char is the character to convert @return [Array] of virtual keycodes
[ "convert", "a", "single", "character", "to", "a", "virtual", "keycode" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/input.rb#L191-L275
1,539
TimPetricola/Credy
lib/credy/rules.rb
Credy.Rules.all
def all rules = [] raw.each do |type, details| # Add general rules Array(details['prefix']).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type }) end # Process each country Array(details['countries']).each do |country, prefixes| # Add a rule for each prefix Array(prefixes).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type, country: country, }) end end end # Sort by prefix length rules.sort { |x, y| y[:prefix].length <=> x[:prefix].length } end
ruby
def all rules = [] raw.each do |type, details| # Add general rules Array(details['prefix']).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type }) end # Process each country Array(details['countries']).each do |country, prefixes| # Add a rule for each prefix Array(prefixes).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type, country: country, }) end end end # Sort by prefix length rules.sort { |x, y| y[:prefix].length <=> x[:prefix].length } end
[ "def", "all", "rules", "=", "[", "]", "raw", ".", "each", "do", "|", "type", ",", "details", "|", "# Add general rules", "Array", "(", "details", "[", "'prefix'", "]", ")", ".", "each", "do", "|", "prefix", "|", "rules", ".", "push", "(", "{", "prefix", ":", "prefix", ".", "to_s", ",", "length", ":", "details", "[", "'length'", "]", ",", "type", ":", "type", "}", ")", "end", "# Process each country", "Array", "(", "details", "[", "'countries'", "]", ")", ".", "each", "do", "|", "country", ",", "prefixes", "|", "# Add a rule for each prefix", "Array", "(", "prefixes", ")", ".", "each", "do", "|", "prefix", "|", "rules", ".", "push", "(", "{", "prefix", ":", "prefix", ".", "to_s", ",", "length", ":", "details", "[", "'length'", "]", ",", "type", ":", "type", ",", "country", ":", "country", ",", "}", ")", "end", "end", "end", "# Sort by prefix length", "rules", ".", "sort", "{", "|", "x", ",", "y", "|", "y", "[", ":prefix", "]", ".", "length", "<=>", "x", "[", ":prefix", "]", ".", "length", "}", "end" ]
Change hash format to process rules
[ "Change", "hash", "format", "to", "process", "rules" ]
c1ba2d51da95b8885d6c446736b5455b6ee5d200
https://github.com/TimPetricola/Credy/blob/c1ba2d51da95b8885d6c446736b5455b6ee5d200/lib/credy/rules.rb#L13-L43
1,540
TimPetricola/Credy
lib/credy/rules.rb
Credy.Rules.filter
def filter(filters = {}) all.select do |rule| [:country, :type].each do |condition| break false if filters[condition] && filters[condition] != rule[condition] true end end end
ruby
def filter(filters = {}) all.select do |rule| [:country, :type].each do |condition| break false if filters[condition] && filters[condition] != rule[condition] true end end end
[ "def", "filter", "(", "filters", "=", "{", "}", ")", "all", ".", "select", "do", "|", "rule", "|", "[", ":country", ",", ":type", "]", ".", "each", "do", "|", "condition", "|", "break", "false", "if", "filters", "[", "condition", "]", "&&", "filters", "[", "condition", "]", "!=", "rule", "[", "condition", "]", "true", "end", "end", "end" ]
Returns rules according to given filters
[ "Returns", "rules", "according", "to", "given", "filters" ]
c1ba2d51da95b8885d6c446736b5455b6ee5d200
https://github.com/TimPetricola/Credy/blob/c1ba2d51da95b8885d6c446736b5455b6ee5d200/lib/credy/rules.rb#L46-L53
1,541
TimPetricola/Credy
lib/credy.rb
Credy.CreditCard.generate
def generate(options = {}) rule = find_rule(options) || return number = generate_from_rule(rule) { number: number, type: rule[:type], country: rule[:country] } end
ruby
def generate(options = {}) rule = find_rule(options) || return number = generate_from_rule(rule) { number: number, type: rule[:type], country: rule[:country] } end
[ "def", "generate", "(", "options", "=", "{", "}", ")", "rule", "=", "find_rule", "(", "options", ")", "||", "return", "number", "=", "generate_from_rule", "(", "rule", ")", "{", "number", ":", "number", ",", "type", ":", "rule", "[", ":type", "]", ",", "country", ":", "rule", "[", ":country", "]", "}", "end" ]
Generate a credit card number
[ "Generate", "a", "credit", "card", "number" ]
c1ba2d51da95b8885d6c446736b5455b6ee5d200
https://github.com/TimPetricola/Credy/blob/c1ba2d51da95b8885d6c446736b5455b6ee5d200/lib/credy.rb#L15-L24
1,542
TimPetricola/Credy
lib/credy.rb
Credy.CreditCard.infos
def infos(number) rules = Rules.all.select do |rule| valid = true # Check number of digits lengths = rule[:length].is_a?(Array) ? rule[:length] : [rule[:length]] valid = false unless lengths.include? number.length # Check prefix valid = false unless !(number =~ Regexp.new("^#{rule[:prefix]}")).nil? valid end if rules rules[0] else nil end end
ruby
def infos(number) rules = Rules.all.select do |rule| valid = true # Check number of digits lengths = rule[:length].is_a?(Array) ? rule[:length] : [rule[:length]] valid = false unless lengths.include? number.length # Check prefix valid = false unless !(number =~ Regexp.new("^#{rule[:prefix]}")).nil? valid end if rules rules[0] else nil end end
[ "def", "infos", "(", "number", ")", "rules", "=", "Rules", ".", "all", ".", "select", "do", "|", "rule", "|", "valid", "=", "true", "# Check number of digits", "lengths", "=", "rule", "[", ":length", "]", ".", "is_a?", "(", "Array", ")", "?", "rule", "[", ":length", "]", ":", "[", "rule", "[", ":length", "]", "]", "valid", "=", "false", "unless", "lengths", ".", "include?", "number", ".", "length", "# Check prefix", "valid", "=", "false", "unless", "!", "(", "number", "=~", "Regexp", ".", "new", "(", "\"^#{rule[:prefix]}\"", ")", ")", ".", "nil?", "valid", "end", "if", "rules", "rules", "[", "0", "]", "else", "nil", "end", "end" ]
Returns information about a number
[ "Returns", "information", "about", "a", "number" ]
c1ba2d51da95b8885d6c446736b5455b6ee5d200
https://github.com/TimPetricola/Credy/blob/c1ba2d51da95b8885d6c446736b5455b6ee5d200/lib/credy.rb#L27-L45
1,543
TimPetricola/Credy
lib/credy.rb
Credy.CreditCard.validate
def validate(number) criterii = {} criterii[:luhn] = Check.luhn number criterii[:type] = !!infos(number) valid = criterii.all? { |_, v| v == true } { valid: valid, details: criterii } end
ruby
def validate(number) criterii = {} criterii[:luhn] = Check.luhn number criterii[:type] = !!infos(number) valid = criterii.all? { |_, v| v == true } { valid: valid, details: criterii } end
[ "def", "validate", "(", "number", ")", "criterii", "=", "{", "}", "criterii", "[", ":luhn", "]", "=", "Check", ".", "luhn", "number", "criterii", "[", ":type", "]", "=", "!", "!", "infos", "(", "number", ")", "valid", "=", "criterii", ".", "all?", "{", "|", "_", ",", "v", "|", "v", "==", "true", "}", "{", "valid", ":", "valid", ",", "details", ":", "criterii", "}", "end" ]
Validates a number
[ "Validates", "a", "number" ]
c1ba2d51da95b8885d6c446736b5455b6ee5d200
https://github.com/TimPetricola/Credy/blob/c1ba2d51da95b8885d6c446736b5455b6ee5d200/lib/credy.rb#L48-L59
1,544
robertwahler/win32-autogui
lib/win32/autogui/application.rb
Autogui.Clipboard.text=
def text=(str) data = str.nil? ? "" : str.dup Win32::Clipboard.set_data(data) end
ruby
def text=(str) data = str.nil? ? "" : str.dup Win32::Clipboard.set_data(data) end
[ "def", "text", "=", "(", "str", ")", "data", "=", "str", ".", "nil?", "?", "\"\"", ":", "str", ".", "dup", "Win32", "::", "Clipboard", ".", "set_data", "(", "data", ")", "end" ]
Clipboard text setter @param [String] str text to load onto the clipboard
[ "Clipboard", "text", "setter" ]
f36dc7ed9d7389893b0960b2c5740338f0d38117
https://github.com/robertwahler/win32-autogui/blob/f36dc7ed9d7389893b0960b2c5740338f0d38117/lib/win32/autogui/application.rb#L26-L29
1,545
jonahb/akismet
lib/akismet/client.rb
Akismet.Client.spam
def spam(user_ip, user_agent, params = {}) response = invoke_comment_method('submit-spam', user_ip, user_agent, params) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end
ruby
def spam(user_ip, user_agent, params = {}) response = invoke_comment_method('submit-spam', user_ip, user_agent, params) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end
[ "def", "spam", "(", "user_ip", ",", "user_agent", ",", "params", "=", "{", "}", ")", "response", "=", "invoke_comment_method", "(", "'submit-spam'", ",", "user_ip", ",", "user_agent", ",", "params", ")", "unless", "response", ".", "body", "==", "'Thanks for making the web a better place.'", "raise_with_response", "response", "end", "end" ]
Submits a comment that has been identified as spam. @!macro akismet_method @return [void]
[ "Submits", "a", "comment", "that", "has", "been", "identified", "as", "spam", "." ]
b03f7fd58181d962c2ac842b16e67752e7c7f023
https://github.com/jonahb/akismet/blob/b03f7fd58181d962c2ac842b16e67752e7c7f023/lib/akismet/client.rb#L238-L247
1,546
nickcharlton/boxes
lib/boxes/builder.rb
Boxes.Builder.run
def run # rubocop:disable Metrics/AbcSize, Metrics/MethodLength original_directory = FileUtils.pwd box_name = '' # render the template rendered_template = template.render(name: name, provider: provider, scripts: scripts) # write the template to a file File.open(Boxes.config.working_dir + "#{build_name}.json", 'w') do |f| f.puts rendered_template end # set the environment vars Boxes.config.environment_vars.each do |e| e.each do |k, v| ENV[k] = v.to_s end end # execute the packer command FileUtils.chdir(Boxes.config.working_dir) cmd = "packer build #{build_name}.json" status = Subprocess.run(cmd) do |stdout, stderr, _thread| puts stdout unless stdout.nil? puts stderr unless stderr.nil? # catch the name of the artifact if stdout =~ /\.box/ box_name = stdout.gsub(/[a-zA-Z0-9:\-_]*?\.box/).first end end if status.exitstatus == 0 FileUtils.mv(Boxes.config.working_dir + box_name, "#{original_directory}/#{name}.box") else fail BuildRunError, 'The build didn\'t complete successfully. Check the logs.' end end
ruby
def run # rubocop:disable Metrics/AbcSize, Metrics/MethodLength original_directory = FileUtils.pwd box_name = '' # render the template rendered_template = template.render(name: name, provider: provider, scripts: scripts) # write the template to a file File.open(Boxes.config.working_dir + "#{build_name}.json", 'w') do |f| f.puts rendered_template end # set the environment vars Boxes.config.environment_vars.each do |e| e.each do |k, v| ENV[k] = v.to_s end end # execute the packer command FileUtils.chdir(Boxes.config.working_dir) cmd = "packer build #{build_name}.json" status = Subprocess.run(cmd) do |stdout, stderr, _thread| puts stdout unless stdout.nil? puts stderr unless stderr.nil? # catch the name of the artifact if stdout =~ /\.box/ box_name = stdout.gsub(/[a-zA-Z0-9:\-_]*?\.box/).first end end if status.exitstatus == 0 FileUtils.mv(Boxes.config.working_dir + box_name, "#{original_directory}/#{name}.box") else fail BuildRunError, 'The build didn\'t complete successfully. Check the logs.' end end
[ "def", "run", "# rubocop:disable Metrics/AbcSize, Metrics/MethodLength", "original_directory", "=", "FileUtils", ".", "pwd", "box_name", "=", "''", "# render the template", "rendered_template", "=", "template", ".", "render", "(", "name", ":", "name", ",", "provider", ":", "provider", ",", "scripts", ":", "scripts", ")", "# write the template to a file", "File", ".", "open", "(", "Boxes", ".", "config", ".", "working_dir", "+", "\"#{build_name}.json\"", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "puts", "rendered_template", "end", "# set the environment vars", "Boxes", ".", "config", ".", "environment_vars", ".", "each", "do", "|", "e", "|", "e", ".", "each", "do", "|", "k", ",", "v", "|", "ENV", "[", "k", "]", "=", "v", ".", "to_s", "end", "end", "# execute the packer command", "FileUtils", ".", "chdir", "(", "Boxes", ".", "config", ".", "working_dir", ")", "cmd", "=", "\"packer build #{build_name}.json\"", "status", "=", "Subprocess", ".", "run", "(", "cmd", ")", "do", "|", "stdout", ",", "stderr", ",", "_thread", "|", "puts", "stdout", "unless", "stdout", ".", "nil?", "puts", "stderr", "unless", "stderr", ".", "nil?", "# catch the name of the artifact", "if", "stdout", "=~", "/", "\\.", "/", "box_name", "=", "stdout", ".", "gsub", "(", "/", "\\-", "\\.", "/", ")", ".", "first", "end", "end", "if", "status", ".", "exitstatus", "==", "0", "FileUtils", ".", "mv", "(", "Boxes", ".", "config", ".", "working_dir", "+", "box_name", ",", "\"#{original_directory}/#{name}.box\"", ")", "else", "fail", "BuildRunError", ",", "'The build didn\\'t complete successfully. Check the logs.'", "end", "end" ]
Initialise a new build. @param env [Boxes::Environment] environment to operate in. @param args [Hash] @param template [String] the name of the template. @param scripts [Array] scripts to include in the build. Run the build.
[ "Initialise", "a", "new", "build", "." ]
d5558d6f2c4f98c6e453f8b960f28c7540433936
https://github.com/nickcharlton/boxes/blob/d5558d6f2c4f98c6e453f8b960f28c7540433936/lib/boxes/builder.rb#L30-L71
1,547
mroth/emoji_data.rb
lib/emoji_data/emoji_char.rb
EmojiData.EmojiChar.render
def render(opts = {}) options = {variant_encoding: true}.merge(opts) #decide whether to use the normal unified ID or the variant for encoding to str target = (self.variant? && options[:variant_encoding]) ? self.variant : @unified EmojiChar::unified_to_char(target) end
ruby
def render(opts = {}) options = {variant_encoding: true}.merge(opts) #decide whether to use the normal unified ID or the variant for encoding to str target = (self.variant? && options[:variant_encoding]) ? self.variant : @unified EmojiChar::unified_to_char(target) end
[ "def", "render", "(", "opts", "=", "{", "}", ")", "options", "=", "{", "variant_encoding", ":", "true", "}", ".", "merge", "(", "opts", ")", "#decide whether to use the normal unified ID or the variant for encoding to str", "target", "=", "(", "self", ".", "variant?", "&&", "options", "[", ":variant_encoding", "]", ")", "?", "self", ".", "variant", ":", "@unified", "EmojiChar", "::", "unified_to_char", "(", "target", ")", "end" ]
Renders an `EmojiChar` to its string glyph representation, suitable for printing to screen. @option opts [Boolean] :variant_encoding specify whether the variant encoding selector should be used to hint to rendering devices that "graphic" representation should be used. By default, we use this for all Emoji characters that contain a possible variant. @return [String] the emoji character rendered to a UTF-8 string
[ "Renders", "an", "EmojiChar", "to", "its", "string", "glyph", "representation", "suitable", "for", "printing", "to", "screen", "." ]
3f1885bcdc39c086cb9fda17704ee7ea4360e4ec
https://github.com/mroth/emoji_data.rb/blob/3f1885bcdc39c086cb9fda17704ee7ea4360e4ec/lib/emoji_data/emoji_char.rb#L56-L61
1,548
mroth/emoji_data.rb
lib/emoji_data/emoji_char.rb
EmojiData.EmojiChar.chars
def chars results = [self.render({variant_encoding: false})] @variations.each do |variation| results << EmojiChar::unified_to_char(variation) end @chars ||= results end
ruby
def chars results = [self.render({variant_encoding: false})] @variations.each do |variation| results << EmojiChar::unified_to_char(variation) end @chars ||= results end
[ "def", "chars", "results", "=", "[", "self", ".", "render", "(", "{", "variant_encoding", ":", "false", "}", ")", "]", "@variations", ".", "each", "do", "|", "variation", "|", "results", "<<", "EmojiChar", "::", "unified_to_char", "(", "variation", ")", "end", "@chars", "||=", "results", "end" ]
Returns a list of all possible UTF-8 string renderings of an `EmojiChar`. E.g., normal, with variant selectors, etc. This is useful if you want to have all possible values to match against when searching for the emoji in a string representation. @return [Array<String>] all possible UTF-8 string renderings
[ "Returns", "a", "list", "of", "all", "possible", "UTF", "-", "8", "string", "renderings", "of", "an", "EmojiChar", "." ]
3f1885bcdc39c086cb9fda17704ee7ea4360e4ec
https://github.com/mroth/emoji_data.rb/blob/3f1885bcdc39c086cb9fda17704ee7ea4360e4ec/lib/emoji_data/emoji_char.rb#L73-L79
1,549
nickcharlton/boxes
lib/boxes/template.rb
Boxes.Template.render
def render(args) ERB.new(template, nil, '-').result(ERBContext.new(args).get_binding) end
ruby
def render(args) ERB.new(template, nil, '-').result(ERBContext.new(args).get_binding) end
[ "def", "render", "(", "args", ")", "ERB", ".", "new", "(", "template", ",", "nil", ",", "'-'", ")", ".", "result", "(", "ERBContext", ".", "new", "(", "args", ")", ".", "get_binding", ")", "end" ]
Load a template with a given name. @param env [Boxes::Environment] the environment to source templates. @param name [String] the name of the template. @return [Boxes::Template] a template instance. Render the template. @param args [Hash] the values to set. @return [String] the rendered template.
[ "Load", "a", "template", "with", "a", "given", "name", "." ]
d5558d6f2c4f98c6e453f8b960f28c7540433936
https://github.com/nickcharlton/boxes/blob/d5558d6f2c4f98c6e453f8b960f28c7540433936/lib/boxes/template.rb#L29-L31
1,550
hzamani/parsi-date
lib/parsi-date.rb
Parsi.Date.-
def - x case x when Numeric return self.class.new!(ajd - x, offset) when Date return ajd - x.ajd end raise TypeError, 'expected numeric or date' end
ruby
def - x case x when Numeric return self.class.new!(ajd - x, offset) when Date return ajd - x.ajd end raise TypeError, 'expected numeric or date' end
[ "def", "-", "x", "case", "x", "when", "Numeric", "return", "self", ".", "class", ".", "new!", "(", "ajd", "-", "x", ",", "offset", ")", "when", "Date", "return", "ajd", "-", "x", ".", "ajd", "end", "raise", "TypeError", ",", "'expected numeric or date'", "end" ]
If +x+ is a Numeric value, create a new Date object that is +x+ days earlier than the current one. If +x+ is a Date, return the number of days between the two dates; or, more precisely, how many days later the current date is than +x+. If +x+ is neither Numeric nor a Date, a TypeError is raised.
[ "If", "+", "x", "+", "is", "a", "Numeric", "value", "create", "a", "new", "Date", "object", "that", "is", "+", "x", "+", "days", "earlier", "than", "the", "current", "one", "." ]
63a9a89cd9c7dfc53b2d508993d5b1add2638589
https://github.com/hzamani/parsi-date/blob/63a9a89cd9c7dfc53b2d508993d5b1add2638589/lib/parsi-date.rb#L500-L508
1,551
hzamani/parsi-date
lib/parsi-date.rb
Parsi.Date.>>
def >> n y, m = (year * 12 + (mon - 1) + n).divmod(12) m, = (m + 1) .divmod(1) d = mday until jd2 = _valid_civil?(y, m, d) d -= 1 raise ArgumentError, 'invalid date' unless d > 0 end self + (jd2 - jd) end
ruby
def >> n y, m = (year * 12 + (mon - 1) + n).divmod(12) m, = (m + 1) .divmod(1) d = mday until jd2 = _valid_civil?(y, m, d) d -= 1 raise ArgumentError, 'invalid date' unless d > 0 end self + (jd2 - jd) end
[ "def", ">>", "n", "y", ",", "m", "=", "(", "year", "*", "12", "+", "(", "mon", "-", "1", ")", "+", "n", ")", ".", "divmod", "(", "12", ")", "m", ",", "=", "(", "m", "+", "1", ")", ".", "divmod", "(", "1", ")", "d", "=", "mday", "until", "jd2", "=", "_valid_civil?", "(", "y", ",", "m", ",", "d", ")", "d", "-=", "1", "raise", "ArgumentError", ",", "'invalid date'", "unless", "d", ">", "0", "end", "self", "+", "(", "jd2", "-", "jd", ")", "end" ]
Return a new Date object that is +n+ months later than the current one. If the day-of-the-month of the current Date is greater than the last day of the target month, the day-of-the-month of the returned Date will be the last day of the target month.
[ "Return", "a", "new", "Date", "object", "that", "is", "+", "n", "+", "months", "later", "than", "the", "current", "one", "." ]
63a9a89cd9c7dfc53b2d508993d5b1add2638589
https://github.com/hzamani/parsi-date/blob/63a9a89cd9c7dfc53b2d508993d5b1add2638589/lib/parsi-date.rb#L570-L579
1,552
paddor/cztop
lib/cztop/config/traversing.rb
CZTop::Config::Traversing.ChildrenAccessor.new
def new(name = nil, value = nil) config = CZTop::Config.new(name, value, parent: @config) yield config if block_given? config end
ruby
def new(name = nil, value = nil) config = CZTop::Config.new(name, value, parent: @config) yield config if block_given? config end
[ "def", "new", "(", "name", "=", "nil", ",", "value", "=", "nil", ")", "config", "=", "CZTop", "::", "Config", ".", "new", "(", "name", ",", "value", ",", "parent", ":", "@config", ")", "yield", "config", "if", "block_given?", "config", "end" ]
Adds a new Config item and yields it, so it can be configured in a block. @param name [String] name for new config item @param value [String] value for new config item @yieldparam config [Config] the new config item, if block was given @return [Config] the new config item
[ "Adds", "a", "new", "Config", "item", "and", "yields", "it", "so", "it", "can", "be", "configured", "in", "a", "block", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/config/traversing.rb#L127-L131
1,553
paddor/cztop
lib/cztop/socket.rb
CZTop.Socket.CURVE_client!
def CURVE_client!(client_cert, server_cert) if server_cert.secret_key raise SecurityError, "server's secret key not secret" end client_cert.apply(self) # NOTE: desired: raises if no secret key in cert options.CURVE_serverkey = server_cert.public_key end
ruby
def CURVE_client!(client_cert, server_cert) if server_cert.secret_key raise SecurityError, "server's secret key not secret" end client_cert.apply(self) # NOTE: desired: raises if no secret key in cert options.CURVE_serverkey = server_cert.public_key end
[ "def", "CURVE_client!", "(", "client_cert", ",", "server_cert", ")", "if", "server_cert", ".", "secret_key", "raise", "SecurityError", ",", "\"server's secret key not secret\"", "end", "client_cert", ".", "apply", "(", "self", ")", "# NOTE: desired: raises if no secret key in cert", "options", ".", "CURVE_serverkey", "=", "server_cert", ".", "public_key", "end" ]
Enables CURVE security and makes this socket a CURVE client. @param client_cert [Certificate] client's certificate, to secure communication (and be authenticated by the server) @param server_cert [Certificate] the remote server's certificate, so this socket is able to authenticate the server @return [void] @raise [SecurityError] if the server's secret key is set in server_cert, which means it's not secret anymore @raise [SystemCallError] if there's no secret key in client_cert
[ "Enables", "CURVE", "security", "and", "makes", "this", "socket", "a", "CURVE", "client", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/socket.rb#L33-L40
1,554
paddor/cztop
lib/cztop/socket.rb
CZTop.Socket.connect
def connect(endpoint) rc = ffi_delegate.connect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
def connect(endpoint) rc = ffi_delegate.connect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
[ "def", "connect", "(", "endpoint", ")", "rc", "=", "ffi_delegate", ".", "connect", "(", "\"%s\"", ",", ":string", ",", "endpoint", ")", "raise", "ArgumentError", ",", "\"incorrect endpoint: %p\"", "%", "endpoint", "if", "rc", "==", "-", "1", "end" ]
Connects to an endpoint. @param endpoint [String] @return [void] @raise [ArgumentError] if the endpoint is incorrect
[ "Connects", "to", "an", "endpoint", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/socket.rb#L54-L57
1,555
paddor/cztop
lib/cztop/socket.rb
CZTop.Socket.disconnect
def disconnect(endpoint) rc = ffi_delegate.disconnect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
def disconnect(endpoint) rc = ffi_delegate.disconnect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
[ "def", "disconnect", "(", "endpoint", ")", "rc", "=", "ffi_delegate", ".", "disconnect", "(", "\"%s\"", ",", ":string", ",", "endpoint", ")", "raise", "ArgumentError", ",", "\"incorrect endpoint: %p\"", "%", "endpoint", "if", "rc", "==", "-", "1", "end" ]
Disconnects from an endpoint. @param endpoint [String] @return [void] @raise [ArgumentError] if the endpoint is incorrect
[ "Disconnects", "from", "an", "endpoint", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/socket.rb#L63-L66
1,556
paddor/cztop
lib/cztop/socket.rb
CZTop.Socket.bind
def bind(endpoint) rc = ffi_delegate.bind("%s", :string, endpoint) raise_zmq_err("unable to bind to %p" % endpoint) if rc == -1 @last_tcp_port = rc if rc > 0 end
ruby
def bind(endpoint) rc = ffi_delegate.bind("%s", :string, endpoint) raise_zmq_err("unable to bind to %p" % endpoint) if rc == -1 @last_tcp_port = rc if rc > 0 end
[ "def", "bind", "(", "endpoint", ")", "rc", "=", "ffi_delegate", ".", "bind", "(", "\"%s\"", ",", ":string", ",", "endpoint", ")", "raise_zmq_err", "(", "\"unable to bind to %p\"", "%", "endpoint", ")", "if", "rc", "==", "-", "1", "@last_tcp_port", "=", "rc", "if", "rc", ">", "0", "end" ]
Binds to an endpoint. @note When binding to an automatically selected TCP port, this will set {#last_tcp_port}. @param endpoint [String] @return [void] @raise [SystemCallError] in case of failure
[ "Binds", "to", "an", "endpoint", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/socket.rb#L85-L89
1,557
paddor/cztop
lib/cztop/socket.rb
CZTop.Socket.unbind
def unbind(endpoint) rc = ffi_delegate.unbind("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
def unbind(endpoint) rc = ffi_delegate.unbind("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
[ "def", "unbind", "(", "endpoint", ")", "rc", "=", "ffi_delegate", ".", "unbind", "(", "\"%s\"", ",", ":string", ",", "endpoint", ")", "raise", "ArgumentError", ",", "\"incorrect endpoint: %p\"", "%", "endpoint", "if", "rc", "==", "-", "1", "end" ]
Unbinds from an endpoint. @param endpoint [String] @return [void] @raise [ArgumentError] if the endpoint is incorrect
[ "Unbinds", "from", "an", "endpoint", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/socket.rb#L95-L98
1,558
hawkular/hawkular-client-ruby
lib/hawkular/inventory/inventory_api.rb
Hawkular::Inventory.Client.resource
def resource(id) hash = http_get(url('/resources/%s', id)) Resource.new(hash) rescue ::Hawkular::Exception => e return if e.cause.is_a?(::RestClient::NotFound) raise end
ruby
def resource(id) hash = http_get(url('/resources/%s', id)) Resource.new(hash) rescue ::Hawkular::Exception => e return if e.cause.is_a?(::RestClient::NotFound) raise end
[ "def", "resource", "(", "id", ")", "hash", "=", "http_get", "(", "url", "(", "'/resources/%s'", ",", "id", ")", ")", "Resource", ".", "new", "(", "hash", ")", "rescue", "::", "Hawkular", "::", "Exception", "=>", "e", "return", "if", "e", ".", "cause", ".", "is_a?", "(", "::", "RestClient", "::", "NotFound", ")", "raise", "end" ]
Get single resource by id @return Resource the resource
[ "Get", "single", "resource", "by", "id" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/inventory/inventory_api.rb#L39-L45
1,559
hawkular/hawkular-client-ruby
lib/hawkular/inventory/inventory_api.rb
Hawkular::Inventory.Client.children_resources
def children_resources(parent_id) http_get(url('/resources/%s/children', parent_id))['results'].map { |r| Resource.new(r) } end
ruby
def children_resources(parent_id) http_get(url('/resources/%s/children', parent_id))['results'].map { |r| Resource.new(r) } end
[ "def", "children_resources", "(", "parent_id", ")", "http_get", "(", "url", "(", "'/resources/%s/children'", ",", "parent_id", ")", ")", "[", "'results'", "]", ".", "map", "{", "|", "r", "|", "Resource", ".", "new", "(", "r", ")", "}", "end" ]
Get childrens of a resource @return Children of a resource
[ "Get", "childrens", "of", "a", "resource" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/inventory/inventory_api.rb#L56-L58
1,560
hawkular/hawkular-client-ruby
lib/hawkular/inventory/inventory_api.rb
Hawkular::Inventory.Client.parent
def parent(id) hash = http_get(url('/resources/%s/parent', id)) Resource.new(hash) if hash end
ruby
def parent(id) hash = http_get(url('/resources/%s/parent', id)) Resource.new(hash) if hash end
[ "def", "parent", "(", "id", ")", "hash", "=", "http_get", "(", "url", "(", "'/resources/%s/parent'", ",", "id", ")", ")", "Resource", ".", "new", "(", "hash", ")", "if", "hash", "end" ]
Get parent of a resource @return Resource the parent resource, or nil if the provided ID referred to a root resource
[ "Get", "parent", "of", "a", "resource" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/inventory/inventory_api.rb#L62-L65
1,561
paddor/cztop
lib/cztop/beacon.rb
CZTop.Beacon.configure
def configure(port) @actor.send_picture("si", :string, "CONFIGURE", :int, port) ptr = Zstr.recv(@actor) # NULL if context terminated or interrupted HasFFIDelegate.raise_zmq_err if ptr.null? hostname = ptr.read_string return hostname unless hostname.empty? raise NotImplementedError, "system doesn't support UDP broadcasts" end
ruby
def configure(port) @actor.send_picture("si", :string, "CONFIGURE", :int, port) ptr = Zstr.recv(@actor) # NULL if context terminated or interrupted HasFFIDelegate.raise_zmq_err if ptr.null? hostname = ptr.read_string return hostname unless hostname.empty? raise NotImplementedError, "system doesn't support UDP broadcasts" end
[ "def", "configure", "(", "port", ")", "@actor", ".", "send_picture", "(", "\"si\"", ",", ":string", ",", "\"CONFIGURE\"", ",", ":int", ",", "port", ")", "ptr", "=", "Zstr", ".", "recv", "(", "@actor", ")", "# NULL if context terminated or interrupted", "HasFFIDelegate", ".", "raise_zmq_err", "if", "ptr", ".", "null?", "hostname", "=", "ptr", ".", "read_string", "return", "hostname", "unless", "hostname", ".", "empty?", "raise", "NotImplementedError", ",", "\"system doesn't support UDP broadcasts\"", "end" ]
Run the beacon on the specified UDP port. @param port [Integer] port number to @return [String] hostname, which can be used as endpoint for incoming connections @raise [Interrupt] if the context was terminated or the process interrupted @raise [NotImplementedError] if the system doesn't support UDP broadcasts
[ "Run", "the", "beacon", "on", "the", "specified", "UDP", "port", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/beacon.rb#L45-L56
1,562
paddor/cztop
lib/cztop/beacon.rb
CZTop.Beacon.publish
def publish(data, interval) raise ArgumentError, "data too long" if data.bytesize > MAX_BEACON_DATA @actor.send_picture("sbi", :string, "PUBLISH", :string, data, :int, data.bytesize, :int, interval) end
ruby
def publish(data, interval) raise ArgumentError, "data too long" if data.bytesize > MAX_BEACON_DATA @actor.send_picture("sbi", :string, "PUBLISH", :string, data, :int, data.bytesize, :int, interval) end
[ "def", "publish", "(", "data", ",", "interval", ")", "raise", "ArgumentError", ",", "\"data too long\"", "if", "data", ".", "bytesize", ">", "MAX_BEACON_DATA", "@actor", ".", "send_picture", "(", "\"sbi\"", ",", ":string", ",", "\"PUBLISH\"", ",", ":string", ",", "data", ",", ":int", ",", "data", ".", "bytesize", ",", ":int", ",", "interval", ")", "end" ]
Start broadcasting a beacon. @param data [String] data to publish @param interval [Integer] interval in msec @raise [ArgumentError] if data is longer than {MAX_BEACON_DATA} bytes @return [void]
[ "Start", "broadcasting", "a", "beacon", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/beacon.rb#L66-L70
1,563
hawkular/hawkular-client-ruby
lib/hawkular/tokens/tokens_api.rb
Hawkular::Token.Client.get_tokens
def get_tokens(credentials = {}) creds = credentials.empty? ? @credentials : credentials auth_header = { Authorization: base_64_credentials(creds) } http_get('/secret-store/v1/tokens', auth_header) end
ruby
def get_tokens(credentials = {}) creds = credentials.empty? ? @credentials : credentials auth_header = { Authorization: base_64_credentials(creds) } http_get('/secret-store/v1/tokens', auth_header) end
[ "def", "get_tokens", "(", "credentials", "=", "{", "}", ")", "creds", "=", "credentials", ".", "empty?", "?", "@credentials", ":", "credentials", "auth_header", "=", "{", "Authorization", ":", "base_64_credentials", "(", "creds", ")", "}", "http_get", "(", "'/secret-store/v1/tokens'", ",", "auth_header", ")", "end" ]
Create a new Secret Store client @param entrypoint [String] base url of Hawkular - e.g http://localhost:8080 @param credentials [Hash{String=>String}] Hash of username, password @param options [Hash{String=>String}] Additional rest client options Retrieve the tenant id for the passed credentials. If no credentials are passed, the ones from the constructor are used @param credentials [Hash{String=>String}] Hash of username, password, token(optional) @return [String] tenant id
[ "Create", "a", "new", "Secret", "Store", "client" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/tokens/tokens_api.rb#L19-L23
1,564
paddor/cztop
lib/cztop/z85.rb
CZTop.Z85.encode
def encode(input) raise ArgumentError, "wrong input length" if input.bytesize % 4 > 0 input = input.dup.force_encoding(Encoding::BINARY) ptr = ffi_delegate.encode(input, input.bytesize) raise_zmq_err if ptr.null? z85 = ptr.read_string z85.encode!(Encoding::ASCII) return z85 end
ruby
def encode(input) raise ArgumentError, "wrong input length" if input.bytesize % 4 > 0 input = input.dup.force_encoding(Encoding::BINARY) ptr = ffi_delegate.encode(input, input.bytesize) raise_zmq_err if ptr.null? z85 = ptr.read_string z85.encode!(Encoding::ASCII) return z85 end
[ "def", "encode", "(", "input", ")", "raise", "ArgumentError", ",", "\"wrong input length\"", "if", "input", ".", "bytesize", "%", "4", ">", "0", "input", "=", "input", ".", "dup", ".", "force_encoding", "(", "Encoding", "::", "BINARY", ")", "ptr", "=", "ffi_delegate", ".", "encode", "(", "input", ",", "input", ".", "bytesize", ")", "raise_zmq_err", "if", "ptr", ".", "null?", "z85", "=", "ptr", ".", "read_string", "z85", ".", "encode!", "(", "Encoding", "::", "ASCII", ")", "return", "z85", "end" ]
Encodes to Z85. @param input [String] possibly binary input data @return [String] Z85 encoded data as ASCII string @raise [ArgumentError] if input length isn't divisible by 4 with no remainder @raise [SystemCallError] if this fails
[ "Encodes", "to", "Z85", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/z85.rb#L55-L63
1,565
paddor/cztop
lib/cztop/z85.rb
CZTop.Z85.decode
def decode(input) raise ArgumentError, "wrong input length" if input.bytesize % 5 > 0 zchunk = ffi_delegate.decode(input) raise_zmq_err if zchunk.null? decoded_string = zchunk.data.read_string(zchunk.size - 1) return decoded_string end
ruby
def decode(input) raise ArgumentError, "wrong input length" if input.bytesize % 5 > 0 zchunk = ffi_delegate.decode(input) raise_zmq_err if zchunk.null? decoded_string = zchunk.data.read_string(zchunk.size - 1) return decoded_string end
[ "def", "decode", "(", "input", ")", "raise", "ArgumentError", ",", "\"wrong input length\"", "if", "input", ".", "bytesize", "%", "5", ">", "0", "zchunk", "=", "ffi_delegate", ".", "decode", "(", "input", ")", "raise_zmq_err", "if", "zchunk", ".", "null?", "decoded_string", "=", "zchunk", ".", "data", ".", "read_string", "(", "zchunk", ".", "size", "-", "1", ")", "return", "decoded_string", "end" ]
Decodes from Z85. @param input [String] Z85 encoded data @return [String] original data as binary string @raise [ArgumentError] if input length isn't divisible by 5 with no remainder @raise [SystemCallError] if this fails
[ "Decodes", "from", "Z85", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/z85.rb#L71-L77
1,566
flori/protocol
lib/protocol/message.rb
Protocol.Message.to_ruby
def to_ruby(result = '') if arity result << " def #{name}(" args = if arity >= 0 (1..arity).map { |i| "x#{i}" } else (1..~arity).map { |i| "x#{i}" } << '*rest' end if block_expected? args << '&block' end result << args * ', ' result << ") end\n" else result << " understand :#{name}\n" end end
ruby
def to_ruby(result = '') if arity result << " def #{name}(" args = if arity >= 0 (1..arity).map { |i| "x#{i}" } else (1..~arity).map { |i| "x#{i}" } << '*rest' end if block_expected? args << '&block' end result << args * ', ' result << ") end\n" else result << " understand :#{name}\n" end end
[ "def", "to_ruby", "(", "result", "=", "''", ")", "if", "arity", "result", "<<", "\" def #{name}(\"", "args", "=", "if", "arity", ">=", "0", "(", "1", "..", "arity", ")", ".", "map", "{", "|", "i", "|", "\"x#{i}\"", "}", "else", "(", "1", "..", "~", "arity", ")", ".", "map", "{", "|", "i", "|", "\"x#{i}\"", "}", "<<", "'*rest'", "end", "if", "block_expected?", "args", "<<", "'&block'", "end", "result", "<<", "args", "*", "', '", "result", "<<", "\") end\\n\"", "else", "result", "<<", "\" understand :#{name}\\n\"", "end", "end" ]
Concatenates a method signature as ruby code to the +result+ string and returns it.
[ "Concatenates", "a", "method", "signature", "as", "ruby", "code", "to", "the", "+", "result", "+", "string", "and", "returns", "it", "." ]
528f250f84a46b0f3e6fccf06430ed413c7d994c
https://github.com/flori/protocol/blob/528f250f84a46b0f3e6fccf06430ed413c7d994c/lib/protocol/message.rb#L57-L73
1,567
flori/protocol
lib/protocol/message.rb
Protocol.Message.check_class
def check_class(klass) unless klass.method_defined?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not implemented in #{klass}") end check_method = klass.instance_method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{klass}") end if block_expected? modul = Utilities.find_method_module(name, klass.ancestors) parser = MethodParser.new(modul, name) parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{klass}") end arity and wrap_method(klass) true end
ruby
def check_class(klass) unless klass.method_defined?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not implemented in #{klass}") end check_method = klass.instance_method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{klass}") end if block_expected? modul = Utilities.find_method_module(name, klass.ancestors) parser = MethodParser.new(modul, name) parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{klass}") end arity and wrap_method(klass) true end
[ "def", "check_class", "(", "klass", ")", "unless", "klass", ".", "method_defined?", "(", "name", ")", "raise", "NotImplementedErrorCheckError", ".", "new", "(", "self", ",", "\"method '#{name}' not implemented in #{klass}\"", ")", "end", "check_method", "=", "klass", ".", "instance_method", "(", "name", ")", "if", "arity", "and", "(", "check_arity", "=", "check_method", ".", "arity", ")", "!=", "arity", "raise", "ArgumentErrorCheckError", ".", "new", "(", "self", ",", "\"wrong number of arguments for protocol\"", "\" in method '#{name}' (#{check_arity} for #{arity}) of #{klass}\"", ")", "end", "if", "block_expected?", "modul", "=", "Utilities", ".", "find_method_module", "(", "name", ",", "klass", ".", "ancestors", ")", "parser", "=", "MethodParser", ".", "new", "(", "modul", ",", "name", ")", "parser", ".", "block_arg?", "or", "raise", "BlockCheckError", ".", "new", "(", "self", ",", "\"expected a block argument for #{klass}\"", ")", "end", "arity", "and", "wrap_method", "(", "klass", ")", "true", "end" ]
Check class +klass+ against this Message instance, and raise a CheckError exception if necessary.
[ "Check", "class", "+", "klass", "+", "against", "this", "Message", "instance", "and", "raise", "a", "CheckError", "exception", "if", "necessary", "." ]
528f250f84a46b0f3e6fccf06430ed413c7d994c
https://github.com/flori/protocol/blob/528f250f84a46b0f3e6fccf06430ed413c7d994c/lib/protocol/message.rb#L92-L111
1,568
flori/protocol
lib/protocol/message.rb
Protocol.Message.check_object
def check_object(object) if !object.respond_to?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not responding in #{object}") end check_method = object.method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{object}") end if block_expected? if object.singleton_methods(false).map { |m| m.to_s } .include?(name) parser = MethodParser.new(object, name, true) else ancestors = object.class.ancestors modul = Utilities.find_method_module(name, ancestors) parser = MethodParser.new(modul, name) end parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{object}:#{object.class}") end if arity and not protocol === object object.extend protocol wrap_method(class << object ; self ; end) end true end
ruby
def check_object(object) if !object.respond_to?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not responding in #{object}") end check_method = object.method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{object}") end if block_expected? if object.singleton_methods(false).map { |m| m.to_s } .include?(name) parser = MethodParser.new(object, name, true) else ancestors = object.class.ancestors modul = Utilities.find_method_module(name, ancestors) parser = MethodParser.new(modul, name) end parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{object}:#{object.class}") end if arity and not protocol === object object.extend protocol wrap_method(class << object ; self ; end) end true end
[ "def", "check_object", "(", "object", ")", "if", "!", "object", ".", "respond_to?", "(", "name", ")", "raise", "NotImplementedErrorCheckError", ".", "new", "(", "self", ",", "\"method '#{name}' not responding in #{object}\"", ")", "end", "check_method", "=", "object", ".", "method", "(", "name", ")", "if", "arity", "and", "(", "check_arity", "=", "check_method", ".", "arity", ")", "!=", "arity", "raise", "ArgumentErrorCheckError", ".", "new", "(", "self", ",", "\"wrong number of arguments for protocol\"", "\" in method '#{name}' (#{check_arity} for #{arity}) of #{object}\"", ")", "end", "if", "block_expected?", "if", "object", ".", "singleton_methods", "(", "false", ")", ".", "map", "{", "|", "m", "|", "m", ".", "to_s", "}", ".", "include?", "(", "name", ")", "parser", "=", "MethodParser", ".", "new", "(", "object", ",", "name", ",", "true", ")", "else", "ancestors", "=", "object", ".", "class", ".", "ancestors", "modul", "=", "Utilities", ".", "find_method_module", "(", "name", ",", "ancestors", ")", "parser", "=", "MethodParser", ".", "new", "(", "modul", ",", "name", ")", "end", "parser", ".", "block_arg?", "or", "raise", "BlockCheckError", ".", "new", "(", "self", ",", "\"expected a block argument for #{object}:#{object.class}\"", ")", "end", "if", "arity", "and", "not", "protocol", "===", "object", "object", ".", "extend", "protocol", "wrap_method", "(", "class", "<<", "object", ";", "self", ";", "end", ")", "end", "true", "end" ]
Check object +object+ against this Message instance, and raise a CheckError exception if necessary.
[ "Check", "object", "+", "object", "+", "against", "this", "Message", "instance", "and", "raise", "a", "CheckError", "exception", "if", "necessary", "." ]
528f250f84a46b0f3e6fccf06430ed413c7d994c
https://github.com/flori/protocol/blob/528f250f84a46b0f3e6fccf06430ed413c7d994c/lib/protocol/message.rb#L190-L217
1,569
mtuchowski/mdspell
lib/mdspell/cli.rb
MdSpell.CLI.files
def files cli_arguments.each_with_index do |filename, index| if Dir.exist?(filename) cli_arguments[index] = Dir["#{filename}/**/*.md"] end end cli_arguments.flatten! cli_arguments end
ruby
def files cli_arguments.each_with_index do |filename, index| if Dir.exist?(filename) cli_arguments[index] = Dir["#{filename}/**/*.md"] end end cli_arguments.flatten! cli_arguments end
[ "def", "files", "cli_arguments", ".", "each_with_index", "do", "|", "filename", ",", "index", "|", "if", "Dir", ".", "exist?", "(", "filename", ")", "cli_arguments", "[", "index", "]", "=", "Dir", "[", "\"#{filename}/**/*.md\"", "]", "end", "end", "cli_arguments", ".", "flatten!", "cli_arguments", "end" ]
List of markdown files from argument list.
[ "List", "of", "markdown", "files", "from", "argument", "list", "." ]
d8232366bbe12261a1e3a7763b0c8aa925d82b85
https://github.com/mtuchowski/mdspell/blob/d8232366bbe12261a1e3a7763b0c8aa925d82b85/lib/mdspell/cli.rb#L59-L67
1,570
damian/jshint
lib/jshint/lint.rb
Jshint.Lint.lint
def lint config.javascript_files.each do |file| file_content = get_file_content_as_json(file) code = %( JSHINT(#{file_content}, #{jshint_options}, #{jshint_globals}); return JSHINT.errors; ) errors[file] = context.exec(code) end end
ruby
def lint config.javascript_files.each do |file| file_content = get_file_content_as_json(file) code = %( JSHINT(#{file_content}, #{jshint_options}, #{jshint_globals}); return JSHINT.errors; ) errors[file] = context.exec(code) end end
[ "def", "lint", "config", ".", "javascript_files", ".", "each", "do", "|", "file", "|", "file_content", "=", "get_file_content_as_json", "(", "file", ")", "code", "=", "%(\n JSHINT(#{file_content}, #{jshint_options}, #{jshint_globals});\n return JSHINT.errors;\n )", "errors", "[", "file", "]", "=", "context", ".", "exec", "(", "code", ")", "end", "end" ]
Sets up our Linting behaviour @param config_path [String] The absolute path to a configuration YAML file @return [void] Runs JSHint over each file in our search path @return [void]
[ "Sets", "up", "our", "Linting", "behaviour" ]
d7dc6f1913bad5927ac0de3e34714ef920e86cbe
https://github.com/damian/jshint/blob/d7dc6f1913bad5927ac0de3e34714ef920e86cbe/lib/jshint/lint.rb#L27-L36
1,571
hawkular/hawkular-client-ruby
lib/hawkular/base_client.rb
Hawkular.BaseClient.generate_query_params
def generate_query_params(params = {}) params = params.reject { |_k, v| v.nil? || ((v.instance_of? Array) && v.empty?) } return '' if params.empty? params.inject('?') do |ret, (k, v)| ret += '&' unless ret == '?' part = v.instance_of?(Array) ? "#{k}=#{v.join(',')}" : "#{k}=#{v}" ret + hawk_escape(part) end end
ruby
def generate_query_params(params = {}) params = params.reject { |_k, v| v.nil? || ((v.instance_of? Array) && v.empty?) } return '' if params.empty? params.inject('?') do |ret, (k, v)| ret += '&' unless ret == '?' part = v.instance_of?(Array) ? "#{k}=#{v.join(',')}" : "#{k}=#{v}" ret + hawk_escape(part) end end
[ "def", "generate_query_params", "(", "params", "=", "{", "}", ")", "params", "=", "params", ".", "reject", "{", "|", "_k", ",", "v", "|", "v", ".", "nil?", "||", "(", "(", "v", ".", "instance_of?", "Array", ")", "&&", "v", ".", "empty?", ")", "}", "return", "''", "if", "params", ".", "empty?", "params", ".", "inject", "(", "'?'", ")", "do", "|", "ret", ",", "(", "k", ",", "v", ")", "|", "ret", "+=", "'&'", "unless", "ret", "==", "'?'", "part", "=", "v", ".", "instance_of?", "(", "Array", ")", "?", "\"#{k}=#{v.join(',')}\"", ":", "\"#{k}=#{v}\"", "ret", "+", "hawk_escape", "(", "part", ")", "end", "end" ]
Generate a query string from the passed hash, starting with '?' Values may be an array, in which case the array values are joined together by `,`. @param params [Hash] key-values pairs @return [String] complete query string to append to a base url, '' if no valid params
[ "Generate", "a", "query", "string", "from", "the", "passed", "hash", "starting", "with", "?", "Values", "may", "be", "an", "array", "in", "which", "case", "the", "array", "values", "are", "joined", "together", "by", "." ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/base_client.rb#L133-L142
1,572
paddor/cztop
lib/cztop/message.rb
CZTop.Message.<<
def <<(frame) case frame when String # NOTE: can't use addstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.addmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.append(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 self end
ruby
def <<(frame) case frame when String # NOTE: can't use addstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.addmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.append(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 self end
[ "def", "<<", "(", "frame", ")", "case", "frame", "when", "String", "# NOTE: can't use addstr because the data might be binary", "mem", "=", "FFI", "::", "MemoryPointer", ".", "from_string", "(", "frame", ")", "rc", "=", "ffi_delegate", ".", "addmem", "(", "mem", ",", "mem", ".", "size", "-", "1", ")", "# without NULL byte", "when", "Frame", "rc", "=", "ffi_delegate", ".", "append", "(", "frame", ".", "ffi_delegate", ")", "else", "raise", "ArgumentError", ",", "\"invalid frame: %p\"", "%", "frame", "end", "raise_zmq_err", "unless", "rc", "==", "0", "self", "end" ]
Append a frame to this message. @param frame [String, Frame] what to append @raise [ArgumentError] if frame has an invalid type @raise [SystemCallError] if this fails @note If you provide a {Frame}, do NOT use that frame afterwards anymore, as its native counterpart will have been destroyed. @return [self] so it can be chained
[ "Append", "a", "frame", "to", "this", "message", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/message.rb#L88-L101
1,573
paddor/cztop
lib/cztop/message.rb
CZTop.Message.prepend
def prepend(frame) case frame when String # NOTE: can't use pushstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.pushmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.prepend(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 end
ruby
def prepend(frame) case frame when String # NOTE: can't use pushstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.pushmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.prepend(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 end
[ "def", "prepend", "(", "frame", ")", "case", "frame", "when", "String", "# NOTE: can't use pushstr because the data might be binary", "mem", "=", "FFI", "::", "MemoryPointer", ".", "from_string", "(", "frame", ")", "rc", "=", "ffi_delegate", ".", "pushmem", "(", "mem", ",", "mem", ".", "size", "-", "1", ")", "# without NULL byte", "when", "Frame", "rc", "=", "ffi_delegate", ".", "prepend", "(", "frame", ".", "ffi_delegate", ")", "else", "raise", "ArgumentError", ",", "\"invalid frame: %p\"", "%", "frame", "end", "raise_zmq_err", "unless", "rc", "==", "0", "end" ]
Prepend a frame to this message. @param frame [String, Frame] what to prepend @raise [ArgumentError] if frame has an invalid type @raise [SystemCallError] if this fails @note If you provide a {Frame}, do NOT use that frame afterwards anymore, as its native counterpart will have been destroyed. @return [void]
[ "Prepend", "a", "frame", "to", "this", "message", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/message.rb#L110-L122
1,574
paddor/cztop
lib/cztop/message.rb
CZTop.Message.pop
def pop # NOTE: can't use popstr because the data might be binary ptr = ffi_delegate.pop return nil if ptr.null? Frame.from_ffi_delegate(ptr).to_s end
ruby
def pop # NOTE: can't use popstr because the data might be binary ptr = ffi_delegate.pop return nil if ptr.null? Frame.from_ffi_delegate(ptr).to_s end
[ "def", "pop", "# NOTE: can't use popstr because the data might be binary", "ptr", "=", "ffi_delegate", ".", "pop", "return", "nil", "if", "ptr", ".", "null?", "Frame", ".", "from_ffi_delegate", "(", "ptr", ")", ".", "to_s", "end" ]
Removes first part from message and returns it as a string. @return [String, nil] first part, if any, or nil
[ "Removes", "first", "part", "from", "message", "and", "returns", "it", "as", "a", "string", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/message.rb#L126-L131
1,575
paddor/cztop
lib/cztop/message.rb
CZTop.Message.to_a
def to_a ffi_delegate = ffi_delegate() frame = ffi_delegate.first return [] if frame.null? arr = [ frame.data.read_bytes(frame.size) ] while frame = ffi_delegate.next and not frame.null? arr << frame.data.read_bytes(frame.size) end return arr end
ruby
def to_a ffi_delegate = ffi_delegate() frame = ffi_delegate.first return [] if frame.null? arr = [ frame.data.read_bytes(frame.size) ] while frame = ffi_delegate.next and not frame.null? arr << frame.data.read_bytes(frame.size) end return arr end
[ "def", "to_a", "ffi_delegate", "=", "ffi_delegate", "(", ")", "frame", "=", "ffi_delegate", ".", "first", "return", "[", "]", "if", "frame", ".", "null?", "arr", "=", "[", "frame", ".", "data", ".", "read_bytes", "(", "frame", ".", "size", ")", "]", "while", "frame", "=", "ffi_delegate", ".", "next", "and", "not", "frame", ".", "null?", "arr", "<<", "frame", ".", "data", ".", "read_bytes", "(", "frame", ".", "size", ")", "end", "return", "arr", "end" ]
Returns all frames as strings in an array. This is useful if for quick inspection of the message. @note It'll read all frames in the message and turn them into Ruby strings. This can be a problem if the message is huge/has huge frames. @return [Array<String>] all frames
[ "Returns", "all", "frames", "as", "strings", "in", "an", "array", ".", "This", "is", "useful", "if", "for", "quick", "inspection", "of", "the", "message", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/message.rb#L144-L155
1,576
paddor/cztop
lib/cztop/message.rb
CZTop.Message.routing_id=
def routing_id=(new_routing_id) raise ArgumentError unless new_routing_id.is_a? Integer # need to raise manually, as FFI lacks this feature. # @see https://github.com/ffi/ffi/issues/473 raise RangeError if new_routing_id < 0 ffi_delegate.set_routing_id(new_routing_id) end
ruby
def routing_id=(new_routing_id) raise ArgumentError unless new_routing_id.is_a? Integer # need to raise manually, as FFI lacks this feature. # @see https://github.com/ffi/ffi/issues/473 raise RangeError if new_routing_id < 0 ffi_delegate.set_routing_id(new_routing_id) end
[ "def", "routing_id", "=", "(", "new_routing_id", ")", "raise", "ArgumentError", "unless", "new_routing_id", ".", "is_a?", "Integer", "# need to raise manually, as FFI lacks this feature.", "# @see https://github.com/ffi/ffi/issues/473", "raise", "RangeError", "if", "new_routing_id", "<", "0", "ffi_delegate", ".", "set_routing_id", "(", "new_routing_id", ")", "end" ]
Sets a new routing ID. @note This is used when the message is sent to a {CZTop::Socket::SERVER} socket. @param new_routing_id [Integer] new routing ID @raise [ArgumentError] if new routing ID is not an Integer @raise [RangeError] if new routing ID is out of +uint32_t+ range @return [new_routing_id]
[ "Sets", "a", "new", "routing", "ID", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/message.rb#L191-L198
1,577
gverger/ruby-cbc
lib/ruby-cbc/conflict_solver.rb
Cbc.ConflictSolver.first_failing
def first_failing(conflict_set_size, crs, continuous: false, max_iterations: nil) min_idx = conflict_set_size max_idx = crs.nb_constraints - 1 loop do unless max_iterations.nil? return min_idx..max_idx if max_iterations <= 0 max_iterations -= 1 end half_constraint_idx = (max_idx + min_idx) / 2 # puts "Refining: [#{min_idx}:#{max_idx}] -> #{half_constraint_idx}" crs2 = crs.restrict_to_n_constraints(half_constraint_idx + 1) problem = Problem.from_compressed_row_storage(crs2, continuous: continuous) if infeasible?(problem) max_idx = half_constraint_idx # puts " INFEAS" else min_idx = half_constraint_idx + 1 # puts " FEAS" end next if max_idx != min_idx return nil if max_idx > crs.nb_constraints return min_idx..max_idx end # Shouldn't come here if the whole problem is infeasible nil end
ruby
def first_failing(conflict_set_size, crs, continuous: false, max_iterations: nil) min_idx = conflict_set_size max_idx = crs.nb_constraints - 1 loop do unless max_iterations.nil? return min_idx..max_idx if max_iterations <= 0 max_iterations -= 1 end half_constraint_idx = (max_idx + min_idx) / 2 # puts "Refining: [#{min_idx}:#{max_idx}] -> #{half_constraint_idx}" crs2 = crs.restrict_to_n_constraints(half_constraint_idx + 1) problem = Problem.from_compressed_row_storage(crs2, continuous: continuous) if infeasible?(problem) max_idx = half_constraint_idx # puts " INFEAS" else min_idx = half_constraint_idx + 1 # puts " FEAS" end next if max_idx != min_idx return nil if max_idx > crs.nb_constraints return min_idx..max_idx end # Shouldn't come here if the whole problem is infeasible nil end
[ "def", "first_failing", "(", "conflict_set_size", ",", "crs", ",", "continuous", ":", "false", ",", "max_iterations", ":", "nil", ")", "min_idx", "=", "conflict_set_size", "max_idx", "=", "crs", ".", "nb_constraints", "-", "1", "loop", "do", "unless", "max_iterations", ".", "nil?", "return", "min_idx", "..", "max_idx", "if", "max_iterations", "<=", "0", "max_iterations", "-=", "1", "end", "half_constraint_idx", "=", "(", "max_idx", "+", "min_idx", ")", "/", "2", "# puts \"Refining: [#{min_idx}:#{max_idx}] -> #{half_constraint_idx}\"", "crs2", "=", "crs", ".", "restrict_to_n_constraints", "(", "half_constraint_idx", "+", "1", ")", "problem", "=", "Problem", ".", "from_compressed_row_storage", "(", "crs2", ",", "continuous", ":", "continuous", ")", "if", "infeasible?", "(", "problem", ")", "max_idx", "=", "half_constraint_idx", "# puts \" INFEAS\"", "else", "min_idx", "=", "half_constraint_idx", "+", "1", "# puts \" FEAS\"", "end", "next", "if", "max_idx", "!=", "min_idx", "return", "nil", "if", "max_idx", ">", "crs", ".", "nb_constraints", "return", "min_idx", "..", "max_idx", "end", "# Shouldn't come here if the whole problem is infeasible", "nil", "end" ]
finds the first constraint from constraints that makes the problem infeasible
[ "finds", "the", "first", "constraint", "from", "constraints", "that", "makes", "the", "problem", "infeasible" ]
e3dfbc3a9f4bb74c13748c9a0fe924f48de0215c
https://github.com/gverger/ruby-cbc/blob/e3dfbc3a9f4bb74c13748c9a0fe924f48de0215c/lib/ruby-cbc/conflict_solver.rb#L69-L95
1,578
masciugo/genealogy
lib/genealogy/alter_methods.rb
Genealogy.AlterMethods.add_siblings
def add_siblings(*args) options = args.extract_options! case options[:half] when :father check_incompatible_relationship(:paternal_half_sibling, *args) when :mother check_incompatible_relationship(:maternal_half_sibling, *args) when nil check_incompatible_relationship(:sibling, *args) end transaction do args.inject(true) do |res,sib| res &= case options[:half] when :father raise LineageGapException, "Can't add paternal halfsiblings without a father" unless father sib.add_mother(options[:spouse]) if options[:spouse] sib.add_father(father) when :mother raise LineageGapException, "Can't add maternal halfsiblings without a mother" unless mother sib.add_father(options[:spouse]) if options[:spouse] sib.add_mother(mother) when nil raise LineageGapException, "Can't add siblings without parents" unless father and mother sib.add_father(father) sib.add_mother(mother) else raise ArgumentError, "Admitted values for :half options are: :father, :mother or nil" end end end end
ruby
def add_siblings(*args) options = args.extract_options! case options[:half] when :father check_incompatible_relationship(:paternal_half_sibling, *args) when :mother check_incompatible_relationship(:maternal_half_sibling, *args) when nil check_incompatible_relationship(:sibling, *args) end transaction do args.inject(true) do |res,sib| res &= case options[:half] when :father raise LineageGapException, "Can't add paternal halfsiblings without a father" unless father sib.add_mother(options[:spouse]) if options[:spouse] sib.add_father(father) when :mother raise LineageGapException, "Can't add maternal halfsiblings without a mother" unless mother sib.add_father(options[:spouse]) if options[:spouse] sib.add_mother(mother) when nil raise LineageGapException, "Can't add siblings without parents" unless father and mother sib.add_father(father) sib.add_mother(mother) else raise ArgumentError, "Admitted values for :half options are: :father, :mother or nil" end end end end
[ "def", "add_siblings", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "case", "options", "[", ":half", "]", "when", ":father", "check_incompatible_relationship", "(", ":paternal_half_sibling", ",", "args", ")", "when", ":mother", "check_incompatible_relationship", "(", ":maternal_half_sibling", ",", "args", ")", "when", "nil", "check_incompatible_relationship", "(", ":sibling", ",", "args", ")", "end", "transaction", "do", "args", ".", "inject", "(", "true", ")", "do", "|", "res", ",", "sib", "|", "res", "&=", "case", "options", "[", ":half", "]", "when", ":father", "raise", "LineageGapException", ",", "\"Can't add paternal halfsiblings without a father\"", "unless", "father", "sib", ".", "add_mother", "(", "options", "[", ":spouse", "]", ")", "if", "options", "[", ":spouse", "]", "sib", ".", "add_father", "(", "father", ")", "when", ":mother", "raise", "LineageGapException", ",", "\"Can't add maternal halfsiblings without a mother\"", "unless", "mother", "sib", ".", "add_father", "(", "options", "[", ":spouse", "]", ")", "if", "options", "[", ":spouse", "]", "sib", ".", "add_mother", "(", "mother", ")", "when", "nil", "raise", "LineageGapException", ",", "\"Can't add siblings without parents\"", "unless", "father", "and", "mother", "sib", ".", "add_father", "(", "father", ")", "sib", ".", "add_mother", "(", "mother", ")", "else", "raise", "ArgumentError", ",", "\"Admitted values for :half options are: :father, :mother or nil\"", "end", "end", "end", "end" ]
add siblings by assigning same parents to individuals passed as arguments @overload add_siblings(*siblings,options={}) @param [Object] siblings list of siblings @param [Hash] options @option options [Symbol] half :father for paternal half siblings and :mother for maternal half siblings @option options [Object] spouse if specified, passed individual will be used as mother in case of half sibling @return [Boolean]
[ "add", "siblings", "by", "assigning", "same", "parents", "to", "individuals", "passed", "as", "arguments" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/alter_methods.rb#L176-L207
1,579
masciugo/genealogy
lib/genealogy/alter_methods.rb
Genealogy.AlterMethods.remove_siblings
def remove_siblings(*args) options = args.extract_options! raise ArgumentError.new("Unknown option value: half: #{options[:half]}.") if (options[:half] and ![:father,:mother].include?(options[:half])) resulting_indivs = if args.blank? siblings(options) else args & siblings(options) end transaction do resulting_indivs.each do |sib| case options[:half] when :father sib.remove_father sib.remove_mother if options[:remove_other_parent] == true when :mother sib.remove_father if options[:remove_other_parent] == true sib.remove_mother when nil sib.remove_parents end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
ruby
def remove_siblings(*args) options = args.extract_options! raise ArgumentError.new("Unknown option value: half: #{options[:half]}.") if (options[:half] and ![:father,:mother].include?(options[:half])) resulting_indivs = if args.blank? siblings(options) else args & siblings(options) end transaction do resulting_indivs.each do |sib| case options[:half] when :father sib.remove_father sib.remove_mother if options[:remove_other_parent] == true when :mother sib.remove_father if options[:remove_other_parent] == true sib.remove_mother when nil sib.remove_parents end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
[ "def", "remove_siblings", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "raise", "ArgumentError", ".", "new", "(", "\"Unknown option value: half: #{options[:half]}.\"", ")", "if", "(", "options", "[", ":half", "]", "and", "!", "[", ":father", ",", ":mother", "]", ".", "include?", "(", "options", "[", ":half", "]", ")", ")", "resulting_indivs", "=", "if", "args", ".", "blank?", "siblings", "(", "options", ")", "else", "args", "&", "siblings", "(", "options", ")", "end", "transaction", "do", "resulting_indivs", ".", "each", "do", "|", "sib", "|", "case", "options", "[", ":half", "]", "when", ":father", "sib", ".", "remove_father", "sib", ".", "remove_mother", "if", "options", "[", ":remove_other_parent", "]", "==", "true", "when", ":mother", "sib", ".", "remove_father", "if", "options", "[", ":remove_other_parent", "]", "==", "true", "sib", ".", "remove_mother", "when", "nil", "sib", ".", "remove_parents", "end", "end", "end", "!", "resulting_indivs", ".", "empty?", "#returned value must be true if self has at least a siblings to affect", "end" ]
remove siblings by nullifying parents of passed individuals @overload remove_siblings(*siblings,options={}) @param [Object] siblings list of siblings @param [Hash] options @option options [Symbol] half :father for paternal half siblings and :mother for maternal half siblings @option options [Boolean] remove_other_parent if specified, passed individuals' mother will also be nullified @return [Boolean] true if at least one sibling was affected, false otherwise
[ "remove", "siblings", "by", "nullifying", "parents", "of", "passed", "individuals" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/alter_methods.rb#L238-L261
1,580
masciugo/genealogy
lib/genealogy/alter_methods.rb
Genealogy.AlterMethods.add_children
def add_children(*args) options = args.extract_options! raise_if_sex_undefined check_incompatible_relationship(:children, *args) transaction do args.inject(true) do |res,child| res &= case sex_before_type_cast when gclass.sex_male_value child.add_mother(options[:spouse]) if options[:spouse] child.add_father(self) when gclass.sex_female_value child.add_father(options[:spouse]) if options[:spouse] child.add_mother(self) else raise SexError, "Sex value not valid for #{self}" end end end end
ruby
def add_children(*args) options = args.extract_options! raise_if_sex_undefined check_incompatible_relationship(:children, *args) transaction do args.inject(true) do |res,child| res &= case sex_before_type_cast when gclass.sex_male_value child.add_mother(options[:spouse]) if options[:spouse] child.add_father(self) when gclass.sex_female_value child.add_father(options[:spouse]) if options[:spouse] child.add_mother(self) else raise SexError, "Sex value not valid for #{self}" end end end end
[ "def", "add_children", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "raise_if_sex_undefined", "check_incompatible_relationship", "(", ":children", ",", "args", ")", "transaction", "do", "args", ".", "inject", "(", "true", ")", "do", "|", "res", ",", "child", "|", "res", "&=", "case", "sex_before_type_cast", "when", "gclass", ".", "sex_male_value", "child", ".", "add_mother", "(", "options", "[", ":spouse", "]", ")", "if", "options", "[", ":spouse", "]", "child", ".", "add_father", "(", "self", ")", "when", "gclass", ".", "sex_female_value", "child", ".", "add_father", "(", "options", "[", ":spouse", "]", ")", "if", "options", "[", ":spouse", "]", "child", ".", "add_mother", "(", "self", ")", "else", "raise", "SexError", ",", "\"Sex value not valid for #{self}\"", "end", "end", "end", "end" ]
add children by assigning self as parent @overload add_children(*children,options={}) @param [Object] children list of children @param [Hash] options @option options [Object] spouse if specified, children will have that spouse @return [Boolean]
[ "add", "children", "by", "assigning", "self", "as", "parent" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/alter_methods.rb#L292-L310
1,581
masciugo/genealogy
lib/genealogy/alter_methods.rb
Genealogy.AlterMethods.remove_children
def remove_children(*args) options = args.extract_options! raise_if_sex_undefined resulting_indivs = if args.blank? children(options) else args & children(options) end transaction do resulting_indivs.each do |child| if options[:remove_other_parent] == true child.remove_parents else case sex_before_type_cast when gclass.sex_male_value child.remove_father when gclass.sex_female_value child.remove_mother else raise SexError, "Sex value not valid for #{self}" end end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
ruby
def remove_children(*args) options = args.extract_options! raise_if_sex_undefined resulting_indivs = if args.blank? children(options) else args & children(options) end transaction do resulting_indivs.each do |child| if options[:remove_other_parent] == true child.remove_parents else case sex_before_type_cast when gclass.sex_male_value child.remove_father when gclass.sex_female_value child.remove_mother else raise SexError, "Sex value not valid for #{self}" end end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
[ "def", "remove_children", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "raise_if_sex_undefined", "resulting_indivs", "=", "if", "args", ".", "blank?", "children", "(", "options", ")", "else", "args", "&", "children", "(", "options", ")", "end", "transaction", "do", "resulting_indivs", ".", "each", "do", "|", "child", "|", "if", "options", "[", ":remove_other_parent", "]", "==", "true", "child", ".", "remove_parents", "else", "case", "sex_before_type_cast", "when", "gclass", ".", "sex_male_value", "child", ".", "remove_father", "when", "gclass", ".", "sex_female_value", "child", ".", "remove_mother", "else", "raise", "SexError", ",", "\"Sex value not valid for #{self}\"", "end", "end", "end", "end", "!", "resulting_indivs", ".", "empty?", "#returned value must be true if self has at least a siblings to affect", "end" ]
remove children by nullifying the parent corresponding to self @overload remove_children(*children,options={}) @param [Object] children list of children @param [Hash] options @option options [Boolean] remove_other_parent if specified, passed individuals' mother will also be nullified @return [Boolean] true if at least one child was affected, false otherwise
[ "remove", "children", "by", "nullifying", "the", "parent", "corresponding", "to", "self" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/alter_methods.rb#L323-L351
1,582
masciugo/genealogy
lib/genealogy/current_spouse_methods.rb
Genealogy.CurrentSpouseMethods.add_current_spouse
def add_current_spouse(spouse) raise_unless_current_spouse_enabled check_incompatible_relationship(:current_spouse,spouse) if gclass.perform_validation_enabled self.current_spouse = spouse spouse.current_spouse = self transaction do spouse.save! save! end else transaction do self.update_attribute(:current_spouse,spouse) spouse.update_attribute(:current_spouse,self) end end end
ruby
def add_current_spouse(spouse) raise_unless_current_spouse_enabled check_incompatible_relationship(:current_spouse,spouse) if gclass.perform_validation_enabled self.current_spouse = spouse spouse.current_spouse = self transaction do spouse.save! save! end else transaction do self.update_attribute(:current_spouse,spouse) spouse.update_attribute(:current_spouse,self) end end end
[ "def", "add_current_spouse", "(", "spouse", ")", "raise_unless_current_spouse_enabled", "check_incompatible_relationship", "(", ":current_spouse", ",", "spouse", ")", "if", "gclass", ".", "perform_validation_enabled", "self", ".", "current_spouse", "=", "spouse", "spouse", ".", "current_spouse", "=", "self", "transaction", "do", "spouse", ".", "save!", "save!", "end", "else", "transaction", "do", "self", ".", "update_attribute", "(", ":current_spouse", ",", "spouse", ")", "spouse", ".", "update_attribute", "(", ":current_spouse", ",", "self", ")", "end", "end", "end" ]
add current spouse updating receiver and argument individuals foreign_key in a transaction @param [Object] spouse @return [Boolean]
[ "add", "current", "spouse", "updating", "receiver", "and", "argument", "individuals", "foreign_key", "in", "a", "transaction" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/current_spouse_methods.rb#L11-L30
1,583
masciugo/genealogy
lib/genealogy/current_spouse_methods.rb
Genealogy.CurrentSpouseMethods.remove_current_spouse
def remove_current_spouse raise_unless_current_spouse_enabled if gclass.perform_validation_enabled ex_current_spouse = current_spouse current_spouse.current_spouse = nil self.current_spouse = nil transaction do ex_current_spouse.save! save! end else transaction do current_spouse.update_attribute(:current_spouse,nil) self.update_attribute(:current_spouse,nil) end end end
ruby
def remove_current_spouse raise_unless_current_spouse_enabled if gclass.perform_validation_enabled ex_current_spouse = current_spouse current_spouse.current_spouse = nil self.current_spouse = nil transaction do ex_current_spouse.save! save! end else transaction do current_spouse.update_attribute(:current_spouse,nil) self.update_attribute(:current_spouse,nil) end end end
[ "def", "remove_current_spouse", "raise_unless_current_spouse_enabled", "if", "gclass", ".", "perform_validation_enabled", "ex_current_spouse", "=", "current_spouse", "current_spouse", ".", "current_spouse", "=", "nil", "self", ".", "current_spouse", "=", "nil", "transaction", "do", "ex_current_spouse", ".", "save!", "save!", "end", "else", "transaction", "do", "current_spouse", ".", "update_attribute", "(", ":current_spouse", ",", "nil", ")", "self", ".", "update_attribute", "(", ":current_spouse", ",", "nil", ")", "end", "end", "end" ]
remove current spouse resetting receiver and argument individuals foreign_key in a transaction @return [Boolean]
[ "remove", "current", "spouse", "resetting", "receiver", "and", "argument", "individuals", "foreign_key", "in", "a", "transaction" ]
e29eeb1d63cd352d52abf1819ec21659364f90a7
https://github.com/masciugo/genealogy/blob/e29eeb1d63cd352d52abf1819ec21659364f90a7/lib/genealogy/current_spouse_methods.rb#L34-L50
1,584
paddor/cztop
lib/cztop/poller/zpoller.rb
CZTop.Poller::ZPoller.add
def add(reader) rc = ffi_delegate.add(reader) raise_zmq_err("unable to add socket %p" % reader) if rc == -1 remember_socket(reader) end
ruby
def add(reader) rc = ffi_delegate.add(reader) raise_zmq_err("unable to add socket %p" % reader) if rc == -1 remember_socket(reader) end
[ "def", "add", "(", "reader", ")", "rc", "=", "ffi_delegate", ".", "add", "(", "reader", ")", "raise_zmq_err", "(", "\"unable to add socket %p\"", "%", "reader", ")", "if", "rc", "==", "-", "1", "remember_socket", "(", "reader", ")", "end" ]
Initializes the Poller. At least one reader has to be given. @param reader [Socket, Actor] socket to poll for input @param readers [Socket, Actor] any additional sockets to poll for input Adds another reader socket to the poller. @param reader [Socket, Actor] socket to poll for input @return [void] @raise [SystemCallError] if this fails
[ "Initializes", "the", "Poller", ".", "At", "least", "one", "reader", "has", "to", "be", "given", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/poller/zpoller.rb#L29-L33
1,585
paddor/cztop
lib/cztop/poller/zpoller.rb
CZTop.Poller::ZPoller.remove
def remove(reader) rc = ffi_delegate.remove(reader) raise_zmq_err("unable to remove socket %p" % reader) if rc == -1 forget_socket(reader) end
ruby
def remove(reader) rc = ffi_delegate.remove(reader) raise_zmq_err("unable to remove socket %p" % reader) if rc == -1 forget_socket(reader) end
[ "def", "remove", "(", "reader", ")", "rc", "=", "ffi_delegate", ".", "remove", "(", "reader", ")", "raise_zmq_err", "(", "\"unable to remove socket %p\"", "%", "reader", ")", "if", "rc", "==", "-", "1", "forget_socket", "(", "reader", ")", "end" ]
Removes a reader socket from the poller. @param reader [Socket, Actor] socket to remove @return [void] @raise [ArgumentError] if socket was invalid, e.g. it wasn't registered in this poller @raise [SystemCallError] if this fails for another reason
[ "Removes", "a", "reader", "socket", "from", "the", "poller", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/poller/zpoller.rb#L41-L45
1,586
paddor/cztop
lib/cztop/poller/zpoller.rb
CZTop.Poller::ZPoller.wait
def wait(timeout = -1) ptr = ffi_delegate.wait(timeout) if ptr.null? raise Interrupt if ffi_delegate.terminated return nil end return socket_by_ptr(ptr) end
ruby
def wait(timeout = -1) ptr = ffi_delegate.wait(timeout) if ptr.null? raise Interrupt if ffi_delegate.terminated return nil end return socket_by_ptr(ptr) end
[ "def", "wait", "(", "timeout", "=", "-", "1", ")", "ptr", "=", "ffi_delegate", ".", "wait", "(", "timeout", ")", "if", "ptr", ".", "null?", "raise", "Interrupt", "if", "ffi_delegate", ".", "terminated", "return", "nil", "end", "return", "socket_by_ptr", "(", "ptr", ")", "end" ]
Waits and returns the first socket that becomes readable. @param timeout [Integer] how long to wait in ms, or 0 to avoid blocking, or -1 to wait indefinitely @return [Socket, Actor] first socket of interest @return [nil] if the timeout expired or @raise [Interrupt] if the timeout expired or
[ "Waits", "and", "returns", "the", "first", "socket", "that", "becomes", "readable", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/poller/zpoller.rb#L53-L60
1,587
mtuchowski/mdspell
lib/mdspell/spell_checker.rb
MdSpell.SpellChecker.typos
def typos results = [] FFI::Aspell::Speller.open(Configuration[:language]) do |speller| TextLine.scan(document).each do |line| line.words.each do |word| next if ignored? word unless speller.correct? word results << Typo.new(line, word, speller.suggestions(word)) end end end end results end
ruby
def typos results = [] FFI::Aspell::Speller.open(Configuration[:language]) do |speller| TextLine.scan(document).each do |line| line.words.each do |word| next if ignored? word unless speller.correct? word results << Typo.new(line, word, speller.suggestions(word)) end end end end results end
[ "def", "typos", "results", "=", "[", "]", "FFI", "::", "Aspell", "::", "Speller", ".", "open", "(", "Configuration", "[", ":language", "]", ")", "do", "|", "speller", "|", "TextLine", ".", "scan", "(", "document", ")", ".", "each", "do", "|", "line", "|", "line", ".", "words", ".", "each", "do", "|", "word", "|", "next", "if", "ignored?", "word", "unless", "speller", ".", "correct?", "word", "results", "<<", "Typo", ".", "new", "(", "line", ",", "word", ",", "speller", ".", "suggestions", "(", "word", ")", ")", "end", "end", "end", "end", "results", "end" ]
Create a new instance from specified file. @param filename [String] a name of file to load. Returns found spelling errors.
[ "Create", "a", "new", "instance", "from", "specified", "file", "." ]
d8232366bbe12261a1e3a7763b0c8aa925d82b85
https://github.com/mtuchowski/mdspell/blob/d8232366bbe12261a1e3a7763b0c8aa925d82b85/lib/mdspell/spell_checker.rb#L30-L44
1,588
hawkular/hawkular-client-ruby
lib/hawkular/metrics/metric_api.rb
Hawkular::Metrics.Client.data_by_tags
def data_by_tags(tags, buckets: nil, bucketDuration: nil, # rubocop:disable Naming/VariableName start: nil, ends: nil) data = { tags: tags_param(tags), buckets: buckets, bucketDuration: bucketDuration, start: start, end: ends } http_post('metrics/stats/query', data) end
ruby
def data_by_tags(tags, buckets: nil, bucketDuration: nil, # rubocop:disable Naming/VariableName start: nil, ends: nil) data = { tags: tags_param(tags), buckets: buckets, bucketDuration: bucketDuration, start: start, end: ends } http_post('metrics/stats/query', data) end
[ "def", "data_by_tags", "(", "tags", ",", "buckets", ":", "nil", ",", "bucketDuration", ":", "nil", ",", "# rubocop:disable Naming/VariableName", "start", ":", "nil", ",", "ends", ":", "nil", ")", "data", "=", "{", "tags", ":", "tags_param", "(", "tags", ")", ",", "buckets", ":", "buckets", ",", "bucketDuration", ":", "bucketDuration", ",", "start", ":", "start", ",", "end", ":", "ends", "}", "http_post", "(", "'metrics/stats/query'", ",", "data", ")", "end" ]
Retrieve all types of metrics datapoints by tags @param tags [Hash] @param buckets [Integer] optional number of buckets @param bucketDuration [String] optional interval (default no aggregation) @param starts [Integer] optional timestamp (default now - 8h) @param ends [Integer] optional timestamp (default now) @return [Array[Hash]] datapoints
[ "Retrieve", "all", "types", "of", "metrics", "datapoints", "by", "tags" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/metrics/metric_api.rb#L26-L33
1,589
hawkular/hawkular-client-ruby
lib/hawkular/metrics/metric_api.rb
Hawkular::Metrics.Client.push_data
def push_data(gauges: [], counters: [], availabilities: [], strings: []) gauges.each { |g| default_timestamp g[:data] } counters.each { |g| default_timestamp g[:data] } availabilities.each { |g| default_timestamp g[:data] } strings.each { |g| default_timestamp g[:data] } data = { gauges: gauges, counters: counters, availabilities: availabilities, strings: strings } path = '/metrics/' path << (@legacy_api ? 'data' : 'raw') http_post(path, data) end
ruby
def push_data(gauges: [], counters: [], availabilities: [], strings: []) gauges.each { |g| default_timestamp g[:data] } counters.each { |g| default_timestamp g[:data] } availabilities.each { |g| default_timestamp g[:data] } strings.each { |g| default_timestamp g[:data] } data = { gauges: gauges, counters: counters, availabilities: availabilities, strings: strings } path = '/metrics/' path << (@legacy_api ? 'data' : 'raw') http_post(path, data) end
[ "def", "push_data", "(", "gauges", ":", "[", "]", ",", "counters", ":", "[", "]", ",", "availabilities", ":", "[", "]", ",", "strings", ":", "[", "]", ")", "gauges", ".", "each", "{", "|", "g", "|", "default_timestamp", "g", "[", ":data", "]", "}", "counters", ".", "each", "{", "|", "g", "|", "default_timestamp", "g", "[", ":data", "]", "}", "availabilities", ".", "each", "{", "|", "g", "|", "default_timestamp", "g", "[", ":data", "]", "}", "strings", ".", "each", "{", "|", "g", "|", "default_timestamp", "g", "[", ":data", "]", "}", "data", "=", "{", "gauges", ":", "gauges", ",", "counters", ":", "counters", ",", "availabilities", ":", "availabilities", ",", "strings", ":", "strings", "}", "path", "=", "'/metrics/'", "path", "<<", "(", "@legacy_api", "?", "'data'", ":", "'raw'", ")", "http_post", "(", "path", ",", "data", ")", "end" ]
Push data for multiple metrics of all supported types @param gauges [Array] @param counters [Array] @param availabilities [Array] @example push datapoints of 2 counter metrics client = Hawkular::Metrics::client::new client.push_data(counters: [{:id => "counter1", :data => [{:value => 1}, {:value => 2}]}, {:id => "counter2", :data => [{:value => 1}, {:value => 3}]}]) @example push gauge and availability datapoints client.push_data(gauges: [{:id => "gauge1", :data => [{:value => 1}, {:value => 2}]}], availabilities: [{:id => "avail1", :data => [{:value => "up"}]}])
[ "Push", "data", "for", "multiple", "metrics", "of", "all", "supported", "types" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/metrics/metric_api.rb#L53-L62
1,590
hawkular/hawkular-client-ruby
lib/hawkular/metrics/metric_api.rb
Hawkular::Metrics.Client.query_stats
def query_stats(gauge_ids: [], counter_ids: [], avail_ids: [], rates: false, starts: nil, ends: nil, bucket_duration: '3600s') path = '/metrics/stats/query' metrics = { gauge: gauge_ids, counter: counter_ids, availability: avail_ids } data = { metrics: metrics, start: starts, end: ends, bucketDuration: bucket_duration } data['types'] = %w[gauge gauge_rate counter counter_rate availability] if rates http_post(path, data) end
ruby
def query_stats(gauge_ids: [], counter_ids: [], avail_ids: [], rates: false, starts: nil, ends: nil, bucket_duration: '3600s') path = '/metrics/stats/query' metrics = { gauge: gauge_ids, counter: counter_ids, availability: avail_ids } data = { metrics: metrics, start: starts, end: ends, bucketDuration: bucket_duration } data['types'] = %w[gauge gauge_rate counter counter_rate availability] if rates http_post(path, data) end
[ "def", "query_stats", "(", "gauge_ids", ":", "[", "]", ",", "counter_ids", ":", "[", "]", ",", "avail_ids", ":", "[", "]", ",", "rates", ":", "false", ",", "starts", ":", "nil", ",", "ends", ":", "nil", ",", "bucket_duration", ":", "'3600s'", ")", "path", "=", "'/metrics/stats/query'", "metrics", "=", "{", "gauge", ":", "gauge_ids", ",", "counter", ":", "counter_ids", ",", "availability", ":", "avail_ids", "}", "data", "=", "{", "metrics", ":", "metrics", ",", "start", ":", "starts", ",", "end", ":", "ends", ",", "bucketDuration", ":", "bucket_duration", "}", "data", "[", "'types'", "]", "=", "%w[", "gauge", "gauge_rate", "counter", "counter_rate", "availability", "]", "if", "rates", "http_post", "(", "path", ",", "data", ")", "end" ]
Fetch stats for multiple metrics of all supported types @param gauge_ids [Array[String]] list of gauge ids @param counter_ids [Array[String]] list of counter ids @param avail_ids [Array[String]] list of availability ids @param rates [Boolean] flag to include rates for gauges and counters metrics @param starts [Integer] optional timestamp (default now - 8h) @param ends [Integer] optional timestamp (default now) @param bucket_duration [String] optional interval (default 3600s) @return [Hash] stats grouped per type @example client = Hawkular::Metrics::client::new client.query_stats( gauge_ids: ['G1', 'G2'], counter_ids: ['C2', 'C3'], avail_ids: ['A2', 'A3'], starts: 200, ends: 500, bucket_duration: '150ms' )
[ "Fetch", "stats", "for", "multiple", "metrics", "of", "all", "supported", "types" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/metrics/metric_api.rb#L83-L90
1,591
hawkular/hawkular-client-ruby
lib/hawkular/metrics/metric_api.rb
Hawkular::Metrics.Client.tags
def tags tags = [] http_get('/metrics/').map do |g| next if g['tags'].nil? g['tags'].map do |k, v| tags << { k => v } end end tags.uniq! end
ruby
def tags tags = [] http_get('/metrics/').map do |g| next if g['tags'].nil? g['tags'].map do |k, v| tags << { k => v } end end tags.uniq! end
[ "def", "tags", "tags", "=", "[", "]", "http_get", "(", "'/metrics/'", ")", ".", "map", "do", "|", "g", "|", "next", "if", "g", "[", "'tags'", "]", ".", "nil?", "g", "[", "'tags'", "]", ".", "map", "do", "|", "k", ",", "v", "|", "tags", "<<", "{", "k", "=>", "v", "}", "end", "end", "tags", ".", "uniq!", "end" ]
Fetch all tags for metrics definitions @return [Hash{String=>String}]
[ "Fetch", "all", "tags", "for", "metrics", "definitions" ]
3b07729c2ab359e3199c282e199a3f1699ddc49c
https://github.com/hawkular/hawkular-client-ruby/blob/3b07729c2ab359e3199c282e199a3f1699ddc49c/lib/hawkular/metrics/metric_api.rb#L94-L104
1,592
bfoz/geometry
lib/geometry/polygon.rb
Geometry.Polygon.outset_bisectors
def outset_bisectors(length) vertices.zip(spokes).map {|v,b| b ? Edge.new(v, v+(b * length)) : nil} end
ruby
def outset_bisectors(length) vertices.zip(spokes).map {|v,b| b ? Edge.new(v, v+(b * length)) : nil} end
[ "def", "outset_bisectors", "(", "length", ")", "vertices", ".", "zip", "(", "spokes", ")", ".", "map", "{", "|", "v", ",", "b", "|", "b", "?", "Edge", ".", "new", "(", "v", ",", "v", "+", "(", "b", "*", "length", ")", ")", ":", "nil", "}", "end" ]
Vertex bisectors suitable for outsetting @param [Number] length The distance to offset by @return [Array<Edge>] {Edge}s representing the bisectors
[ "Vertex", "bisectors", "suitable", "for", "outsetting" ]
3054ccba59f184c172be52a6f0b7cf4a33f617a5
https://github.com/bfoz/geometry/blob/3054ccba59f184c172be52a6f0b7cf4a33f617a5/lib/geometry/polygon.rb#L287-L289
1,593
apotonick/declarative
lib/declarative/defaults.rb
Declarative.Defaults.call
def call(name, given_options) # TODO: allow to receive rest of options/block in dynamic block. or, rather, test it as it was already implemented. evaluated_options = @dynamic_options.(name, given_options) options = Variables.merge( @static_options, handle_array_and_deprecate(evaluated_options) ) options = Variables.merge( options, handle_array_and_deprecate(given_options) ) # FIXME: given_options is not tested! end
ruby
def call(name, given_options) # TODO: allow to receive rest of options/block in dynamic block. or, rather, test it as it was already implemented. evaluated_options = @dynamic_options.(name, given_options) options = Variables.merge( @static_options, handle_array_and_deprecate(evaluated_options) ) options = Variables.merge( options, handle_array_and_deprecate(given_options) ) # FIXME: given_options is not tested! end
[ "def", "call", "(", "name", ",", "given_options", ")", "# TODO: allow to receive rest of options/block in dynamic block. or, rather, test it as it was already implemented.", "evaluated_options", "=", "@dynamic_options", ".", "(", "name", ",", "given_options", ")", "options", "=", "Variables", ".", "merge", "(", "@static_options", ",", "handle_array_and_deprecate", "(", "evaluated_options", ")", ")", "options", "=", "Variables", ".", "merge", "(", "options", ",", "handle_array_and_deprecate", "(", "given_options", ")", ")", "# FIXME: given_options is not tested!", "end" ]
Evaluate defaults and merge given_options into them.
[ "Evaluate", "defaults", "and", "merge", "given_options", "into", "them", "." ]
927ecf53fd9b94b85be29a5a0bab115057ecee9b
https://github.com/apotonick/declarative/blob/927ecf53fd9b94b85be29a5a0bab115057ecee9b/lib/declarative/defaults.rb#L20-L26
1,594
paddor/cztop
lib/cztop/certificate.rb
CZTop.Certificate.[]=
def []=(key, value) if value ffi_delegate.set_meta(key, "%s", :string, value) else ffi_delegate.unset_meta(key) end end
ruby
def []=(key, value) if value ffi_delegate.set_meta(key, "%s", :string, value) else ffi_delegate.unset_meta(key) end end
[ "def", "[]=", "(", "key", ",", "value", ")", "if", "value", "ffi_delegate", ".", "set_meta", "(", "key", ",", "\"%s\"", ",", ":string", ",", "value", ")", "else", "ffi_delegate", ".", "unset_meta", "(", "key", ")", "end", "end" ]
Set metadata. @param key [String] metadata key @param value [String] metadata value @return [value]
[ "Set", "metadata", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/certificate.rb#L97-L103
1,595
paddor/cztop
lib/cztop/certificate.rb
CZTop.Certificate.meta_keys
def meta_keys zlist = ffi_delegate.meta_keys first_key = zlist.first return [] if first_key.null? keys = [first_key.read_string] while key = zlist.next break if key.null? keys << key.read_string end keys end
ruby
def meta_keys zlist = ffi_delegate.meta_keys first_key = zlist.first return [] if first_key.null? keys = [first_key.read_string] while key = zlist.next break if key.null? keys << key.read_string end keys end
[ "def", "meta_keys", "zlist", "=", "ffi_delegate", ".", "meta_keys", "first_key", "=", "zlist", ".", "first", "return", "[", "]", "if", "first_key", ".", "null?", "keys", "=", "[", "first_key", ".", "read_string", "]", "while", "key", "=", "zlist", ".", "next", "break", "if", "key", ".", "null?", "keys", "<<", "key", ".", "read_string", "end", "keys", "end" ]
Returns meta keys set. @return [Array<String>]
[ "Returns", "meta", "keys", "set", "." ]
d20ee44775d05b60f40fffd1287a9b01270ab853
https://github.com/paddor/cztop/blob/d20ee44775d05b60f40fffd1287a9b01270ab853/lib/cztop/certificate.rb#L107-L117
1,596
mynameisrufus/sorted
lib/sorted/set.rb
Sorted.Set.direction_intersect
def direction_intersect(other_set) self.class.new.tap do |memo| unless other_set.keys.empty? a(memo, other_set) b(memo, other_set) end c(memo) d(memo, other_set) end end
ruby
def direction_intersect(other_set) self.class.new.tap do |memo| unless other_set.keys.empty? a(memo, other_set) b(memo, other_set) end c(memo) d(memo, other_set) end end
[ "def", "direction_intersect", "(", "other_set", ")", "self", ".", "class", ".", "new", ".", "tap", "do", "|", "memo", "|", "unless", "other_set", ".", "keys", ".", "empty?", "a", "(", "memo", ",", "other_set", ")", "b", "(", "memo", ",", "other_set", ")", "end", "c", "(", "memo", ")", "d", "(", "memo", ",", "other_set", ")", "end", "end" ]
Returns a new array containing elements common to the two arrays, excluding any duplicates. Any matching keys at matching indexes with the same order will have the order reversed. a = Sorted::Set.new([['email', 'asc'], ['name', 'asc']]) b = Sorted::Set.new([['email', 'asc'], ['phone', 'asc']]) s = a.direction_intersect(b) s.to_a #=> [['email', 'desc'], ['phone', 'asc'], ['name', 'asc']]
[ "Returns", "a", "new", "array", "containing", "elements", "common", "to", "the", "two", "arrays", "excluding", "any", "duplicates", "." ]
6490682f7970e27b692ff0c931f04cf86a52ec0a
https://github.com/mynameisrufus/sorted/blob/6490682f7970e27b692ff0c931f04cf86a52ec0a/lib/sorted/set.rb#L43-L52
1,597
mynameisrufus/sorted
lib/sorted/set.rb
Sorted.Set.-
def -(other_set) self.class.new.tap do |memo| each do |a| b = other_set.assoc(a.first) next if b memo << a end end end
ruby
def -(other_set) self.class.new.tap do |memo| each do |a| b = other_set.assoc(a.first) next if b memo << a end end end
[ "def", "-", "(", "other_set", ")", "self", ".", "class", ".", "new", ".", "tap", "do", "|", "memo", "|", "each", "do", "|", "a", "|", "b", "=", "other_set", ".", "assoc", "(", "a", ".", "first", ")", "next", "if", "b", "memo", "<<", "a", "end", "end", "end" ]
Array Difference - Returns a new set that is a copy of the original set, removing any items that also appear in +other_set+. The order is preserved from the original set. set = Sorted::Set.new(['email', 'desc']) other_set = Sorted::Set.new(['phone', 'asc']) set - other_set #=> #<Sorted::Set:0x007fafde1ead80>
[ "Array", "Difference", "-", "Returns", "a", "new", "set", "that", "is", "a", "copy", "of", "the", "original", "set", "removing", "any", "items", "that", "also", "appear", "in", "+", "other_set", "+", ".", "The", "order", "is", "preserved", "from", "the", "original", "set", "." ]
6490682f7970e27b692ff0c931f04cf86a52ec0a
https://github.com/mynameisrufus/sorted/blob/6490682f7970e27b692ff0c931f04cf86a52ec0a/lib/sorted/set.rb#L63-L71
1,598
mynameisrufus/sorted
lib/sorted/set.rb
Sorted.Set.a
def a(memo, other) if keys == other.keys.take(keys.size) keys.each do |order| if other.keys.include?(order) memo << [order, flip_direction(other.assoc(order).last)] end end else keys.each do |order| if other.keys.include?(order) memo << other.assoc(order) end end end end
ruby
def a(memo, other) if keys == other.keys.take(keys.size) keys.each do |order| if other.keys.include?(order) memo << [order, flip_direction(other.assoc(order).last)] end end else keys.each do |order| if other.keys.include?(order) memo << other.assoc(order) end end end end
[ "def", "a", "(", "memo", ",", "other", ")", "if", "keys", "==", "other", ".", "keys", ".", "take", "(", "keys", ".", "size", ")", "keys", ".", "each", "do", "|", "order", "|", "if", "other", ".", "keys", ".", "include?", "(", "order", ")", "memo", "<<", "[", "order", ",", "flip_direction", "(", "other", ".", "assoc", "(", "order", ")", ".", "last", ")", "]", "end", "end", "else", "keys", ".", "each", "do", "|", "order", "|", "if", "other", ".", "keys", ".", "include?", "(", "order", ")", "memo", "<<", "other", ".", "assoc", "(", "order", ")", "end", "end", "end", "end" ]
If the order of keys match upto the size of the set then flip them
[ "If", "the", "order", "of", "keys", "match", "upto", "the", "size", "of", "the", "set", "then", "flip", "them" ]
6490682f7970e27b692ff0c931f04cf86a52ec0a
https://github.com/mynameisrufus/sorted/blob/6490682f7970e27b692ff0c931f04cf86a52ec0a/lib/sorted/set.rb#L188-L202
1,599
mynameisrufus/sorted
lib/sorted/set.rb
Sorted.Set.b
def b(memo, other) other.keys.each do |sort| if keys.include?(sort) && !memo.keys.include?(sort) memo << other.assoc(sort) end end end
ruby
def b(memo, other) other.keys.each do |sort| if keys.include?(sort) && !memo.keys.include?(sort) memo << other.assoc(sort) end end end
[ "def", "b", "(", "memo", ",", "other", ")", "other", ".", "keys", ".", "each", "do", "|", "sort", "|", "if", "keys", ".", "include?", "(", "sort", ")", "&&", "!", "memo", ".", "keys", ".", "include?", "(", "sort", ")", "memo", "<<", "other", ".", "assoc", "(", "sort", ")", "end", "end", "end" ]
Add items from other that are common and not already added
[ "Add", "items", "from", "other", "that", "are", "common", "and", "not", "already", "added" ]
6490682f7970e27b692ff0c931f04cf86a52ec0a
https://github.com/mynameisrufus/sorted/blob/6490682f7970e27b692ff0c931f04cf86a52ec0a/lib/sorted/set.rb#L205-L211