repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
pagseguro/ruby
lib/pagseguro/authorization_request.rb
PagSeguro.AuthorizationRequest.create
def create request = Request.post_xml('authorizations/request', api_version, credentials, xml) response = Response.new(request) update_attributes(response.serialize) response.success? end
ruby
def create request = Request.post_xml('authorizations/request', api_version, credentials, xml) response = Response.new(request) update_attributes(response.serialize) response.success? end
[ "def", "create", "request", "=", "Request", ".", "post_xml", "(", "'authorizations/request'", ",", "api_version", ",", "credentials", ",", "xml", ")", "response", "=", "Response", ".", "new", "(", "request", ")", "update_attributes", "(", "response", ".", "serialize", ")", "response", ".", "success?", "end" ]
Post and create an Authorization. Return Boolean.
[ "Post", "and", "create", "an", "Authorization", ".", "Return", "Boolean", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/authorization_request.rb#L48-L54
train
pagseguro/ruby
lib/pagseguro/items.rb
PagSeguro.Items.<<
def <<(item) item = ensure_type(Item, item) original_item = find_item(item) if original_item original_item.quantity += (item.quantity || 1) else store << item end end
ruby
def <<(item) item = ensure_type(Item, item) original_item = find_item(item) if original_item original_item.quantity += (item.quantity || 1) else store << item end end
[ "def", "<<", "(", "item", ")", "item", "=", "ensure_type", "(", "Item", ",", "item", ")", "original_item", "=", "find_item", "(", "item", ")", "if", "original_item", "original_item", ".", "quantity", "+=", "(", "item", ".", "quantity", "||", "1", ")", "else", "store", "<<", "item", "end", "end" ]
Overriding standard method to add new objects
[ "Overriding", "standard", "method", "to", "add", "new", "objects" ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/items.rb#L6-L16
train
pagseguro/ruby
lib/pagseguro/payment_request.rb
PagSeguro.PaymentRequest.register
def register request = if @receivers.empty? Request.post('checkout', api_version, params) else Request.post_xml('checkouts', api_version, credentials, xml_params) end Response.new(request) end
ruby
def register request = if @receivers.empty? Request.post('checkout', api_version, params) else Request.post_xml('checkouts', api_version, credentials, xml_params) end Response.new(request) end
[ "def", "register", "request", "=", "if", "@receivers", ".", "empty?", "Request", ".", "post", "(", "'checkout'", ",", "api_version", ",", "params", ")", "else", "Request", ".", "post_xml", "(", "'checkouts'", ",", "api_version", ",", "credentials", ",", "xml_params", ")", "end", "Response", ".", "new", "(", "request", ")", "end" ]
Calls the PagSeguro web service and register this request for payment.
[ "Calls", "the", "PagSeguro", "web", "service", "and", "register", "this", "request", "for", "payment", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/payment_request.rb#L87-L95
train
pagseguro/ruby
lib/pagseguro/transaction_request.rb
PagSeguro.TransactionRequest.create
def create request = if receivers.empty? Request.post('transactions', api_version, params) else Request.post_xml('transactions/', nil, credentials, xml_params) end Response.new(request, self).serialize end
ruby
def create request = if receivers.empty? Request.post('transactions', api_version, params) else Request.post_xml('transactions/', nil, credentials, xml_params) end Response.new(request, self).serialize end
[ "def", "create", "request", "=", "if", "receivers", ".", "empty?", "Request", ".", "post", "(", "'transactions'", ",", "api_version", ",", "params", ")", "else", "Request", ".", "post_xml", "(", "'transactions/'", ",", "nil", ",", "credentials", ",", "xml_params", ")", "end", "Response", ".", "new", "(", "request", ",", "self", ")", ".", "serialize", "end" ]
Calls the PagSeguro web service and create this request for payment. Return boolean.
[ "Calls", "the", "PagSeguro", "web", "service", "and", "create", "this", "request", "for", "payment", ".", "Return", "boolean", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/transaction_request.rb#L108-L116
train
pagseguro/ruby
lib/pagseguro/request.rb
PagSeguro.Request.get
def get(path, api_version, data = {}, headers = {}) execute :get, path, api_version, data, headers end
ruby
def get(path, api_version, data = {}, headers = {}) execute :get, path, api_version, data, headers end
[ "def", "get", "(", "path", ",", "api_version", ",", "data", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "execute", ":get", ",", "path", ",", "api_version", ",", "data", ",", "headers", "end" ]
Perform a GET request. # +path+: the path that will be requested. Must be something like <tt>"transactions/code/739D69-79C052C05280-55542D9FBB33-CAB2B1"</tt>. # +api_version+: the current PagSeguro API version of the requested service # +data+: the data that will be sent as query string. Must be a Hash. # +headers+: any additional header that will be sent through the request.
[ "Perform", "a", "GET", "request", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/request.rb#L17-L19
train
pagseguro/ruby
lib/pagseguro/request.rb
PagSeguro.Request.post
def post(path, api_version, data = {}, headers = {}) execute :post, path, api_version, data, headers end
ruby
def post(path, api_version, data = {}, headers = {}) execute :post, path, api_version, data, headers end
[ "def", "post", "(", "path", ",", "api_version", ",", "data", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "execute", ":post", ",", "path", ",", "api_version", ",", "data", ",", "headers", "end" ]
Perform a POST request. # +path+: the path that will be requested. Must be something like <tt>"checkout"</tt>. # +api_version+: the current PagSeguro API version of the requested service # +data+: the data that will be sent as body data. Must be a Hash. # +headers+: any additional header that will be sent through the request.
[ "Perform", "a", "POST", "request", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/request.rb#L39-L41
train
pagseguro/ruby
lib/pagseguro/request.rb
PagSeguro.Request.post_xml
def post_xml(path, api_version, credentials, data = '', options={}) credentials_params = credentials_to_params(credentials) url_path = [api_version, path].reject(&:nil?).join('/') request.post do url PagSeguro.api_url("#{url_path}?#{credentials_params}") headers "Content-Type" => "application/xml; charset=#{PagSeguro.encoding}" headers.merge!(options[:headers]) if options[:headers] body data end end
ruby
def post_xml(path, api_version, credentials, data = '', options={}) credentials_params = credentials_to_params(credentials) url_path = [api_version, path].reject(&:nil?).join('/') request.post do url PagSeguro.api_url("#{url_path}?#{credentials_params}") headers "Content-Type" => "application/xml; charset=#{PagSeguro.encoding}" headers.merge!(options[:headers]) if options[:headers] body data end end
[ "def", "post_xml", "(", "path", ",", "api_version", ",", "credentials", ",", "data", "=", "''", ",", "options", "=", "{", "}", ")", "credentials_params", "=", "credentials_to_params", "(", "credentials", ")", "url_path", "=", "[", "api_version", ",", "path", "]", ".", "reject", "(", ":nil?", ")", ".", "join", "(", "'/'", ")", "request", ".", "post", "do", "url", "PagSeguro", ".", "api_url", "(", "\"#{url_path}?#{credentials_params}\"", ")", "headers", "\"Content-Type\"", "=>", "\"application/xml; charset=#{PagSeguro.encoding}\"", "headers", ".", "merge!", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "body", "data", "end", "end" ]
Perform a POST request, sending XML data. # +path+: the path that will be requested. Must be something like <tt>"checkout"</tt>. # +api_version+: the current PagSeguro API version of the requested service # +credentials+: the credentials like ApplicationCredentials or AccountCredentials. # +data+: the data that will be sent as body data. Must be a XML.
[ "Perform", "a", "POST", "request", "sending", "XML", "data", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/request.rb#L50-L60
train
pagseguro/ruby
lib/pagseguro/request.rb
PagSeguro.Request.put_xml
def put_xml(path, credentials, data) full_url = PagSeguro.api_url("#{path}?#{credentials_to_params(credentials)}") request.put do url full_url headers "Content-Type" => "application/xml; charset=#{PagSeguro.encoding}", "Accept" => "application/vnd.pagseguro.com.br.v1+xml;charset=ISO-8859-1" body data end end
ruby
def put_xml(path, credentials, data) full_url = PagSeguro.api_url("#{path}?#{credentials_to_params(credentials)}") request.put do url full_url headers "Content-Type" => "application/xml; charset=#{PagSeguro.encoding}", "Accept" => "application/vnd.pagseguro.com.br.v1+xml;charset=ISO-8859-1" body data end end
[ "def", "put_xml", "(", "path", ",", "credentials", ",", "data", ")", "full_url", "=", "PagSeguro", ".", "api_url", "(", "\"#{path}?#{credentials_to_params(credentials)}\"", ")", "request", ".", "put", "do", "url", "full_url", "headers", "\"Content-Type\"", "=>", "\"application/xml; charset=#{PagSeguro.encoding}\"", ",", "\"Accept\"", "=>", "\"application/vnd.pagseguro.com.br.v1+xml;charset=ISO-8859-1\"", "body", "data", "end", "end" ]
Perform a PUT request, sending XML data. # +path+: the path that will be requested. Must be something like <tt>"checkout"</tt>. # +credentials+: the credentials like ApplicationCredentials or AccountCredentials. # +data+: the data that will be sent as body data. Must be a XML.
[ "Perform", "a", "PUT", "request", "sending", "XML", "data", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/request.rb#L68-L77
train
pagseguro/ruby
lib/pagseguro/request.rb
PagSeguro.Request.execute
def execute(request_method, path, api_version, data, headers) # :nodoc: request.public_send( request_method, PagSeguro.api_url("#{api_version}/#{path}"), extended_data(data), extended_headers(request_method, headers) ) end
ruby
def execute(request_method, path, api_version, data, headers) # :nodoc: request.public_send( request_method, PagSeguro.api_url("#{api_version}/#{path}"), extended_data(data), extended_headers(request_method, headers) ) end
[ "def", "execute", "(", "request_method", ",", "path", ",", "api_version", ",", "data", ",", "headers", ")", "# :nodoc:", "request", ".", "public_send", "(", "request_method", ",", "PagSeguro", ".", "api_url", "(", "\"#{api_version}/#{path}\"", ")", ",", "extended_data", "(", "data", ")", ",", "extended_headers", "(", "request_method", ",", "headers", ")", ")", "end" ]
Perform the specified HTTP request. It will include the API credentials, api_version, encoding and additional headers.
[ "Perform", "the", "specified", "HTTP", "request", ".", "It", "will", "include", "the", "API", "credentials", "api_version", "encoding", "and", "additional", "headers", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/request.rb#L81-L88
train
pagseguro/ruby
lib/pagseguro/payment_releases.rb
PagSeguro.PaymentReleases.include?
def include?(payment) self.find do |included_payment| included_payment.installment == ensure_type(PaymentRelease, payment).installment end end
ruby
def include?(payment) self.find do |included_payment| included_payment.installment == ensure_type(PaymentRelease, payment).installment end end
[ "def", "include?", "(", "payment", ")", "self", ".", "find", "do", "|", "included_payment", "|", "included_payment", ".", "installment", "==", "ensure_type", "(", "PaymentRelease", ",", "payment", ")", ".", "installment", "end", "end" ]
Verify if a payment is already included to payment list. Returns Boolean.
[ "Verify", "if", "a", "payment", "is", "already", "included", "to", "payment", "list", ".", "Returns", "Boolean", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/payment_releases.rb#L22-L26
train
pagseguro/ruby
lib/pagseguro/subscription_discount.rb
PagSeguro.SubscriptionDiscount.create
def create request = Request.put_xml("pre-approvals/#{code}/discount", credentials, xml_params) Response.new(request, self).serialize self end
ruby
def create request = Request.put_xml("pre-approvals/#{code}/discount", credentials, xml_params) Response.new(request, self).serialize self end
[ "def", "create", "request", "=", "Request", ".", "put_xml", "(", "\"pre-approvals/#{code}/discount\"", ",", "credentials", ",", "xml_params", ")", "Response", ".", "new", "(", "request", ",", "self", ")", ".", "serialize", "self", "end" ]
The server returns only with a 200 response in case of success.
[ "The", "server", "returns", "only", "with", "a", "200", "response", "in", "case", "of", "success", "." ]
c2d4bd67bcdaff3f067cf2fe82a8643340555c18
https://github.com/pagseguro/ruby/blob/c2d4bd67bcdaff3f067cf2fe82a8643340555c18/lib/pagseguro/subscription_discount.rb#L23-L29
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_categories_category_get
def gifs_categories_category_get(api_key, category, opts = {}) data, _status_code, _headers = gifs_categories_category_get_with_http_info(api_key, category, opts) return data end
ruby
def gifs_categories_category_get(api_key, category, opts = {}) data, _status_code, _headers = gifs_categories_category_get_with_http_info(api_key, category, opts) return data end
[ "def", "gifs_categories_category_get", "(", "api_key", ",", "category", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_categories_category_get_with_http_info", "(", "api_key", ",", "category", ",", "opts", ")", "return", "data", "end" ]
Category Tags Endpoint. Returns a list of tags for a given category. NOTE `limit` and `offset` must both be set; otherwise they're ignored. @param api_key Giphy API Key. @param category Filters results by category. @param [Hash] opts the optional parameters @option opts [Integer] :limit The maximum number of records to return. (default to 25) @option opts [Integer] :offset An optional results offset. Defaults to 0. (default to 0) @return [InlineResponse2004]
[ "Category", "Tags", "Endpoint", ".", "Returns", "a", "list", "of", "tags", "for", "a", "given", "category", ".", "NOTE", "limit", "and", "offset", "must", "both", "be", "set", ";", "otherwise", "they", "re", "ignored", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L30-L33
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_categories_get
def gifs_categories_get(api_key, opts = {}) data, _status_code, _headers = gifs_categories_get_with_http_info(api_key, opts) return data end
ruby
def gifs_categories_get(api_key, opts = {}) data, _status_code, _headers = gifs_categories_get_with_http_info(api_key, opts) return data end
[ "def", "gifs_categories_get", "(", "api_key", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_categories_get_with_http_info", "(", "api_key", ",", "opts", ")", "return", "data", "end" ]
Categories Endpoint. Returns a list of categories. @param api_key Giphy API Key. @param [Hash] opts the optional parameters @option opts [Integer] :limit The maximum number of records to return. (default to 25) @return [InlineResponse2003]
[ "Categories", "Endpoint", ".", "Returns", "a", "list", "of", "categories", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L192-L195
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_get
def gifs_get(api_key, ids, opts = {}) data, _status_code, _headers = gifs_get_with_http_info(api_key, ids, opts) return data end
ruby
def gifs_get(api_key, ids, opts = {}) data, _status_code, _headers = gifs_get_with_http_info(api_key, ids, opts) return data end
[ "def", "gifs_get", "(", "api_key", ",", "ids", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_get_with_http_info", "(", "api_key", ",", "ids", ",", "opts", ")", "return", "data", "end" ]
Get GIFs by ID Endpoint A multiget version of the get GIF by ID endpoint. @param api_key Giphy API Key. @param ids Filters results by specified GIF IDs, separated by commas. @param [Hash] opts the optional parameters @return [InlineResponse200]
[ "Get", "GIFs", "by", "ID", "Endpoint", "A", "multiget", "version", "of", "the", "get", "GIF", "by", "ID", "endpoint", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L257-L260
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_gif_id_get
def gifs_gif_id_get(api_key, gif_id, opts = {}) data, _status_code, _headers = gifs_gif_id_get_with_http_info(api_key, gif_id, opts) return data end
ruby
def gifs_gif_id_get(api_key, gif_id, opts = {}) data, _status_code, _headers = gifs_gif_id_get_with_http_info(api_key, gif_id, opts) return data end
[ "def", "gifs_gif_id_get", "(", "api_key", ",", "gif_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_gif_id_get_with_http_info", "(", "api_key", ",", "gif_id", ",", "opts", ")", "return", "data", "end" ]
Get GIF by ID Endpoint Returns a GIF given that GIF's unique ID @param api_key Giphy API Key. @param gif_id Filters results by specified GIF ID. @param [Hash] opts the optional parameters @return [InlineResponse2001]
[ "Get", "GIF", "by", "ID", "Endpoint", "Returns", "a", "GIF", "given", "that", "GIF", "s", "unique", "ID" ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L316-L319
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_random_get
def gifs_random_get(api_key, opts = {}) data, _status_code, _headers = gifs_random_get_with_http_info(api_key, opts) return data end
ruby
def gifs_random_get(api_key, opts = {}) data, _status_code, _headers = gifs_random_get_with_http_info(api_key, opts) return data end
[ "def", "gifs_random_get", "(", "api_key", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_random_get_with_http_info", "(", "api_key", ",", "opts", ")", "return", "data", "end" ]
Random Endpoint Returns a random GIF, limited by tag. Excluding the tag parameter will return a random GIF from the GIPHY catalog. @param api_key Giphy API Key. @param [Hash] opts the optional parameters @option opts [String] :tag Filters results by specified tag. @option opts [String] :rating Filters results by specified rating. @option opts [String] :fmt Used to indicate the expected response format. Default is Json. (default to json) @return [InlineResponse2002]
[ "Random", "Endpoint", "Returns", "a", "random", "GIF", "limited", "by", "tag", ".", "Excluding", "the", "tag", "parameter", "will", "return", "a", "random", "GIF", "from", "the", "GIPHY", "catalog", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L376-L379
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_search_get
def gifs_search_get(api_key, q, opts = {}) data, _status_code, _headers = gifs_search_get_with_http_info(api_key, q, opts) return data end
ruby
def gifs_search_get(api_key, q, opts = {}) data, _status_code, _headers = gifs_search_get_with_http_info(api_key, q, opts) return data end
[ "def", "gifs_search_get", "(", "api_key", ",", "q", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_search_get_with_http_info", "(", "api_key", ",", "q", ",", "opts", ")", "return", "data", "end" ]
Search Endpoint Search all Giphy GIFs for a word or phrase. Punctuation will be stripped and ignored. Use a plus or url encode for phrases. Example paul+rudd, ryan+gosling or american+psycho. @param api_key Giphy API Key. @param q Search query term or prhase. @param [Hash] opts the optional parameters @option opts [Integer] :limit The maximum number of records to return. (default to 25) @option opts [Integer] :offset An optional results offset. Defaults to 0. (default to 0) @option opts [String] :rating Filters results by specified rating. @option opts [String] :lang Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages &lt;a href &#x3D; \&quot;../language-support\&quot;&gt;here&lt;/a&gt;. @option opts [String] :fmt Used to indicate the expected response format. Default is Json. (default to json) @return [InlineResponse200]
[ "Search", "Endpoint", "Search", "all", "Giphy", "GIFs", "for", "a", "word", "or", "phrase", ".", "Punctuation", "will", "be", "stripped", "and", "ignored", ".", "Use", "a", "plus", "or", "url", "encode", "for", "phrases", ".", "Example", "paul", "+", "rudd", "ryan", "+", "gosling", "or", "american", "+", "psycho", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L445-L448
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.gifs_translate_get
def gifs_translate_get(api_key, s, opts = {}) data, _status_code, _headers = gifs_translate_get_with_http_info(api_key, s, opts) return data end
ruby
def gifs_translate_get(api_key, s, opts = {}) data, _status_code, _headers = gifs_translate_get_with_http_info(api_key, s, opts) return data end
[ "def", "gifs_translate_get", "(", "api_key", ",", "s", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "gifs_translate_get_with_http_info", "(", "api_key", ",", "s", ",", "opts", ")", "return", "data", "end" ]
Translate Endpoint The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs. @param api_key Giphy API Key. @param s Search term. @param [Hash] opts the optional parameters @return [InlineResponse2001]
[ "Translate", "Endpoint", "The", "translate", "API", "draws", "on", "search", "but", "uses", "the", "Giphy", "special", "sauce", "to", "handle", "translating", "from", "one", "vocabulary", "to", "another", ".", "In", "this", "case", "words", "and", "phrases", "to", "GIFs", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L533-L536
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.stickers_random_get
def stickers_random_get(api_key, opts = {}) data, _status_code, _headers = stickers_random_get_with_http_info(api_key, opts) return data end
ruby
def stickers_random_get(api_key, opts = {}) data, _status_code, _headers = stickers_random_get_with_http_info(api_key, opts) return data end
[ "def", "stickers_random_get", "(", "api_key", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "stickers_random_get_with_http_info", "(", "api_key", ",", "opts", ")", "return", "data", "end" ]
Random Sticker Endpoint Returns a random GIF, limited by tag. Excluding the tag parameter will return a random GIF from the GIPHY catalog. @param api_key Giphy API Key. @param [Hash] opts the optional parameters @option opts [String] :tag Filters results by specified tag. @option opts [String] :rating Filters results by specified rating. @option opts [String] :fmt Used to indicate the expected response format. Default is Json. (default to json) @return [InlineResponse2002]
[ "Random", "Sticker", "Endpoint", "Returns", "a", "random", "GIF", "limited", "by", "tag", ".", "Excluding", "the", "tag", "parameter", "will", "return", "a", "random", "GIF", "from", "the", "GIPHY", "catalog", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L668-L671
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.stickers_search_get
def stickers_search_get(api_key, q, opts = {}) data, _status_code, _headers = stickers_search_get_with_http_info(api_key, q, opts) return data end
ruby
def stickers_search_get(api_key, q, opts = {}) data, _status_code, _headers = stickers_search_get_with_http_info(api_key, q, opts) return data end
[ "def", "stickers_search_get", "(", "api_key", ",", "q", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "stickers_search_get_with_http_info", "(", "api_key", ",", "q", ",", "opts", ")", "return", "data", "end" ]
Sticker Search Endpoint Replicates the functionality and requirements of the classic GIPHY search, but returns animated stickers rather than GIFs. @param api_key Giphy API Key. @param q Search query term or prhase. @param [Hash] opts the optional parameters @option opts [Integer] :limit The maximum number of records to return. (default to 25) @option opts [Integer] :offset An optional results offset. Defaults to 0. (default to 0) @option opts [String] :rating Filters results by specified rating. @option opts [String] :lang Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages &lt;a href &#x3D; \&quot;../language-support\&quot;&gt;here&lt;/a&gt;. @option opts [String] :fmt Used to indicate the expected response format. Default is Json. (default to json) @return [InlineResponse200]
[ "Sticker", "Search", "Endpoint", "Replicates", "the", "functionality", "and", "requirements", "of", "the", "classic", "GIPHY", "search", "but", "returns", "animated", "stickers", "rather", "than", "GIFs", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L737-L740
train
Giphy/giphy-ruby-client
lib/GiphyClient/api/default_api.rb
GiphyClient.DefaultApi.stickers_translate_get
def stickers_translate_get(api_key, s, opts = {}) data, _status_code, _headers = stickers_translate_get_with_http_info(api_key, s, opts) return data end
ruby
def stickers_translate_get(api_key, s, opts = {}) data, _status_code, _headers = stickers_translate_get_with_http_info(api_key, s, opts) return data end
[ "def", "stickers_translate_get", "(", "api_key", ",", "s", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "stickers_translate_get_with_http_info", "(", "api_key", ",", "s", ",", "opts", ")", "return", "data", "end" ]
Sticker Translate Endpoint The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs. @param api_key Giphy API Key. @param s Search term. @param [Hash] opts the optional parameters @return [InlineResponse2001]
[ "Sticker", "Translate", "Endpoint", "The", "translate", "API", "draws", "on", "search", "but", "uses", "the", "Giphy", "special", "sauce", "to", "handle", "translating", "from", "one", "vocabulary", "to", "another", ".", "In", "this", "case", "words", "and", "phrases", "to", "GIFs", "." ]
75a99c4d529ac74a864f70a6d89174c5decf11e8
https://github.com/Giphy/giphy-ruby-client/blob/75a99c4d529ac74a864f70a6d89174c5decf11e8/lib/GiphyClient/api/default_api.rb#L825-L828
train
digitalsparky/jekyll-minifier
spec/fixtures/_plugins/generate_categories.rb
Jekyll.Filters.date_to_html_string
def date_to_html_string(date) result = '<span class="month">' + date.strftime('%b').upcase + '</span> ' result += date.strftime('<span class="day">%d</span> ') result += date.strftime('<span class="year">%Y</span> ') result end
ruby
def date_to_html_string(date) result = '<span class="month">' + date.strftime('%b').upcase + '</span> ' result += date.strftime('<span class="day">%d</span> ') result += date.strftime('<span class="year">%Y</span> ') result end
[ "def", "date_to_html_string", "(", "date", ")", "result", "=", "'<span class=\"month\">'", "+", "date", ".", "strftime", "(", "'%b'", ")", ".", "upcase", "+", "'</span> '", "result", "+=", "date", ".", "strftime", "(", "'<span class=\"day\">%d</span> '", ")", "result", "+=", "date", ".", "strftime", "(", "'<span class=\"year\">%Y</span> '", ")", "result", "end" ]
Outputs the post.date as formatted html, with hooks for CSS styling. +date+ is the date object to format as HTML. Returns string
[ "Outputs", "the", "post", ".", "date", "as", "formatted", "html", "with", "hooks", "for", "CSS", "styling", "." ]
ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a
https://github.com/digitalsparky/jekyll-minifier/blob/ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a/spec/fixtures/_plugins/generate_categories.rb#L231-L236
train
digitalsparky/jekyll-minifier
spec/fixtures/_plugins/generate_categories.rb
Jekyll.Site.write_category_index
def write_category_index(category) target_dir = GenerateCategories.category_dir(self.config['category_dir'], category) index = CategoryIndex.new(self, self.source, target_dir, category) if index.render? index.render(self.layouts, site_payload) index.write(self.dest) # Record the fact that this pages has been added, otherwise Site::cleanup will remove it. self.pages << index end # Create an Atom-feed for each index. feed = CategoryFeed.new(self, self.source, target_dir, category) if feed.render? feed.render(self.layouts, site_payload) feed.write(self.dest) # Record the fact that this pages has been added, otherwise Site::cleanup will remove it. self.pages << feed end end
ruby
def write_category_index(category) target_dir = GenerateCategories.category_dir(self.config['category_dir'], category) index = CategoryIndex.new(self, self.source, target_dir, category) if index.render? index.render(self.layouts, site_payload) index.write(self.dest) # Record the fact that this pages has been added, otherwise Site::cleanup will remove it. self.pages << index end # Create an Atom-feed for each index. feed = CategoryFeed.new(self, self.source, target_dir, category) if feed.render? feed.render(self.layouts, site_payload) feed.write(self.dest) # Record the fact that this pages has been added, otherwise Site::cleanup will remove it. self.pages << feed end end
[ "def", "write_category_index", "(", "category", ")", "target_dir", "=", "GenerateCategories", ".", "category_dir", "(", "self", ".", "config", "[", "'category_dir'", "]", ",", "category", ")", "index", "=", "CategoryIndex", ".", "new", "(", "self", ",", "self", ".", "source", ",", "target_dir", ",", "category", ")", "if", "index", ".", "render?", "index", ".", "render", "(", "self", ".", "layouts", ",", "site_payload", ")", "index", ".", "write", "(", "self", ".", "dest", ")", "# Record the fact that this pages has been added, otherwise Site::cleanup will remove it.", "self", ".", "pages", "<<", "index", "end", "# Create an Atom-feed for each index.", "feed", "=", "CategoryFeed", ".", "new", "(", "self", ",", "self", ".", "source", ",", "target_dir", ",", "category", ")", "if", "feed", ".", "render?", "feed", ".", "render", "(", "self", ".", "layouts", ",", "site_payload", ")", "feed", ".", "write", "(", "self", ".", "dest", ")", "# Record the fact that this pages has been added, otherwise Site::cleanup will remove it.", "self", ".", "pages", "<<", "feed", "end", "end" ]
Creates an instance of CategoryIndex for each category page, renders it, and writes the output to a file. +category+ is the category currently being processed.
[ "Creates", "an", "instance", "of", "CategoryIndex", "for", "each", "category", "page", "renders", "it", "and", "writes", "the", "output", "to", "a", "file", "." ]
ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a
https://github.com/digitalsparky/jekyll-minifier/blob/ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a/spec/fixtures/_plugins/generate_categories.rb#L140-L158
train
digitalsparky/jekyll-minifier
spec/fixtures/_plugins/generate_categories.rb
Jekyll.Site.write_category_indexes
def write_category_indexes if self.layouts.key? 'category_index' self.categories.keys.each do |category| self.write_category_index(category) end # Throw an exception if the layout couldn't be found. else throw "No 'category_index' layout found." end end
ruby
def write_category_indexes if self.layouts.key? 'category_index' self.categories.keys.each do |category| self.write_category_index(category) end # Throw an exception if the layout couldn't be found. else throw "No 'category_index' layout found." end end
[ "def", "write_category_indexes", "if", "self", ".", "layouts", ".", "key?", "'category_index'", "self", ".", "categories", ".", "keys", ".", "each", "do", "|", "category", "|", "self", ".", "write_category_index", "(", "category", ")", "end", "# Throw an exception if the layout couldn't be found.", "else", "throw", "\"No 'category_index' layout found.\"", "end", "end" ]
Loops through the list of category pages and processes each one.
[ "Loops", "through", "the", "list", "of", "category", "pages", "and", "processes", "each", "one", "." ]
ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a
https://github.com/digitalsparky/jekyll-minifier/blob/ddf4d970985c0f8a9657b2f411e8419ef3ea1e1a/spec/fixtures/_plugins/generate_categories.rb#L161-L171
train
tomichj/invitation
lib/invitation/user_registration.rb
Invitation.UserRegistration.process_invite_token
def process_invite_token(new_user = nil) new_user = user_instance_variable if new_user.nil? token = params[:invite_token] new_user.claim_invite token if !token.nil? && !new_user.nil? end
ruby
def process_invite_token(new_user = nil) new_user = user_instance_variable if new_user.nil? token = params[:invite_token] new_user.claim_invite token if !token.nil? && !new_user.nil? end
[ "def", "process_invite_token", "(", "new_user", "=", "nil", ")", "new_user", "=", "user_instance_variable", "if", "new_user", ".", "nil?", "token", "=", "params", "[", ":invite_token", "]", "new_user", ".", "claim_invite", "token", "if", "!", "token", ".", "nil?", "&&", "!", "new_user", ".", "nil?", "end" ]
Check for an invitation token and process the invite. If an invitation is found, the user claims the invite. Use this only when creating a new user. Invoke manually or from an after_action: after_action :process_invite, only: [:create] Invoke with new_user, or set an instance variable with the standard 'underscore' name of your user model class. For example, if your user model is UserProfile, this method will check for @user_profile.
[ "Check", "for", "an", "invitation", "token", "and", "process", "the", "invite", ".", "If", "an", "invitation", "is", "found", "the", "user", "claims", "the", "invite", "." ]
d31f7cadb0da93c4f3cd934ba5763512d84dc432
https://github.com/tomichj/invitation/blob/d31f7cadb0da93c4f3cd934ba5763512d84dc432/lib/invitation/user_registration.rb#L29-L33
train
tomichj/invitation
lib/invitation/invitable.rb
Invitation.Invitable.invitable
def invitable(options = {}) has_many :invites, as: :invitable class_attribute :invitable_options self.invitable_options = {} case when options[:named_by] then invitable_options[:named_by] = options[:named_by] when options[:named] then invitable_options[:named] = options[:named] else raise 'invitable requires options be set, either :name or :named_by. \ e.g.: `invitable named: "string"` or `invitable named_by: :method_name`' end include Invitation::Invitable::InstanceMethods end
ruby
def invitable(options = {}) has_many :invites, as: :invitable class_attribute :invitable_options self.invitable_options = {} case when options[:named_by] then invitable_options[:named_by] = options[:named_by] when options[:named] then invitable_options[:named] = options[:named] else raise 'invitable requires options be set, either :name or :named_by. \ e.g.: `invitable named: "string"` or `invitable named_by: :method_name`' end include Invitation::Invitable::InstanceMethods end
[ "def", "invitable", "(", "options", "=", "{", "}", ")", "has_many", ":invites", ",", "as", ":", ":invitable", "class_attribute", ":invitable_options", "self", ".", "invitable_options", "=", "{", "}", "case", "when", "options", "[", ":named_by", "]", "then", "invitable_options", "[", ":named_by", "]", "=", "options", "[", ":named_by", "]", "when", "options", "[", ":named", "]", "then", "invitable_options", "[", ":named", "]", "=", "options", "[", ":named", "]", "else", "raise", "'invitable requires options be set, either :name or :named_by. \\\n e.g.: `invitable named: \"string\"` or `invitable named_by: :method_name`'", "end", "include", "Invitation", "::", "Invitable", "::", "InstanceMethods", "end" ]
All resources or organizations should be invitable. @param [Hash] options - either named_by: <method name> or named: <String>
[ "All", "resources", "or", "organizations", "should", "be", "invitable", "." ]
d31f7cadb0da93c4f3cd934ba5763512d84dc432
https://github.com/tomichj/invitation/blob/d31f7cadb0da93c4f3cd934ba5763512d84dc432/lib/invitation/invitable.rb#L22-L33
train
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.run
def run(*args, &block) cmd = command(*args) result = execute_command(cmd, &block) if result && result.failure? raise ExitError.new(cmd.to_command, result) end result end
ruby
def run(*args, &block) cmd = command(*args) result = execute_command(cmd, &block) if result && result.failure? raise ExitError.new(cmd.to_command, result) end result end
[ "def", "run", "(", "*", "args", ",", "&", "block", ")", "cmd", "=", "command", "(", "args", ")", "result", "=", "execute_command", "(", "cmd", ",", "block", ")", "if", "result", "&&", "result", ".", "failure?", "raise", "ExitError", ".", "new", "(", "cmd", ".", "to_command", ",", "result", ")", "end", "result", "end" ]
Initialize a Command object @param [Hash] options @option options [IO] :output the stream to which printer prints, defaults to stdout @option options [Symbol] :printer the printer to use for output logging, defaults to :pretty @option options [Symbol] :dry_run the mode for executing command @api public Start external executable in a child process @example cmd.run(command, [argv1, ..., argvN], [options]) @example cmd.run(command, ...) do |result| ... end @param [String] command the command to run @param [Array[String]] argv an array of string arguments @param [Hash] options hash of operations to perform @option options [String] :chdir The current directory. @option options [Integer] :timeout Maximum number of seconds to allow the process to run before aborting with a TimeoutExceeded exception. @option options [Symbol] :signal Signal used on timeout, SIGKILL by default @yield [out, err] Yields stdout and stderr output whenever available @raise [ExitError] raised when command exits with non-zero code @api public
[ "Initialize", "a", "Command", "object" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L102-L109
train
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.ruby
def ruby(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} if args.length > 1 run(*([RUBY] + args + [options]), &block) else run("#{RUBY} #{args.first}", options, &block) end end
ruby
def ruby(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} if args.length > 1 run(*([RUBY] + args + [options]), &block) else run("#{RUBY} #{args.first}", options, &block) end end
[ "def", "ruby", "(", "*", "args", ",", "&", "block", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "if", "args", ".", "length", ">", "1", "run", "(", "(", "[", "RUBY", "]", "+", "args", "+", "[", "options", "]", ")", ",", "block", ")", "else", "run", "(", "\"#{RUBY} #{args.first}\"", ",", "options", ",", "block", ")", "end", "end" ]
Run Ruby interperter with the given arguments @example ruby %q{-e "puts 'Hello world'"} @api public
[ "Run", "Ruby", "interperter", "with", "the", "given", "arguments" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L154-L161
train
piotrmurach/tty-command
lib/tty/command.rb
TTY.Command.find_printer_class
def find_printer_class(name) const_name = name.to_s.split('_').map(&:capitalize).join.to_sym if const_name.empty? || !TTY::Command::Printers.const_defined?(const_name) raise ArgumentError, %(Unknown printer type "#{name}") end TTY::Command::Printers.const_get(const_name) end
ruby
def find_printer_class(name) const_name = name.to_s.split('_').map(&:capitalize).join.to_sym if const_name.empty? || !TTY::Command::Printers.const_defined?(const_name) raise ArgumentError, %(Unknown printer type "#{name}") end TTY::Command::Printers.const_get(const_name) end
[ "def", "find_printer_class", "(", "name", ")", "const_name", "=", "name", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", ".", "join", ".", "to_sym", "if", "const_name", ".", "empty?", "||", "!", "TTY", "::", "Command", "::", "Printers", ".", "const_defined?", "(", "const_name", ")", "raise", "ArgumentError", ",", "%(Unknown printer type \"#{name}\")", "end", "TTY", "::", "Command", "::", "Printers", ".", "const_get", "(", "const_name", ")", "end" ]
Find printer class or fail @raise [ArgumentError] @api private
[ "Find", "printer", "class", "or", "fail" ]
10910b0279a08de3652433d8627e2090cd8b9087
https://github.com/piotrmurach/tty-command/blob/10910b0279a08de3652433d8627e2090cd8b9087/lib/tty/command.rb#L206-L212
train
heroku/hatchet
lib/hatchet/config.rb
Hatchet.Config.init_config!
def init_config!(config) set_internal_config!(config) config.each do |(directory, git_repos)| git_repos.each do |git_repo| git_repo = git_repo.include?("github.com") ? git_repo : "https://github.com/#{git_repo}.git" repo_name = name_from_git_repo(git_repo) repo_path = File.join(repo_directory_path, directory, repo_name) if repos.key? repo_name puts " warning duplicate repo found: #{repo_name.inspect}" repos[repo_name] = false else repos[repo_name] = repo_path end dirs[repo_path] = git_repo end end end
ruby
def init_config!(config) set_internal_config!(config) config.each do |(directory, git_repos)| git_repos.each do |git_repo| git_repo = git_repo.include?("github.com") ? git_repo : "https://github.com/#{git_repo}.git" repo_name = name_from_git_repo(git_repo) repo_path = File.join(repo_directory_path, directory, repo_name) if repos.key? repo_name puts " warning duplicate repo found: #{repo_name.inspect}" repos[repo_name] = false else repos[repo_name] = repo_path end dirs[repo_path] = git_repo end end end
[ "def", "init_config!", "(", "config", ")", "set_internal_config!", "(", "config", ")", "config", ".", "each", "do", "|", "(", "directory", ",", "git_repos", ")", "|", "git_repos", ".", "each", "do", "|", "git_repo", "|", "git_repo", "=", "git_repo", ".", "include?", "(", "\"github.com\"", ")", "?", "git_repo", ":", "\"https://github.com/#{git_repo}.git\"", "repo_name", "=", "name_from_git_repo", "(", "git_repo", ")", "repo_path", "=", "File", ".", "join", "(", "repo_directory_path", ",", "directory", ",", "repo_name", ")", "if", "repos", ".", "key?", "repo_name", "puts", "\" warning duplicate repo found: #{repo_name.inspect}\"", "repos", "[", "repo_name", "]", "=", "false", "else", "repos", "[", "repo_name", "]", "=", "repo_path", "end", "dirs", "[", "repo_path", "]", "=", "git_repo", "end", "end", "end" ]
pulls out config and makes easy to use hashes dirs has the repo paths as keys and the git_repos as values repos has repo names as keys and the paths as values
[ "pulls", "out", "config", "and", "makes", "easy", "to", "use", "hashes", "dirs", "has", "the", "repo", "paths", "as", "keys", "and", "the", "git_repos", "as", "values", "repos", "has", "repo", "names", "as", "keys", "and", "the", "paths", "as", "values" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/config.rb#L71-L87
train
heroku/hatchet
lib/hatchet/app.rb
Hatchet.App.setup!
def setup! return self if @app_is_setup puts "Hatchet setup: #{name.inspect} for #{repo_name.inspect}" create_git_repo! unless is_git_repo? create_app set_labs! buildpack_list = @buildpacks.map { |pack| { buildpack: pack } } api_rate_limit.call.buildpack_installation.update(name, updates: buildpack_list) set_config @app_config call_before_deploy @app_is_setup = true self end
ruby
def setup! return self if @app_is_setup puts "Hatchet setup: #{name.inspect} for #{repo_name.inspect}" create_git_repo! unless is_git_repo? create_app set_labs! buildpack_list = @buildpacks.map { |pack| { buildpack: pack } } api_rate_limit.call.buildpack_installation.update(name, updates: buildpack_list) set_config @app_config call_before_deploy @app_is_setup = true self end
[ "def", "setup!", "return", "self", "if", "@app_is_setup", "puts", "\"Hatchet setup: #{name.inspect} for #{repo_name.inspect}\"", "create_git_repo!", "unless", "is_git_repo?", "create_app", "set_labs!", "buildpack_list", "=", "@buildpacks", ".", "map", "{", "|", "pack", "|", "{", "buildpack", ":", "pack", "}", "}", "api_rate_limit", ".", "call", ".", "buildpack_installation", ".", "update", "(", "name", ",", "updates", ":", "buildpack_list", ")", "set_config", "@app_config", "call_before_deploy", "@app_is_setup", "=", "true", "self", "end" ]
creates a new heroku app via the API
[ "creates", "a", "new", "heroku", "app", "via", "the", "API" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/app.rb#L164-L177
train
heroku/hatchet
lib/hatchet/reaper.rb
Hatchet.Reaper.get_apps
def get_apps apps = @api_rate_limit.call.app.list.sort_by { |app| DateTime.parse(app["created_at"]) }.reverse @app_count = apps.count @hatchet_apps = apps.select {|app| app["name"].match(@regex) } end
ruby
def get_apps apps = @api_rate_limit.call.app.list.sort_by { |app| DateTime.parse(app["created_at"]) }.reverse @app_count = apps.count @hatchet_apps = apps.select {|app| app["name"].match(@regex) } end
[ "def", "get_apps", "apps", "=", "@api_rate_limit", ".", "call", ".", "app", ".", "list", ".", "sort_by", "{", "|", "app", "|", "DateTime", ".", "parse", "(", "app", "[", "\"created_at\"", "]", ")", "}", ".", "reverse", "@app_count", "=", "apps", ".", "count", "@hatchet_apps", "=", "apps", ".", "select", "{", "|", "app", "|", "app", "[", "\"name\"", "]", ".", "match", "(", "@regex", ")", "}", "end" ]
Ascending order, oldest is last
[ "Ascending", "order", "oldest", "is", "last" ]
12815a5255419442b4b528f06ed59c96e5859e4e
https://github.com/heroku/hatchet/blob/12815a5255419442b4b528f06ed59c96e5859e4e/lib/hatchet/reaper.rb#L21-L25
train
hammackj/uirusu
lib/uirusu/vtresult.rb
Uirusu.VTResult.to_stdout
def to_stdout result_string = String.new hashes = Array.new @results.sort_by {|k| k[:scanner] }.each do |result| unless hashes.include? result[:hash].downcase result_string << "#{result[:hash]}:\n" hashes << result[:hash].downcase end result_string << "#{result[:scanner]}: ".rjust(25) + "#{result[:result]}\n" end if @results != nil result_string end
ruby
def to_stdout result_string = String.new hashes = Array.new @results.sort_by {|k| k[:scanner] }.each do |result| unless hashes.include? result[:hash].downcase result_string << "#{result[:hash]}:\n" hashes << result[:hash].downcase end result_string << "#{result[:scanner]}: ".rjust(25) + "#{result[:result]}\n" end if @results != nil result_string end
[ "def", "to_stdout", "result_string", "=", "String", ".", "new", "hashes", "=", "Array", ".", "new", "@results", ".", "sort_by", "{", "|", "k", "|", "k", "[", ":scanner", "]", "}", ".", "each", "do", "|", "result", "|", "unless", "hashes", ".", "include?", "result", "[", ":hash", "]", ".", "downcase", "result_string", "<<", "\"#{result[:hash]}:\\n\"", "hashes", "<<", "result", "[", ":hash", "]", ".", "downcase", "end", "result_string", "<<", "\"#{result[:scanner]}: \"", ".", "rjust", "(", "25", ")", "+", "\"#{result[:result]}\\n\"", "end", "if", "@results", "!=", "nil", "result_string", "end" ]
Builds a VTResult object based on the hash and results passed to it @param hash, Cryptographic hash that was searched @param results, Results of the search on Virustotal.com Outputs the result to STDOUT @return [String] Pretty text printable representation of the result
[ "Builds", "a", "VTResult", "object", "based", "on", "the", "hash", "and", "results", "passed", "to", "it" ]
1f9e46d505416bc6c006f4e6ae334bc7a93e3402
https://github.com/hammackj/uirusu/blob/1f9e46d505416bc6c006f4e6ae334bc7a93e3402/lib/uirusu/vtresult.rb#L108-L121
train
hammackj/uirusu
lib/uirusu/vtresult.rb
Uirusu.VTResult.to_xml
def to_xml result_string = String.new result_string << "<results>\n" @results.each do |result| result_string << "\t<vtresult>\n" RESULT_FIELDS.each{|field| result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil? } result_string << "\t</vtresult>\n" end if @results != nil result_string << "</results>\n" result_string end
ruby
def to_xml result_string = String.new result_string << "<results>\n" @results.each do |result| result_string << "\t<vtresult>\n" RESULT_FIELDS.each{|field| result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil? } result_string << "\t</vtresult>\n" end if @results != nil result_string << "</results>\n" result_string end
[ "def", "to_xml", "result_string", "=", "String", ".", "new", "result_string", "<<", "\"<results>\\n\"", "@results", ".", "each", "do", "|", "result", "|", "result_string", "<<", "\"\\t<vtresult>\\n\"", "RESULT_FIELDS", ".", "each", "{", "|", "field", "|", "result_string", "<<", "\"\\t\\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\\n\"", "unless", "field", "==", ":permalink", "and", "result", "[", "'permalink'", "]", ".", "nil?", "}", "result_string", "<<", "\"\\t</vtresult>\\n\"", "end", "if", "@results", "!=", "nil", "result_string", "<<", "\"</results>\\n\"", "result_string", "end" ]
Outputs the result to XML @return [String] XML representation of the result
[ "Outputs", "the", "result", "to", "XML" ]
1f9e46d505416bc6c006f4e6ae334bc7a93e3402
https://github.com/hammackj/uirusu/blob/1f9e46d505416bc6c006f4e6ae334bc7a93e3402/lib/uirusu/vtresult.rb#L140-L153
train
netbe/Babelish
lib/babelish/strings2csv.rb
Babelish.Strings2CSV.load_strings
def load_strings(strings_filename) strings = {} comments = {} # genstrings uses utf16, so that's what we expect. utf8 should not be impact file = File.open(strings_filename, "r:utf-16:utf-8") begin contents = file.read if RUBY_VERSION == "1.9.2" # fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/ require 'iconv' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') contents = ic.iconv(contents + ' ')[0..-2] end rescue Encoding::InvalidByteSequenceError => e # silent error # faults back to utf8 contents = File.open(strings_filename, "r:utf-8") end previous_comment = nil contents.each_line do |line| key, value = self.parse_dotstrings_line(line) if key strings.merge!({key => value}) comments[key] = previous_comment if previous_comment else previous_comment = self.parse_comment_line(line) end end [strings, comments] end
ruby
def load_strings(strings_filename) strings = {} comments = {} # genstrings uses utf16, so that's what we expect. utf8 should not be impact file = File.open(strings_filename, "r:utf-16:utf-8") begin contents = file.read if RUBY_VERSION == "1.9.2" # fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/ require 'iconv' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') contents = ic.iconv(contents + ' ')[0..-2] end rescue Encoding::InvalidByteSequenceError => e # silent error # faults back to utf8 contents = File.open(strings_filename, "r:utf-8") end previous_comment = nil contents.each_line do |line| key, value = self.parse_dotstrings_line(line) if key strings.merge!({key => value}) comments[key] = previous_comment if previous_comment else previous_comment = self.parse_comment_line(line) end end [strings, comments] end
[ "def", "load_strings", "(", "strings_filename", ")", "strings", "=", "{", "}", "comments", "=", "{", "}", "# genstrings uses utf16, so that's what we expect. utf8 should not be impact", "file", "=", "File", ".", "open", "(", "strings_filename", ",", "\"r:utf-16:utf-8\"", ")", "begin", "contents", "=", "file", ".", "read", "if", "RUBY_VERSION", "==", "\"1.9.2\"", "# fixes conversion, see http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/", "require", "'iconv'", "ic", "=", "Iconv", ".", "new", "(", "'UTF-8//IGNORE'", ",", "'UTF-8'", ")", "contents", "=", "ic", ".", "iconv", "(", "contents", "+", "' '", ")", "[", "0", "..", "-", "2", "]", "end", "rescue", "Encoding", "::", "InvalidByteSequenceError", "=>", "e", "# silent error", "# faults back to utf8", "contents", "=", "File", ".", "open", "(", "strings_filename", ",", "\"r:utf-8\"", ")", "end", "previous_comment", "=", "nil", "contents", ".", "each_line", "do", "|", "line", "|", "key", ",", "value", "=", "self", ".", "parse_dotstrings_line", "(", "line", ")", "if", "key", "strings", ".", "merge!", "(", "{", "key", "=>", "value", "}", ")", "comments", "[", "key", "]", "=", "previous_comment", "if", "previous_comment", "else", "previous_comment", "=", "self", ".", "parse_comment_line", "(", "line", ")", "end", "end", "[", "strings", ",", "comments", "]", "end" ]
Load all strings of a given file
[ "Load", "all", "strings", "of", "a", "given", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/strings2csv.rb#L28-L58
train
netbe/Babelish
lib/babelish/csv2base.rb
Babelish.Csv2Base.convert
def convert(name = @csv_filename) rowIndex = 0 excludedCols = [] defaultCol = 0 CSV.foreach(name, :quote_char => '"', :col_sep => @csv_separator, :row_sep => :auto) do |row| if rowIndex == 0 #check there's at least two columns return unless row.count > 1 else #skip empty lines (or sections) next if row == nil or row[@keys_column].nil? end # go through columns row.size.times do |i| next if excludedCols.include? i #header if rowIndex == 0 # defaultCol can be the keyValue defaultCol = i if self.default_lang == row[i] # ignore all headers not listed in langs to create files (excludedCols << i and next) unless @langs.has_key?(row[i]) language = Language.new(row[i]) if @langs[row[i]].is_a?(Array) @langs[row[i]].each do |id| language.add_language_id(id.to_s) end else language.add_language_id(@langs[row[i]].to_s) end @languages[i] = language elsif !@state_column || (row[@state_column].nil? || row[@state_column] == '' || !@excluded_states.include?(row[@state_column])) key = row[@keys_column] comment = @comments_column ? row[@comments_column] : nil key.strip! if @stripping default_value = self.default_lang ? row[defaultCol] : nil value = self.process_value(row[i], default_value) @comments[key] = comment @languages[i].add_content_pair(key, value) end end rowIndex += 1 end write_content end
ruby
def convert(name = @csv_filename) rowIndex = 0 excludedCols = [] defaultCol = 0 CSV.foreach(name, :quote_char => '"', :col_sep => @csv_separator, :row_sep => :auto) do |row| if rowIndex == 0 #check there's at least two columns return unless row.count > 1 else #skip empty lines (or sections) next if row == nil or row[@keys_column].nil? end # go through columns row.size.times do |i| next if excludedCols.include? i #header if rowIndex == 0 # defaultCol can be the keyValue defaultCol = i if self.default_lang == row[i] # ignore all headers not listed in langs to create files (excludedCols << i and next) unless @langs.has_key?(row[i]) language = Language.new(row[i]) if @langs[row[i]].is_a?(Array) @langs[row[i]].each do |id| language.add_language_id(id.to_s) end else language.add_language_id(@langs[row[i]].to_s) end @languages[i] = language elsif !@state_column || (row[@state_column].nil? || row[@state_column] == '' || !@excluded_states.include?(row[@state_column])) key = row[@keys_column] comment = @comments_column ? row[@comments_column] : nil key.strip! if @stripping default_value = self.default_lang ? row[defaultCol] : nil value = self.process_value(row[i], default_value) @comments[key] = comment @languages[i].add_content_pair(key, value) end end rowIndex += 1 end write_content end
[ "def", "convert", "(", "name", "=", "@csv_filename", ")", "rowIndex", "=", "0", "excludedCols", "=", "[", "]", "defaultCol", "=", "0", "CSV", ".", "foreach", "(", "name", ",", ":quote_char", "=>", "'\"'", ",", ":col_sep", "=>", "@csv_separator", ",", ":row_sep", "=>", ":auto", ")", "do", "|", "row", "|", "if", "rowIndex", "==", "0", "#check there's at least two columns", "return", "unless", "row", ".", "count", ">", "1", "else", "#skip empty lines (or sections)", "next", "if", "row", "==", "nil", "or", "row", "[", "@keys_column", "]", ".", "nil?", "end", "# go through columns", "row", ".", "size", ".", "times", "do", "|", "i", "|", "next", "if", "excludedCols", ".", "include?", "i", "#header", "if", "rowIndex", "==", "0", "# defaultCol can be the keyValue", "defaultCol", "=", "i", "if", "self", ".", "default_lang", "==", "row", "[", "i", "]", "# ignore all headers not listed in langs to create files", "(", "excludedCols", "<<", "i", "and", "next", ")", "unless", "@langs", ".", "has_key?", "(", "row", "[", "i", "]", ")", "language", "=", "Language", ".", "new", "(", "row", "[", "i", "]", ")", "if", "@langs", "[", "row", "[", "i", "]", "]", ".", "is_a?", "(", "Array", ")", "@langs", "[", "row", "[", "i", "]", "]", ".", "each", "do", "|", "id", "|", "language", ".", "add_language_id", "(", "id", ".", "to_s", ")", "end", "else", "language", ".", "add_language_id", "(", "@langs", "[", "row", "[", "i", "]", "]", ".", "to_s", ")", "end", "@languages", "[", "i", "]", "=", "language", "elsif", "!", "@state_column", "||", "(", "row", "[", "@state_column", "]", ".", "nil?", "||", "row", "[", "@state_column", "]", "==", "''", "||", "!", "@excluded_states", ".", "include?", "(", "row", "[", "@state_column", "]", ")", ")", "key", "=", "row", "[", "@keys_column", "]", "comment", "=", "@comments_column", "?", "row", "[", "@comments_column", "]", ":", "nil", "key", ".", "strip!", "if", "@stripping", "default_value", "=", "self", ".", "default_lang", "?", "row", "[", "defaultCol", "]", ":", "nil", "value", "=", "self", ".", "process_value", "(", "row", "[", "i", "]", ",", "default_value", ")", "@comments", "[", "key", "]", "=", "comment", "@languages", "[", "i", "]", ".", "add_content_pair", "(", "key", ",", "value", ")", "end", "end", "rowIndex", "+=", "1", "end", "write_content", "end" ]
Convert csv file to multiple Localizable.strings files for each column
[ "Convert", "csv", "file", "to", "multiple", "Localizable", ".", "strings", "files", "for", "each", "column" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/csv2base.rb#L97-L147
train
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.convert
def convert(write_to_file = true) strings = {} keys = nil comments = {} @filenames.each do |fname| header = fname strings[header], file_comments = load_strings(fname) keys ||= strings[header].keys comments.merge!(file_comments) unless file_comments.nil? end if write_to_file # Create csv file puts "Creating #{@csv_filename}" create_csv_file(keys, strings, comments) else return keys, strings end end
ruby
def convert(write_to_file = true) strings = {} keys = nil comments = {} @filenames.each do |fname| header = fname strings[header], file_comments = load_strings(fname) keys ||= strings[header].keys comments.merge!(file_comments) unless file_comments.nil? end if write_to_file # Create csv file puts "Creating #{@csv_filename}" create_csv_file(keys, strings, comments) else return keys, strings end end
[ "def", "convert", "(", "write_to_file", "=", "true", ")", "strings", "=", "{", "}", "keys", "=", "nil", "comments", "=", "{", "}", "@filenames", ".", "each", "do", "|", "fname", "|", "header", "=", "fname", "strings", "[", "header", "]", ",", "file_comments", "=", "load_strings", "(", "fname", ")", "keys", "||=", "strings", "[", "header", "]", ".", "keys", "comments", ".", "merge!", "(", "file_comments", ")", "unless", "file_comments", ".", "nil?", "end", "if", "write_to_file", "# Create csv file", "puts", "\"Creating #{@csv_filename}\"", "create_csv_file", "(", "keys", ",", "strings", ",", "comments", ")", "else", "return", "keys", ",", "strings", "end", "end" ]
Process files and create csv @param [Boolean] write_to_file create or not the csv file @return [Hash] the translations formatted if write_to_file
[ "Process", "files", "and", "create", "csv" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L24-L43
train
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.basename
def basename(file_path) filename = File.basename(file_path) return filename.split('.')[0].to_sym if file_path end
ruby
def basename(file_path) filename = File.basename(file_path) return filename.split('.')[0].to_sym if file_path end
[ "def", "basename", "(", "file_path", ")", "filename", "=", "File", ".", "basename", "(", "file_path", ")", "return", "filename", ".", "split", "(", "'.'", ")", "[", "0", "]", ".", "to_sym", "if", "file_path", "end" ]
Basename of given file @param [String, #read] file_path @return [String] basename
[ "Basename", "of", "given", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L71-L74
train
netbe/Babelish
lib/babelish/base2csv.rb
Babelish.Base2Csv.create_csv_file
def create_csv_file(keys, strings, comments = nil) raise "csv_filename must not be nil" unless @csv_filename CSV.open(@csv_filename, "wb") do |csv| @headers << "Comments" if !comments.nil? && !comments.empty? csv << @headers keys.each do |key| line = [key] default_val = strings[@default_lang][key] if strings[@default_lang] @filenames.each do |fname| lang = fname current_val = (lang != default_lang && strings[lang][key] == default_val) ? '' : strings[lang][key] line << current_val end line << comments[key] if comments && comments[key] csv << line end puts "Done" end end
ruby
def create_csv_file(keys, strings, comments = nil) raise "csv_filename must not be nil" unless @csv_filename CSV.open(@csv_filename, "wb") do |csv| @headers << "Comments" if !comments.nil? && !comments.empty? csv << @headers keys.each do |key| line = [key] default_val = strings[@default_lang][key] if strings[@default_lang] @filenames.each do |fname| lang = fname current_val = (lang != default_lang && strings[lang][key] == default_val) ? '' : strings[lang][key] line << current_val end line << comments[key] if comments && comments[key] csv << line end puts "Done" end end
[ "def", "create_csv_file", "(", "keys", ",", "strings", ",", "comments", "=", "nil", ")", "raise", "\"csv_filename must not be nil\"", "unless", "@csv_filename", "CSV", ".", "open", "(", "@csv_filename", ",", "\"wb\"", ")", "do", "|", "csv", "|", "@headers", "<<", "\"Comments\"", "if", "!", "comments", ".", "nil?", "&&", "!", "comments", ".", "empty?", "csv", "<<", "@headers", "keys", ".", "each", "do", "|", "key", "|", "line", "=", "[", "key", "]", "default_val", "=", "strings", "[", "@default_lang", "]", "[", "key", "]", "if", "strings", "[", "@default_lang", "]", "@filenames", ".", "each", "do", "|", "fname", "|", "lang", "=", "fname", "current_val", "=", "(", "lang", "!=", "default_lang", "&&", "strings", "[", "lang", "]", "[", "key", "]", "==", "default_val", ")", "?", "''", ":", "strings", "[", "lang", "]", "[", "key", "]", "line", "<<", "current_val", "end", "line", "<<", "comments", "[", "key", "]", "if", "comments", "&&", "comments", "[", "key", "]", "csv", "<<", "line", "end", "puts", "\"Done\"", "end", "end" ]
Create the resulting file @param [Array] keys references of all translations @param [Array] strings translations of all languages @param [Hash] comments hash containing keys, comments related to each keys, describe the translation
[ "Create", "the", "resulting", "file" ]
1fd8488322b3422f038bd440d6e6b06d8b1ea202
https://github.com/netbe/Babelish/blob/1fd8488322b3422f038bd440d6e6b06d8b1ea202/lib/babelish/base2csv.rb#L83-L101
train
janlelis/clipboard
lib/clipboard/utils.rb
Clipboard.Utils.popen
def popen(cmd, data, read_output_stream = false) Open3.popen2(cmd) { |input, output, waiter_thread| output_thread = Thread.new { output.read } if read_output_stream begin input.write data rescue Errno::EPIPE end input.close output_thread.value if read_output_stream waiter_thread.value } end
ruby
def popen(cmd, data, read_output_stream = false) Open3.popen2(cmd) { |input, output, waiter_thread| output_thread = Thread.new { output.read } if read_output_stream begin input.write data rescue Errno::EPIPE end input.close output_thread.value if read_output_stream waiter_thread.value } end
[ "def", "popen", "(", "cmd", ",", "data", ",", "read_output_stream", "=", "false", ")", "Open3", ".", "popen2", "(", "cmd", ")", "{", "|", "input", ",", "output", ",", "waiter_thread", "|", "output_thread", "=", "Thread", ".", "new", "{", "output", ".", "read", "}", "if", "read_output_stream", "begin", "input", ".", "write", "data", "rescue", "Errno", "::", "EPIPE", "end", "input", ".", "close", "output_thread", ".", "value", "if", "read_output_stream", "waiter_thread", ".", "value", "}", "end" ]
Utility to call external command - pure .popen2 becomes messy with xsel when not reading the output stream - xclip doesn't like to have output stream read
[ "Utility", "to", "call", "external", "command", "-", "pure", ".", "popen2", "becomes", "messy", "with", "xsel", "when", "not", "reading", "the", "output", "stream", "-", "xclip", "doesn", "t", "like", "to", "have", "output", "stream", "read" ]
a2d406dd9f93d304e11059176c9c1dc978bfc87b
https://github.com/janlelis/clipboard/blob/a2d406dd9f93d304e11059176c9c1dc978bfc87b/lib/clipboard/utils.rb#L18-L31
train
neovim/neovim-ruby
lib/neovim/executable.rb
Neovim.Executable.version
def version @version ||= IO.popen([@path, "--version"]) do |io| io.gets[VERSION_PATTERN, 1] end rescue => e raise Error, "Couldn't load #{@path}: #{e}" end
ruby
def version @version ||= IO.popen([@path, "--version"]) do |io| io.gets[VERSION_PATTERN, 1] end rescue => e raise Error, "Couldn't load #{@path}: #{e}" end
[ "def", "version", "@version", "||=", "IO", ".", "popen", "(", "[", "@path", ",", "\"--version\"", "]", ")", "do", "|", "io", "|", "io", ".", "gets", "[", "VERSION_PATTERN", ",", "1", "]", "end", "rescue", "=>", "e", "raise", "Error", ",", "\"Couldn't load #{@path}: #{e}\"", "end" ]
Fetch the +nvim+ version. @return [String]
[ "Fetch", "the", "+", "nvim", "+", "version", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/executable.rb#L26-L32
train
neovim/neovim-ruby
lib/neovim/api.rb
Neovim.API.functions
def functions @functions ||= @api_info.fetch("functions").inject({}) do |acc, func| function = Function.new(func) acc.merge(function.name => function) end end
ruby
def functions @functions ||= @api_info.fetch("functions").inject({}) do |acc, func| function = Function.new(func) acc.merge(function.name => function) end end
[ "def", "functions", "@functions", "||=", "@api_info", ".", "fetch", "(", "\"functions\"", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "acc", ",", "func", "|", "function", "=", "Function", ".", "new", "(", "func", ")", "acc", ".", "merge", "(", "function", ".", "name", "=>", "function", ")", "end", "end" ]
Return all functions defined by the API.
[ "Return", "all", "functions", "defined", "by", "the", "API", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/api.rb#L11-L16
train
neovim/neovim-ruby
lib/neovim/window.rb
Neovim.Window.cursor=
def cursor=(coords) x, y = coords x = [x, 1].max y = [y, 0].max + 1 @session.request(:nvim_eval, "cursor(#{x}, #{y})") end
ruby
def cursor=(coords) x, y = coords x = [x, 1].max y = [y, 0].max + 1 @session.request(:nvim_eval, "cursor(#{x}, #{y})") end
[ "def", "cursor", "=", "(", "coords", ")", "x", ",", "y", "=", "coords", "x", "=", "[", "x", ",", "1", "]", ".", "max", "y", "=", "[", "y", ",", "0", "]", ".", "max", "+", "1", "@session", ".", "request", "(", ":nvim_eval", ",", "\"cursor(#{x}, #{y})\"", ")", "end" ]
Set the cursor coodinates @param coords [Array(Integer, Integer)] @return [Array(Integer, Integer)]
[ "Set", "the", "cursor", "coodinates" ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/window.rb#L58-L63
train
neovim/neovim-ruby
lib/neovim/line_range.rb
Neovim.LineRange.each
def each(&block) ([email protected]).each_slice(5000) do |linenos| start, stop = linenos[0], linenos[-1] + 1 @buffer.get_lines(start, stop, true).each(&block) end end
ruby
def each(&block) ([email protected]).each_slice(5000) do |linenos| start, stop = linenos[0], linenos[-1] + 1 @buffer.get_lines(start, stop, true).each(&block) end end
[ "def", "each", "(", "&", "block", ")", "(", "0", "...", "@buffer", ".", "count", ")", ".", "each_slice", "(", "5000", ")", "do", "|", "linenos", "|", "start", ",", "stop", "=", "linenos", "[", "0", "]", ",", "linenos", "[", "-", "1", "]", "+", "1", "@buffer", ".", "get_lines", "(", "start", ",", "stop", ",", "true", ")", ".", "each", "(", "block", ")", "end", "end" ]
Satisfy the +Enumerable+ interface by yielding each line. @yieldparam line [String]
[ "Satisfy", "the", "+", "Enumerable", "+", "interface", "by", "yielding", "each", "line", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/line_range.rb#L13-L18
train
neovim/neovim-ruby
lib/neovim/line_range.rb
Neovim.LineRange.[]=
def []=(*args) *target, val = args pos, len = target if pos.is_a?(Range) @buffer.set_lines(*range_indices(pos), true, Array(val)) else start, stop = length_indices(pos, len || 1) @buffer.set_lines(start, stop, true, Array(val)) end end
ruby
def []=(*args) *target, val = args pos, len = target if pos.is_a?(Range) @buffer.set_lines(*range_indices(pos), true, Array(val)) else start, stop = length_indices(pos, len || 1) @buffer.set_lines(start, stop, true, Array(val)) end end
[ "def", "[]=", "(", "*", "args", ")", "*", "target", ",", "val", "=", "args", "pos", ",", "len", "=", "target", "if", "pos", ".", "is_a?", "(", "Range", ")", "@buffer", ".", "set_lines", "(", "range_indices", "(", "pos", ")", ",", "true", ",", "Array", "(", "val", ")", ")", "else", "start", ",", "stop", "=", "length_indices", "(", "pos", ",", "len", "||", "1", ")", "@buffer", ".", "set_lines", "(", "start", ",", "stop", ",", "true", ",", "Array", "(", "val", ")", ")", "end", "end" ]
Set a line or line range. @overload []=(index, string) @param index [Integer] @param string [String] @overload []=(index, length, strings) @param index [Integer] @param length [Integer] @param strings [Array<String>] @overload []=(range, strings) @param range [Range] @param strings [Array<String>] @example Replace the first line using an index line_range[0] = "first" @example Replace the first two lines using a +Range+ line_range[0..1] = ["first", "second"] @example Replace the first two lines using an index and length line_range[0, 2] = ["first", "second"]
[ "Set", "a", "line", "or", "line", "range", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/line_range.rb#L84-L94
train
neovim/neovim-ruby
lib/neovim/session.rb
Neovim.Session.request
def request(method, *args) main_thread_only do @request_id += 1 blocking = Fiber.current == @main_fiber log(:debug) do { method_name: method, request_id: @request_id, blocking: blocking, arguments: args } end @event_loop.request(@request_id, method, *args) response = blocking ? blocking_response : yielding_response raise(Exited) if response.nil? raise(response.error) if response.error response.value end end
ruby
def request(method, *args) main_thread_only do @request_id += 1 blocking = Fiber.current == @main_fiber log(:debug) do { method_name: method, request_id: @request_id, blocking: blocking, arguments: args } end @event_loop.request(@request_id, method, *args) response = blocking ? blocking_response : yielding_response raise(Exited) if response.nil? raise(response.error) if response.error response.value end end
[ "def", "request", "(", "method", ",", "*", "args", ")", "main_thread_only", "do", "@request_id", "+=", "1", "blocking", "=", "Fiber", ".", "current", "==", "@main_fiber", "log", "(", ":debug", ")", "do", "{", "method_name", ":", "method", ",", "request_id", ":", "@request_id", ",", "blocking", ":", "blocking", ",", "arguments", ":", "args", "}", "end", "@event_loop", ".", "request", "(", "@request_id", ",", "method", ",", "args", ")", "response", "=", "blocking", "?", "blocking_response", ":", "yielding_response", "raise", "(", "Exited", ")", "if", "response", ".", "nil?", "raise", "(", "response", ".", "error", ")", "if", "response", ".", "error", "response", ".", "value", "end", "end" ]
Make an RPC request and return its response. If this method is called inside a callback, we are already inside a +Fiber+ handler. In that case, we write to the stream and yield the +Fiber+. Once the response is received, resume the +Fiber+ and return the result. If this method is called outside a callback, write to the stream and run the event loop until a response is received. Messages received in the meantime are enqueued to be handled later.
[ "Make", "an", "RPC", "request", "and", "return", "its", "response", "." ]
3c58db971226219b9f373a8abb359be3f26b3b52
https://github.com/neovim/neovim-ruby/blob/3c58db971226219b9f373a8abb359be3f26b3b52/lib/neovim/session.rb#L54-L75
train
onfido/tzu_mock
lib/tzu_mock/mocker.rb
TzuMock.Mocker.mock_proc
def mock_proc(klass, methods, success, result, type) Proc.new do methods.each do |method| allow(klass).to receive(method) do |&block| outcome = Tzu::Outcome.new(success, result, type) outcome.handle(&block) if block outcome end end end end
ruby
def mock_proc(klass, methods, success, result, type) Proc.new do methods.each do |method| allow(klass).to receive(method) do |&block| outcome = Tzu::Outcome.new(success, result, type) outcome.handle(&block) if block outcome end end end end
[ "def", "mock_proc", "(", "klass", ",", "methods", ",", "success", ",", "result", ",", "type", ")", "Proc", ".", "new", "do", "methods", ".", "each", "do", "|", "method", "|", "allow", "(", "klass", ")", ".", "to", "receive", "(", "method", ")", "do", "|", "&", "block", "|", "outcome", "=", "Tzu", "::", "Outcome", ".", "new", "(", "success", ",", "result", ",", "type", ")", "outcome", ".", "handle", "(", "block", ")", "if", "block", "outcome", "end", "end", "end", "end" ]
Need to pass variables in explicity to give the Proc access to them
[ "Need", "to", "pass", "variables", "in", "explicity", "to", "give", "the", "Proc", "access", "to", "them" ]
6fd135b825cdce664e6ca2427cb93f08a8621651
https://github.com/onfido/tzu_mock/blob/6fd135b825cdce664e6ca2427cb93f08a8621651/lib/tzu_mock/mocker.rb#L21-L31
train
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.find_solution
def find_solution(solution_constraints, valid_packages = nil) # this is a performance optimization so that packages that are # completely unreachable by the solution constraints don't get # added to the CSP packages_to_include_in_solve = trim_unreachable_packages(dep_graph, solution_constraints) begin # first, try to solve the whole set of constraints solve(dep_graph.clone, solution_constraints, valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound, Exceptions::TimeBoundExceededNoSolution # since we're here, solving the whole system failed, so add # the solution_constraints one-by-one and try to solve in # order to find the constraint that breaks the system in order # to give helpful debugging info # # TODO [cw,2010/11/28]: for an efficiency gain, instead of # continually re-building the problem and looking for a # solution, turn solution_constraints into a Generator and # iteratively add and solve in order to re-use # propagations. This will require separating setting up the # constraints from searching for the solution. Timeout::timeout(@time_bound, Exceptions::TimeBoundExceededNoSolution) do solution_constraints.each_index do |idx| workspace = dep_graph.clone begin solve(workspace, solution_constraints[0..idx], valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound => nsf disabled_packages = packages_to_include_in_solve.inject([]) do |acc, elt| pkg = workspace.package(elt.name) acc << pkg if nsf.unsatisfiable_problem.is_package_disabled?(pkg.gecode_package_id) acc end # disambiguate between packages disabled becuase they # don't exist and those that have otherwise problematic # constraints disabled_non_existent_packages = [] disabled_most_constrained_packages = [] disabled_packages.each do |disabled_pkg| disabled_collection = if disabled_pkg.valid? || (valid_packages && valid_packages.include?(disabled_pkg)) disabled_most_constrained_packages else disabled_non_existent_packages end disabled_collection << disabled_pkg end # Pick the first non-existent or most-constrained package # that was required or the package whose constraints had # to be disabled in order to find a solution and generate # feedback for it. We only report feedback for one # package, because it is in fact actionable and dispalying # feedback for every disabled package would probably be # too long. The full set of disabled packages is # accessible in the NoSolutionExists exception. disabled_package_to_report_on = disabled_non_existent_packages.first || disabled_most_constrained_packages.first feedback = error_reporter.give_feedback(dep_graph, solution_constraints, idx, disabled_package_to_report_on) raise Exceptions::NoSolutionExists.new(feedback, solution_constraints[idx], disabled_non_existent_packages, disabled_most_constrained_packages) end end end end end
ruby
def find_solution(solution_constraints, valid_packages = nil) # this is a performance optimization so that packages that are # completely unreachable by the solution constraints don't get # added to the CSP packages_to_include_in_solve = trim_unreachable_packages(dep_graph, solution_constraints) begin # first, try to solve the whole set of constraints solve(dep_graph.clone, solution_constraints, valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound, Exceptions::TimeBoundExceededNoSolution # since we're here, solving the whole system failed, so add # the solution_constraints one-by-one and try to solve in # order to find the constraint that breaks the system in order # to give helpful debugging info # # TODO [cw,2010/11/28]: for an efficiency gain, instead of # continually re-building the problem and looking for a # solution, turn solution_constraints into a Generator and # iteratively add and solve in order to re-use # propagations. This will require separating setting up the # constraints from searching for the solution. Timeout::timeout(@time_bound, Exceptions::TimeBoundExceededNoSolution) do solution_constraints.each_index do |idx| workspace = dep_graph.clone begin solve(workspace, solution_constraints[0..idx], valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound => nsf disabled_packages = packages_to_include_in_solve.inject([]) do |acc, elt| pkg = workspace.package(elt.name) acc << pkg if nsf.unsatisfiable_problem.is_package_disabled?(pkg.gecode_package_id) acc end # disambiguate between packages disabled becuase they # don't exist and those that have otherwise problematic # constraints disabled_non_existent_packages = [] disabled_most_constrained_packages = [] disabled_packages.each do |disabled_pkg| disabled_collection = if disabled_pkg.valid? || (valid_packages && valid_packages.include?(disabled_pkg)) disabled_most_constrained_packages else disabled_non_existent_packages end disabled_collection << disabled_pkg end # Pick the first non-existent or most-constrained package # that was required or the package whose constraints had # to be disabled in order to find a solution and generate # feedback for it. We only report feedback for one # package, because it is in fact actionable and dispalying # feedback for every disabled package would probably be # too long. The full set of disabled packages is # accessible in the NoSolutionExists exception. disabled_package_to_report_on = disabled_non_existent_packages.first || disabled_most_constrained_packages.first feedback = error_reporter.give_feedback(dep_graph, solution_constraints, idx, disabled_package_to_report_on) raise Exceptions::NoSolutionExists.new(feedback, solution_constraints[idx], disabled_non_existent_packages, disabled_most_constrained_packages) end end end end end
[ "def", "find_solution", "(", "solution_constraints", ",", "valid_packages", "=", "nil", ")", "# this is a performance optimization so that packages that are", "# completely unreachable by the solution constraints don't get", "# added to the CSP", "packages_to_include_in_solve", "=", "trim_unreachable_packages", "(", "dep_graph", ",", "solution_constraints", ")", "begin", "# first, try to solve the whole set of constraints", "solve", "(", "dep_graph", ".", "clone", ",", "solution_constraints", ",", "valid_packages", ",", "packages_to_include_in_solve", ")", "rescue", "Exceptions", "::", "NoSolutionFound", ",", "Exceptions", "::", "TimeBoundExceededNoSolution", "# since we're here, solving the whole system failed, so add", "# the solution_constraints one-by-one and try to solve in", "# order to find the constraint that breaks the system in order", "# to give helpful debugging info", "#", "# TODO [cw,2010/11/28]: for an efficiency gain, instead of", "# continually re-building the problem and looking for a", "# solution, turn solution_constraints into a Generator and", "# iteratively add and solve in order to re-use", "# propagations. This will require separating setting up the", "# constraints from searching for the solution.", "Timeout", "::", "timeout", "(", "@time_bound", ",", "Exceptions", "::", "TimeBoundExceededNoSolution", ")", "do", "solution_constraints", ".", "each_index", "do", "|", "idx", "|", "workspace", "=", "dep_graph", ".", "clone", "begin", "solve", "(", "workspace", ",", "solution_constraints", "[", "0", "..", "idx", "]", ",", "valid_packages", ",", "packages_to_include_in_solve", ")", "rescue", "Exceptions", "::", "NoSolutionFound", "=>", "nsf", "disabled_packages", "=", "packages_to_include_in_solve", ".", "inject", "(", "[", "]", ")", "do", "|", "acc", ",", "elt", "|", "pkg", "=", "workspace", ".", "package", "(", "elt", ".", "name", ")", "acc", "<<", "pkg", "if", "nsf", ".", "unsatisfiable_problem", ".", "is_package_disabled?", "(", "pkg", ".", "gecode_package_id", ")", "acc", "end", "# disambiguate between packages disabled becuase they", "# don't exist and those that have otherwise problematic", "# constraints", "disabled_non_existent_packages", "=", "[", "]", "disabled_most_constrained_packages", "=", "[", "]", "disabled_packages", ".", "each", "do", "|", "disabled_pkg", "|", "disabled_collection", "=", "if", "disabled_pkg", ".", "valid?", "||", "(", "valid_packages", "&&", "valid_packages", ".", "include?", "(", "disabled_pkg", ")", ")", "disabled_most_constrained_packages", "else", "disabled_non_existent_packages", "end", "disabled_collection", "<<", "disabled_pkg", "end", "# Pick the first non-existent or most-constrained package", "# that was required or the package whose constraints had", "# to be disabled in order to find a solution and generate", "# feedback for it. We only report feedback for one", "# package, because it is in fact actionable and dispalying", "# feedback for every disabled package would probably be", "# too long. The full set of disabled packages is", "# accessible in the NoSolutionExists exception.", "disabled_package_to_report_on", "=", "disabled_non_existent_packages", ".", "first", "||", "disabled_most_constrained_packages", ".", "first", "feedback", "=", "error_reporter", ".", "give_feedback", "(", "dep_graph", ",", "solution_constraints", ",", "idx", ",", "disabled_package_to_report_on", ")", "raise", "Exceptions", "::", "NoSolutionExists", ".", "new", "(", "feedback", ",", "solution_constraints", "[", "idx", "]", ",", "disabled_non_existent_packages", ",", "disabled_most_constrained_packages", ")", "end", "end", "end", "end", "end" ]
Based on solution_constraints, this method tries to find an assignment of PackageVersions that is compatible with the DependencyGraph. If one cannot be found, the constraints are added one at a time until the first unsatisfiable constraint is detected. Once the unsatisfiable solution constraint is identified, required non-existent packages and the most constrained packages are identified and thrown in a NoSolutionExists exception. If a solution constraint refers to a package that doesn't exist or the constraint matches no versions, it is considered invalid. All invalid solution constraints are collected and raised in an InvalidSolutionConstraints exception. If valid_packages is non-nil, it is considered the authoritative list of extant Packages; otherwise, Package#valid? is used. This is useful if the dependency graph represents an already filtered set of packages such that a Package actually exists in your domain but is added to the dependency graph with no versions, in which case Package#valid? would return false even though we don't want to report that the package is non-existent.
[ "Based", "on", "solution_constraints", "this", "method", "tries", "to", "find", "an", "assignment", "of", "PackageVersions", "that", "is", "compatible", "with", "the", "DependencyGraph", ".", "If", "one", "cannot", "be", "found", "the", "constraints", "are", "added", "one", "at", "a", "time", "until", "the", "first", "unsatisfiable", "constraint", "is", "detected", ".", "Once", "the", "unsatisfiable", "solution", "constraint", "is", "identified", "required", "non", "-", "existent", "packages", "and", "the", "most", "constrained", "packages", "are", "identified", "and", "thrown", "in", "a", "NoSolutionExists", "exception", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L63-L131
train
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.process_soln_constraints
def process_soln_constraints(workspace, solution_constraints, valid_packages) gecode = workspace.gecode_wrapper # create shadow package whose dependencies are the solution constraints soln_constraints_pkg_id = gecode.add_package(0, 0, 0) soln_constraints_on_non_existent_packages = [] soln_constraints_that_match_no_versions = [] # generate constraints imposed by solution_constraints solution_constraints.each do |soln_constraint| # look up the package in the cloned dep_graph that corresponds to soln_constraint pkg_name = soln_constraint.package.name pkg = workspace.package(pkg_name) constraint = soln_constraint.constraint # record invalid solution constraints and raise an exception # afterwards unless pkg.valid? || (valid_packages && valid_packages.include?(pkg)) soln_constraints_on_non_existent_packages << soln_constraint next end if pkg[constraint].empty? soln_constraints_that_match_no_versions << soln_constraint next end pkg_id = pkg.gecode_package_id gecode.mark_preferred_to_be_at_latest(pkg_id, 10) gecode.mark_required(pkg_id) if constraint acceptable_versions = pkg.densely_packed_versions[constraint] gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, acceptable_versions.min, acceptable_versions.max) else # this restricts the domain of the variable to >= 0, which # means -1, the shadow package, cannot be assigned, meaning # the package must be bound to an actual version gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, 0, pkg.densely_packed_versions.range.max) end end if soln_constraints_on_non_existent_packages.any? || soln_constraints_that_match_no_versions.any? raise Exceptions::InvalidSolutionConstraints.new(soln_constraints_on_non_existent_packages, soln_constraints_that_match_no_versions) end end
ruby
def process_soln_constraints(workspace, solution_constraints, valid_packages) gecode = workspace.gecode_wrapper # create shadow package whose dependencies are the solution constraints soln_constraints_pkg_id = gecode.add_package(0, 0, 0) soln_constraints_on_non_existent_packages = [] soln_constraints_that_match_no_versions = [] # generate constraints imposed by solution_constraints solution_constraints.each do |soln_constraint| # look up the package in the cloned dep_graph that corresponds to soln_constraint pkg_name = soln_constraint.package.name pkg = workspace.package(pkg_name) constraint = soln_constraint.constraint # record invalid solution constraints and raise an exception # afterwards unless pkg.valid? || (valid_packages && valid_packages.include?(pkg)) soln_constraints_on_non_existent_packages << soln_constraint next end if pkg[constraint].empty? soln_constraints_that_match_no_versions << soln_constraint next end pkg_id = pkg.gecode_package_id gecode.mark_preferred_to_be_at_latest(pkg_id, 10) gecode.mark_required(pkg_id) if constraint acceptable_versions = pkg.densely_packed_versions[constraint] gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, acceptable_versions.min, acceptable_versions.max) else # this restricts the domain of the variable to >= 0, which # means -1, the shadow package, cannot be assigned, meaning # the package must be bound to an actual version gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, 0, pkg.densely_packed_versions.range.max) end end if soln_constraints_on_non_existent_packages.any? || soln_constraints_that_match_no_versions.any? raise Exceptions::InvalidSolutionConstraints.new(soln_constraints_on_non_existent_packages, soln_constraints_that_match_no_versions) end end
[ "def", "process_soln_constraints", "(", "workspace", ",", "solution_constraints", ",", "valid_packages", ")", "gecode", "=", "workspace", ".", "gecode_wrapper", "# create shadow package whose dependencies are the solution constraints", "soln_constraints_pkg_id", "=", "gecode", ".", "add_package", "(", "0", ",", "0", ",", "0", ")", "soln_constraints_on_non_existent_packages", "=", "[", "]", "soln_constraints_that_match_no_versions", "=", "[", "]", "# generate constraints imposed by solution_constraints", "solution_constraints", ".", "each", "do", "|", "soln_constraint", "|", "# look up the package in the cloned dep_graph that corresponds to soln_constraint", "pkg_name", "=", "soln_constraint", ".", "package", ".", "name", "pkg", "=", "workspace", ".", "package", "(", "pkg_name", ")", "constraint", "=", "soln_constraint", ".", "constraint", "# record invalid solution constraints and raise an exception", "# afterwards", "unless", "pkg", ".", "valid?", "||", "(", "valid_packages", "&&", "valid_packages", ".", "include?", "(", "pkg", ")", ")", "soln_constraints_on_non_existent_packages", "<<", "soln_constraint", "next", "end", "if", "pkg", "[", "constraint", "]", ".", "empty?", "soln_constraints_that_match_no_versions", "<<", "soln_constraint", "next", "end", "pkg_id", "=", "pkg", ".", "gecode_package_id", "gecode", ".", "mark_preferred_to_be_at_latest", "(", "pkg_id", ",", "10", ")", "gecode", ".", "mark_required", "(", "pkg_id", ")", "if", "constraint", "acceptable_versions", "=", "pkg", ".", "densely_packed_versions", "[", "constraint", "]", "gecode", ".", "add_version_constraint", "(", "soln_constraints_pkg_id", ",", "0", ",", "pkg_id", ",", "acceptable_versions", ".", "min", ",", "acceptable_versions", ".", "max", ")", "else", "# this restricts the domain of the variable to >= 0, which", "# means -1, the shadow package, cannot be assigned, meaning", "# the package must be bound to an actual version", "gecode", ".", "add_version_constraint", "(", "soln_constraints_pkg_id", ",", "0", ",", "pkg_id", ",", "0", ",", "pkg", ".", "densely_packed_versions", ".", "range", ".", "max", ")", "end", "end", "if", "soln_constraints_on_non_existent_packages", ".", "any?", "||", "soln_constraints_that_match_no_versions", ".", "any?", "raise", "Exceptions", "::", "InvalidSolutionConstraints", ".", "new", "(", "soln_constraints_on_non_existent_packages", ",", "soln_constraints_that_match_no_versions", ")", "end", "end" ]
This method validates SolutionConstraints and adds their corresponding constraints to the workspace.
[ "This", "method", "validates", "SolutionConstraints", "and", "adds", "their", "corresponding", "constraints", "to", "the", "workspace", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L156-L203
train
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.trim_solution
def trim_solution(soln_constraints, soln, workspace) trimmed_soln = {} soln_constraints.each do |soln_constraint| package = workspace.package(soln_constraint.package.name) expand_package(trimmed_soln, package, soln) end trimmed_soln end
ruby
def trim_solution(soln_constraints, soln, workspace) trimmed_soln = {} soln_constraints.each do |soln_constraint| package = workspace.package(soln_constraint.package.name) expand_package(trimmed_soln, package, soln) end trimmed_soln end
[ "def", "trim_solution", "(", "soln_constraints", ",", "soln", ",", "workspace", ")", "trimmed_soln", "=", "{", "}", "soln_constraints", ".", "each", "do", "|", "soln_constraint", "|", "package", "=", "workspace", ".", "package", "(", "soln_constraint", ".", "package", ".", "name", ")", "expand_package", "(", "trimmed_soln", ",", "package", ",", "soln", ")", "end", "trimmed_soln", "end" ]
Given an assignment of versions to packages, filter down to only the required assignments
[ "Given", "an", "assignment", "of", "versions", "to", "packages", "filter", "down", "to", "only", "the", "required", "assignments" ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L207-L217
train
chef/dep-selector
lib/dep_selector/selector.rb
DepSelector.Selector.trim_unreachable_packages
def trim_unreachable_packages(workspace, soln_constraints) reachable_packages = [] soln_constraints.each do |soln_constraint| find_reachable_packages(workspace, soln_constraint.package, soln_constraint.constraint, reachable_packages) end reachable_packages end
ruby
def trim_unreachable_packages(workspace, soln_constraints) reachable_packages = [] soln_constraints.each do |soln_constraint| find_reachable_packages(workspace, soln_constraint.package, soln_constraint.constraint, reachable_packages) end reachable_packages end
[ "def", "trim_unreachable_packages", "(", "workspace", ",", "soln_constraints", ")", "reachable_packages", "=", "[", "]", "soln_constraints", ".", "each", "do", "|", "soln_constraint", "|", "find_reachable_packages", "(", "workspace", ",", "soln_constraint", ".", "package", ",", "soln_constraint", ".", "constraint", ",", "reachable_packages", ")", "end", "reachable_packages", "end" ]
Given a workspace and solution constraints, this method returns an array that includes only packages that can be induced by the solution constraints.
[ "Given", "a", "workspace", "and", "solution", "constraints", "this", "method", "returns", "an", "array", "that", "includes", "only", "packages", "that", "can", "be", "induced", "by", "the", "solution", "constraints", "." ]
48b05738be2c9ce28ca5ed83681291b9e0d87d6c
https://github.com/chef/dep-selector/blob/48b05738be2c9ce28ca5ed83681291b9e0d87d6c/lib/dep_selector/selector.rb#L238-L248
train
janko/tus-ruby-server
lib/tus/server.rb
Tus.Server.validate_partial_uploads!
def validate_partial_uploads!(part_uids) input = Queue.new part_uids.each { |part_uid| input << part_uid } input.close results = Queue.new thread_count = storage.concurrency[:concatenation] if storage.respond_to?(:concurrency) thread_count ||= 10 threads = thread_count.times.map do Thread.new do begin loop do part_uid = input.pop or break part_info = storage.read_info(part_uid) results << Tus::Info.new(part_info) end nil rescue => error input.clear error end end end errors = threads.map(&:value).compact if errors.any? { |error| error.is_a?(Tus::NotFound) } error!(400, "One or more partial uploads were not found") elsif errors.any? fail errors.first end part_infos = Array.new(results.size) { results.pop } # convert Queue into an Array unless part_infos.all?(&:partial?) error!(400, "One or more uploads were not partial") end if max_size && part_infos.map(&:length).inject(0, :+) > max_size error!(400, "The sum of partial upload lengths exceed Tus-Max-Size") end end
ruby
def validate_partial_uploads!(part_uids) input = Queue.new part_uids.each { |part_uid| input << part_uid } input.close results = Queue.new thread_count = storage.concurrency[:concatenation] if storage.respond_to?(:concurrency) thread_count ||= 10 threads = thread_count.times.map do Thread.new do begin loop do part_uid = input.pop or break part_info = storage.read_info(part_uid) results << Tus::Info.new(part_info) end nil rescue => error input.clear error end end end errors = threads.map(&:value).compact if errors.any? { |error| error.is_a?(Tus::NotFound) } error!(400, "One or more partial uploads were not found") elsif errors.any? fail errors.first end part_infos = Array.new(results.size) { results.pop } # convert Queue into an Array unless part_infos.all?(&:partial?) error!(400, "One or more uploads were not partial") end if max_size && part_infos.map(&:length).inject(0, :+) > max_size error!(400, "The sum of partial upload lengths exceed Tus-Max-Size") end end
[ "def", "validate_partial_uploads!", "(", "part_uids", ")", "input", "=", "Queue", ".", "new", "part_uids", ".", "each", "{", "|", "part_uid", "|", "input", "<<", "part_uid", "}", "input", ".", "close", "results", "=", "Queue", ".", "new", "thread_count", "=", "storage", ".", "concurrency", "[", ":concatenation", "]", "if", "storage", ".", "respond_to?", "(", ":concurrency", ")", "thread_count", "||=", "10", "threads", "=", "thread_count", ".", "times", ".", "map", "do", "Thread", ".", "new", "do", "begin", "loop", "do", "part_uid", "=", "input", ".", "pop", "or", "break", "part_info", "=", "storage", ".", "read_info", "(", "part_uid", ")", "results", "<<", "Tus", "::", "Info", ".", "new", "(", "part_info", ")", "end", "nil", "rescue", "=>", "error", "input", ".", "clear", "error", "end", "end", "end", "errors", "=", "threads", ".", "map", "(", ":value", ")", ".", "compact", "if", "errors", ".", "any?", "{", "|", "error", "|", "error", ".", "is_a?", "(", "Tus", "::", "NotFound", ")", "}", "error!", "(", "400", ",", "\"One or more partial uploads were not found\"", ")", "elsif", "errors", ".", "any?", "fail", "errors", ".", "first", "end", "part_infos", "=", "Array", ".", "new", "(", "results", ".", "size", ")", "{", "results", ".", "pop", "}", "# convert Queue into an Array", "unless", "part_infos", ".", "all?", "(", ":partial?", ")", "error!", "(", "400", ",", "\"One or more uploads were not partial\"", ")", "end", "if", "max_size", "&&", "part_infos", ".", "map", "(", ":length", ")", ".", "inject", "(", "0", ",", ":+", ")", ">", "max_size", "error!", "(", "400", ",", "\"The sum of partial upload lengths exceed Tus-Max-Size\"", ")", "end", "end" ]
Validates that each partial upload exists and is marked as one.
[ "Validates", "that", "each", "partial", "upload", "exists", "and", "is", "marked", "as", "one", "." ]
8e8cb77a10a83c1e61263107b8bfd7934ac45638
https://github.com/janko/tus-ruby-server/blob/8e8cb77a10a83c1e61263107b8bfd7934ac45638/lib/tus/server.rb#L309-L352
train
wvanbergen/chunky_png
lib/chunky_png/image.rb
ChunkyPNG.Image.metadata_chunks
def metadata_chunks metadata.map do |key, value| if value.length >= METADATA_COMPRESSION_TRESHOLD ChunkyPNG::Chunk::CompressedText.new(key, value) else ChunkyPNG::Chunk::Text.new(key, value) end end end
ruby
def metadata_chunks metadata.map do |key, value| if value.length >= METADATA_COMPRESSION_TRESHOLD ChunkyPNG::Chunk::CompressedText.new(key, value) else ChunkyPNG::Chunk::Text.new(key, value) end end end
[ "def", "metadata_chunks", "metadata", ".", "map", "do", "|", "key", ",", "value", "|", "if", "value", ".", "length", ">=", "METADATA_COMPRESSION_TRESHOLD", "ChunkyPNG", "::", "Chunk", "::", "CompressedText", ".", "new", "(", "key", ",", "value", ")", "else", "ChunkyPNG", "::", "Chunk", "::", "Text", ".", "new", "(", "key", ",", "value", ")", "end", "end", "end" ]
Returns the metadata for this image as PNG chunks. Chunks will either be of the {ChunkyPNG::Chunk::Text} type for small values (in bytes), or of the {ChunkyPNG::Chunk::CompressedText} type for values that are larger in size. @return [Array<ChunkyPNG::Chunk>] An array of metadata chunks. @see ChunkyPNG::Image::METADATA_COMPRESSION_TRESHOLD
[ "Returns", "the", "metadata", "for", "this", "image", "as", "PNG", "chunks", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/image.rb#L41-L49
train
wvanbergen/chunky_png
lib/chunky_png/rmagick.rb
ChunkyPNG.RMagick.import
def import(image) pixels = image.export_pixels_to_str(0, 0, image.columns, image.rows, "RGBA") ChunkyPNG::Canvas.from_rgba_stream(image.columns, image.rows, pixels) end
ruby
def import(image) pixels = image.export_pixels_to_str(0, 0, image.columns, image.rows, "RGBA") ChunkyPNG::Canvas.from_rgba_stream(image.columns, image.rows, pixels) end
[ "def", "import", "(", "image", ")", "pixels", "=", "image", ".", "export_pixels_to_str", "(", "0", ",", "0", ",", "image", ".", "columns", ",", "image", ".", "rows", ",", "\"RGBA\"", ")", "ChunkyPNG", "::", "Canvas", ".", "from_rgba_stream", "(", "image", ".", "columns", ",", "image", ".", "rows", ",", "pixels", ")", "end" ]
Imports an RMagick image as Canvas object. @param [Magick::Image] image The image to import @return [ChunkyPNG::Canvas] The canvas, constructed from the RMagick image.
[ "Imports", "an", "RMagick", "image", "as", "Canvas", "object", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/rmagick.rb#L27-L30
train
wvanbergen/chunky_png
lib/chunky_png/rmagick.rb
ChunkyPNG.RMagick.export
def export(canvas) image = Magick::Image.new(canvas.width, canvas.height) image.import_pixels(0, 0, canvas.width, canvas.height, "RGBA", canvas.pixels.pack("N*")) image end
ruby
def export(canvas) image = Magick::Image.new(canvas.width, canvas.height) image.import_pixels(0, 0, canvas.width, canvas.height, "RGBA", canvas.pixels.pack("N*")) image end
[ "def", "export", "(", "canvas", ")", "image", "=", "Magick", "::", "Image", ".", "new", "(", "canvas", ".", "width", ",", "canvas", ".", "height", ")", "image", ".", "import_pixels", "(", "0", ",", "0", ",", "canvas", ".", "width", ",", "canvas", ".", "height", ",", "\"RGBA\"", ",", "canvas", ".", "pixels", ".", "pack", "(", "\"N*\"", ")", ")", "image", "end" ]
Exports a Canvas as RMagick image instance. @param [ChunkyPNG::Canvas] canvas The canvas to export. @return [Magick::Image] The RMagick image constructed from the Canvas instance.
[ "Exports", "a", "Canvas", "as", "RMagick", "image", "instance", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/rmagick.rb#L35-L39
train
wvanbergen/chunky_png
lib/chunky_png/vector.rb
ChunkyPNG.Vector.each_edge
def each_edge(close = true) raise ChunkyPNG::ExpectationFailed, "Not enough points in this path to draw an edge!" if length < 2 points.each_cons(2) { |a, b| yield(a, b) } yield(points.last, points.first) if close end
ruby
def each_edge(close = true) raise ChunkyPNG::ExpectationFailed, "Not enough points in this path to draw an edge!" if length < 2 points.each_cons(2) { |a, b| yield(a, b) } yield(points.last, points.first) if close end
[ "def", "each_edge", "(", "close", "=", "true", ")", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"Not enough points in this path to draw an edge!\"", "if", "length", "<", "2", "points", ".", "each_cons", "(", "2", ")", "{", "|", "a", ",", "b", "|", "yield", "(", "a", ",", "b", ")", "}", "yield", "(", "points", ".", "last", ",", "points", ".", "first", ")", "if", "close", "end" ]
Initializes a vector based on a list of Point instances. You usually do not want to use this method directly, but call {ChunkyPNG.Vector} instead. @param [Array<ChunkyPNG::Point>] points @see ChunkyPNG.Vector Iterates over all the edges in this vector. An edge is a combination of two subsequent points in the vector. Together, they will form a path from the first point to the last point @param [true, false] close Whether to close the path, i.e. return an edge that connects the last point in the vector back to the first point. @return [void] @raise [ChunkyPNG::ExpectationFailed] if the vector contains less than two points. @see #edges
[ "Initializes", "a", "vector", "based", "on", "a", "list", "of", "Point", "instances", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/vector.rb#L58-L62
train
wvanbergen/chunky_png
lib/chunky_png/datastream.rb
ChunkyPNG.Datastream.to_blob
def to_blob str = StringIO.new str.set_encoding("ASCII-8BIT") write(str) str.string end
ruby
def to_blob str = StringIO.new str.set_encoding("ASCII-8BIT") write(str) str.string end
[ "def", "to_blob", "str", "=", "StringIO", ".", "new", "str", ".", "set_encoding", "(", "\"ASCII-8BIT\"", ")", "write", "(", "str", ")", "str", ".", "string", "end" ]
Encodes this datastream into a string. @return [String] The encoded PNG datastream.
[ "Encodes", "this", "datastream", "into", "a", "string", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/datastream.rb#L180-L185
train
wvanbergen/chunky_png
lib/chunky_png/dimension.rb
ChunkyPNG.Dimension.include?
def include?(*point_like) point = ChunkyPNG::Point(*point_like) point.x >= 0 && point.x < width && point.y >= 0 && point.y < height end
ruby
def include?(*point_like) point = ChunkyPNG::Point(*point_like) point.x >= 0 && point.x < width && point.y >= 0 && point.y < height end
[ "def", "include?", "(", "*", "point_like", ")", "point", "=", "ChunkyPNG", "::", "Point", "(", "point_like", ")", "point", ".", "x", ">=", "0", "&&", "point", ".", "x", "<", "width", "&&", "point", ".", "y", ">=", "0", "&&", "point", ".", "y", "<", "height", "end" ]
Checks whether a point is within bounds of this dimension. @param [ChunkyPNG::Point, ...] point_like A point-like to bounds-check. @return [true, false] True iff the x and y coordinate fall in this dimension. @see ChunkyPNG.Point
[ "Checks", "whether", "a", "point", "is", "within", "bounds", "of", "this", "dimension", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/dimension.rb#L94-L97
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.parse
def parse(source) return source if source.is_a?(Integer) case source.to_s when /^\d+$/ then source.to_s.to_i when HEX3_COLOR_REGEXP, HEX6_COLOR_REGEXP then from_hex(source.to_s) when HTML_COLOR_REGEXP then html_color(source.to_s) else raise ArgumentError, "Don't know how to create a color from #{source.inspect}!" end end
ruby
def parse(source) return source if source.is_a?(Integer) case source.to_s when /^\d+$/ then source.to_s.to_i when HEX3_COLOR_REGEXP, HEX6_COLOR_REGEXP then from_hex(source.to_s) when HTML_COLOR_REGEXP then html_color(source.to_s) else raise ArgumentError, "Don't know how to create a color from #{source.inspect}!" end end
[ "def", "parse", "(", "source", ")", "return", "source", "if", "source", ".", "is_a?", "(", "Integer", ")", "case", "source", ".", "to_s", "when", "/", "\\d", "/", "then", "source", ".", "to_s", ".", "to_i", "when", "HEX3_COLOR_REGEXP", ",", "HEX6_COLOR_REGEXP", "then", "from_hex", "(", "source", ".", "to_s", ")", "when", "HTML_COLOR_REGEXP", "then", "html_color", "(", "source", ".", "to_s", ")", "else", "raise", "ArgumentError", ",", "\"Don't know how to create a color from #{source.inspect}!\"", "end", "end" ]
CONSTRUCTING COLOR VALUES Parses a color value given a numeric or string argument. It supports color numbers, colors in hex notation and named HTML colors. @param [Integer, String] source The color value. @return [Integer] The color value, with the opacity applied if one was given.
[ "CONSTRUCTING", "COLOR", "VALUES" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L84-L92
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hex
def from_hex(hex_value, opacity = nil) base_color = case hex_value when HEX3_COLOR_REGEXP $1.gsub(/([0-9a-f])/i, '\1\1').hex << 8 when HEX6_COLOR_REGEXP $1.hex << 8 else raise ArgumentError, "Not a valid hex color notation: #{hex_value.inspect}!" end opacity ||= $2 ? $2.hex : 0xff base_color | opacity end
ruby
def from_hex(hex_value, opacity = nil) base_color = case hex_value when HEX3_COLOR_REGEXP $1.gsub(/([0-9a-f])/i, '\1\1').hex << 8 when HEX6_COLOR_REGEXP $1.hex << 8 else raise ArgumentError, "Not a valid hex color notation: #{hex_value.inspect}!" end opacity ||= $2 ? $2.hex : 0xff base_color | opacity end
[ "def", "from_hex", "(", "hex_value", ",", "opacity", "=", "nil", ")", "base_color", "=", "case", "hex_value", "when", "HEX3_COLOR_REGEXP", "$1", ".", "gsub", "(", "/", "/i", ",", "'\\1\\1'", ")", ".", "hex", "<<", "8", "when", "HEX6_COLOR_REGEXP", "$1", ".", "hex", "<<", "8", "else", "raise", "ArgumentError", ",", "\"Not a valid hex color notation: #{hex_value.inspect}!\"", "end", "opacity", "||=", "$2", "?", "$2", ".", "hex", ":", "0xff", "base_color", "|", "opacity", "end" ]
Creates a color by converting it from a string in hex notation. It supports colors with (#rrggbbaa) or without (#rrggbb) alpha channel as well as the 3-digit short format (#rgb) for those without. Color strings may include the prefix "0x" or "#". @param [String] hex_value The color in hex notation. @param [Integer] opacity The opacity value for the color. Overrides any opacity value given in the hex value if given. @return [Integer] The color value. @raise [ArgumentError] if the value given is not a hex color notation.
[ "Creates", "a", "color", "by", "converting", "it", "from", "a", "string", "in", "hex", "notation", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L165-L176
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hsv
def from_hsv(hue, saturation, value, alpha = 255) raise ArgumentError, "Hue must be between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation must be between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Value/brightness must be between 0 and 1" unless (0..1).cover?(value) chroma = value * saturation rgb = cylindrical_to_cubic(hue, saturation, value, chroma) rgb.map! { |component| ((component + value - chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
ruby
def from_hsv(hue, saturation, value, alpha = 255) raise ArgumentError, "Hue must be between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation must be between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Value/brightness must be between 0 and 1" unless (0..1).cover?(value) chroma = value * saturation rgb = cylindrical_to_cubic(hue, saturation, value, chroma) rgb.map! { |component| ((component + value - chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
[ "def", "from_hsv", "(", "hue", ",", "saturation", ",", "value", ",", "alpha", "=", "255", ")", "raise", "ArgumentError", ",", "\"Hue must be between 0 and 360\"", "unless", "(", "0", "..", "360", ")", ".", "cover?", "(", "hue", ")", "raise", "ArgumentError", ",", "\"Saturation must be between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "saturation", ")", "raise", "ArgumentError", ",", "\"Value/brightness must be between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "value", ")", "chroma", "=", "value", "*", "saturation", "rgb", "=", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "value", ",", "chroma", ")", "rgb", ".", "map!", "{", "|", "component", "|", "(", "(", "component", "+", "value", "-", "chroma", ")", "*", "255", ")", ".", "to_i", "}", "rgb", "<<", "alpha", "rgba", "(", "rgb", ")", "end" ]
Creates a new color from an HSV triple. Create a new color using an HSV (sometimes also called HSB) triple. The words `value` and `brightness` are used interchangeably and synonymously in descriptions of this colorspace. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] value The value (brightness) component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsv triple is invalid. @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Creates", "a", "new", "color", "from", "an", "HSV", "triple", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L192-L202
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.from_hsl
def from_hsl(hue, saturation, lightness, alpha = 255) raise ArgumentError, "Hue #{hue} was not between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation #{saturation} was not between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Lightness #{lightness} was not between 0 and 1" unless (0..1).cover?(lightness) chroma = (1 - (2 * lightness - 1).abs) * saturation rgb = cylindrical_to_cubic(hue, saturation, lightness, chroma) rgb.map! { |component| ((component + lightness - 0.5 * chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
ruby
def from_hsl(hue, saturation, lightness, alpha = 255) raise ArgumentError, "Hue #{hue} was not between 0 and 360" unless (0..360).cover?(hue) raise ArgumentError, "Saturation #{saturation} was not between 0 and 1" unless (0..1).cover?(saturation) raise ArgumentError, "Lightness #{lightness} was not between 0 and 1" unless (0..1).cover?(lightness) chroma = (1 - (2 * lightness - 1).abs) * saturation rgb = cylindrical_to_cubic(hue, saturation, lightness, chroma) rgb.map! { |component| ((component + lightness - 0.5 * chroma) * 255).to_i } rgb << alpha rgba(*rgb) end
[ "def", "from_hsl", "(", "hue", ",", "saturation", ",", "lightness", ",", "alpha", "=", "255", ")", "raise", "ArgumentError", ",", "\"Hue #{hue} was not between 0 and 360\"", "unless", "(", "0", "..", "360", ")", ".", "cover?", "(", "hue", ")", "raise", "ArgumentError", ",", "\"Saturation #{saturation} was not between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "saturation", ")", "raise", "ArgumentError", ",", "\"Lightness #{lightness} was not between 0 and 1\"", "unless", "(", "0", "..", "1", ")", ".", "cover?", "(", "lightness", ")", "chroma", "=", "(", "1", "-", "(", "2", "*", "lightness", "-", "1", ")", ".", "abs", ")", "*", "saturation", "rgb", "=", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "lightness", ",", "chroma", ")", "rgb", ".", "map!", "{", "|", "component", "|", "(", "(", "component", "+", "lightness", "-", "0.5", "*", "chroma", ")", "*", "255", ")", ".", "to_i", "}", "rgb", "<<", "alpha", "rgba", "(", "rgb", ")", "end" ]
Creates a new color from an HSL triple. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] lightness The lightness component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsl triple is invalid. @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Creates", "a", "new", "color", "from", "an", "HSL", "triple", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L218-L228
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.cylindrical_to_cubic
def cylindrical_to_cubic(hue, saturation, y_component, chroma) hue_prime = hue.fdiv(60) x = chroma * (1 - (hue_prime % 2 - 1).abs) case hue_prime when (0...1) then [chroma, x, 0] when (1...2) then [x, chroma, 0] when (2...3) then [0, chroma, x] when (3...4) then [0, x, chroma] when (4...5) then [x, 0, chroma] when (5..6) then [chroma, 0, x] end end
ruby
def cylindrical_to_cubic(hue, saturation, y_component, chroma) hue_prime = hue.fdiv(60) x = chroma * (1 - (hue_prime % 2 - 1).abs) case hue_prime when (0...1) then [chroma, x, 0] when (1...2) then [x, chroma, 0] when (2...3) then [0, chroma, x] when (3...4) then [0, x, chroma] when (4...5) then [x, 0, chroma] when (5..6) then [chroma, 0, x] end end
[ "def", "cylindrical_to_cubic", "(", "hue", ",", "saturation", ",", "y_component", ",", "chroma", ")", "hue_prime", "=", "hue", ".", "fdiv", "(", "60", ")", "x", "=", "chroma", "*", "(", "1", "-", "(", "hue_prime", "%", "2", "-", "1", ")", ".", "abs", ")", "case", "hue_prime", "when", "(", "0", "...", "1", ")", "then", "[", "chroma", ",", "x", ",", "0", "]", "when", "(", "1", "...", "2", ")", "then", "[", "x", ",", "chroma", ",", "0", "]", "when", "(", "2", "...", "3", ")", "then", "[", "0", ",", "chroma", ",", "x", "]", "when", "(", "3", "...", "4", ")", "then", "[", "0", ",", "x", ",", "chroma", "]", "when", "(", "4", "...", "5", ")", "then", "[", "x", ",", "0", ",", "chroma", "]", "when", "(", "5", "..", "6", ")", "then", "[", "chroma", ",", "0", ",", "x", "]", "end", "end" ]
Convert one HSL or HSV triple and associated chroma to a scaled rgb triple This method encapsulates the shared mathematical operations needed to convert coordinates from a cylindrical colorspace such as HSL or HSV into coordinates of the RGB colorspace. Even though chroma values are derived from the other three coordinates, the formula for calculating chroma differs for each colorspace. Since it is calculated differently for each colorspace, it must be passed in as a parameter. @param [Fixnum] hue The hue-component (0-360) @param [Fixnum] saturation The saturation-component (0-1) @param [Fixnum] y_component The y_component can represent either lightness or brightness/value (0-1) depending on which scheme (HSV/HSL) is being used. @param [Fixnum] chroma The associated chroma value. @return [Array<Fixnum>] A scaled r,g,b triple. Scheme-dependent adjustments are still needed to reach the true r,g,b values. @see http://en.wikipedia.org/wiki/HSL_and_HSV @see http://www.tomjewett.com/colors/hsb.html @private
[ "Convert", "one", "HSL", "or", "HSV", "triple", "and", "associated", "chroma", "to", "a", "scaled", "rgb", "triple" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L251-L263
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.grayscale?
def grayscale?(value) r(value) == b(value) && b(value) == g(value) end
ruby
def grayscale?(value) r(value) == b(value) && b(value) == g(value) end
[ "def", "grayscale?", "(", "value", ")", "r", "(", "value", ")", "==", "b", "(", "value", ")", "&&", "b", "(", "value", ")", "==", "g", "(", "value", ")", "end" ]
Returns true if this color is fully transparent. @param [Integer] value The color to test. @return [true, false] True if the r, g and b component are equal.
[ "Returns", "true", "if", "this", "color", "is", "fully", "transparent", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L321-L323
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.compose_quick
def compose_quick(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) a_com = int8_mult(0xff - a(fg), a(bg)) new_r = int8_mult(a(fg), r(fg)) + int8_mult(a_com, r(bg)) new_g = int8_mult(a(fg), g(fg)) + int8_mult(a_com, g(bg)) new_b = int8_mult(a(fg), b(fg)) + int8_mult(a_com, b(bg)) new_a = a(fg) + a_com rgba(new_r, new_g, new_b, new_a) end
ruby
def compose_quick(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) a_com = int8_mult(0xff - a(fg), a(bg)) new_r = int8_mult(a(fg), r(fg)) + int8_mult(a_com, r(bg)) new_g = int8_mult(a(fg), g(fg)) + int8_mult(a_com, g(bg)) new_b = int8_mult(a(fg), b(fg)) + int8_mult(a_com, b(bg)) new_a = a(fg) + a_com rgba(new_r, new_g, new_b, new_a) end
[ "def", "compose_quick", "(", "fg", ",", "bg", ")", "return", "fg", "if", "opaque?", "(", "fg", ")", "||", "fully_transparent?", "(", "bg", ")", "return", "bg", "if", "fully_transparent?", "(", "fg", ")", "a_com", "=", "int8_mult", "(", "0xff", "-", "a", "(", "fg", ")", ",", "a", "(", "bg", ")", ")", "new_r", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "r", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "r", "(", "bg", ")", ")", "new_g", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "g", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "g", "(", "bg", ")", ")", "new_b", "=", "int8_mult", "(", "a", "(", "fg", ")", ",", "b", "(", "fg", ")", ")", "+", "int8_mult", "(", "a_com", ",", "b", "(", "bg", ")", ")", "new_a", "=", "a", "(", "fg", ")", "+", "a_com", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Composes two colors with an alpha channel using integer math. This version is faster than the version based on floating point math, so this compositing function is used by default. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_precise
[ "Composes", "two", "colors", "with", "an", "alpha", "channel", "using", "integer", "math", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L360-L370
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.compose_precise
def compose_precise(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) fg_a = a(fg).to_f / MAX bg_a = a(bg).to_f / MAX a_com = (1.0 - fg_a) * bg_a new_r = (fg_a * r(fg) + a_com * r(bg)).round new_g = (fg_a * g(fg) + a_com * g(bg)).round new_b = (fg_a * b(fg) + a_com * b(bg)).round new_a = ((fg_a + a_com) * MAX).round rgba(new_r, new_g, new_b, new_a) end
ruby
def compose_precise(fg, bg) return fg if opaque?(fg) || fully_transparent?(bg) return bg if fully_transparent?(fg) fg_a = a(fg).to_f / MAX bg_a = a(bg).to_f / MAX a_com = (1.0 - fg_a) * bg_a new_r = (fg_a * r(fg) + a_com * r(bg)).round new_g = (fg_a * g(fg) + a_com * g(bg)).round new_b = (fg_a * b(fg) + a_com * b(bg)).round new_a = ((fg_a + a_com) * MAX).round rgba(new_r, new_g, new_b, new_a) end
[ "def", "compose_precise", "(", "fg", ",", "bg", ")", "return", "fg", "if", "opaque?", "(", "fg", ")", "||", "fully_transparent?", "(", "bg", ")", "return", "bg", "if", "fully_transparent?", "(", "fg", ")", "fg_a", "=", "a", "(", "fg", ")", ".", "to_f", "/", "MAX", "bg_a", "=", "a", "(", "bg", ")", ".", "to_f", "/", "MAX", "a_com", "=", "(", "1.0", "-", "fg_a", ")", "*", "bg_a", "new_r", "=", "(", "fg_a", "*", "r", "(", "fg", ")", "+", "a_com", "*", "r", "(", "bg", ")", ")", ".", "round", "new_g", "=", "(", "fg_a", "*", "g", "(", "fg", ")", "+", "a_com", "*", "g", "(", "bg", ")", ")", ".", "round", "new_b", "=", "(", "fg_a", "*", "b", "(", "fg", ")", "+", "a_com", "*", "b", "(", "bg", ")", ")", ".", "round", "new_a", "=", "(", "(", "fg_a", "+", "a_com", ")", "*", "MAX", ")", ".", "round", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Composes two colors with an alpha channel using floating point math. This method uses more precise floating point math, but this precision is lost when the result is converted back to an integer. Because it is slower than the version based on integer math, that version is preferred. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_quick
[ "Composes", "two", "colors", "with", "an", "alpha", "channel", "using", "floating", "point", "math", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L382-L395
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.interpolate_quick
def interpolate_quick(fg, bg, alpha) return fg if alpha >= 255 return bg if alpha <= 0 alpha_com = 255 - alpha new_r = int8_mult(alpha, r(fg)) + int8_mult(alpha_com, r(bg)) new_g = int8_mult(alpha, g(fg)) + int8_mult(alpha_com, g(bg)) new_b = int8_mult(alpha, b(fg)) + int8_mult(alpha_com, b(bg)) new_a = int8_mult(alpha, a(fg)) + int8_mult(alpha_com, a(bg)) rgba(new_r, new_g, new_b, new_a) end
ruby
def interpolate_quick(fg, bg, alpha) return fg if alpha >= 255 return bg if alpha <= 0 alpha_com = 255 - alpha new_r = int8_mult(alpha, r(fg)) + int8_mult(alpha_com, r(bg)) new_g = int8_mult(alpha, g(fg)) + int8_mult(alpha_com, g(bg)) new_b = int8_mult(alpha, b(fg)) + int8_mult(alpha_com, b(bg)) new_a = int8_mult(alpha, a(fg)) + int8_mult(alpha_com, a(bg)) rgba(new_r, new_g, new_b, new_a) end
[ "def", "interpolate_quick", "(", "fg", ",", "bg", ",", "alpha", ")", "return", "fg", "if", "alpha", ">=", "255", "return", "bg", "if", "alpha", "<=", "0", "alpha_com", "=", "255", "-", "alpha", "new_r", "=", "int8_mult", "(", "alpha", ",", "r", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "r", "(", "bg", ")", ")", "new_g", "=", "int8_mult", "(", "alpha", ",", "g", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "g", "(", "bg", ")", ")", "new_b", "=", "int8_mult", "(", "alpha", ",", "b", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "b", "(", "bg", ")", ")", "new_a", "=", "int8_mult", "(", "alpha", ",", "a", "(", "fg", ")", ")", "+", "int8_mult", "(", "alpha_com", ",", "a", "(", "bg", ")", ")", "rgba", "(", "new_r", ",", "new_g", ",", "new_b", ",", "new_a", ")", "end" ]
Interpolates the foreground and background colors by the given alpha value. This also blends the alpha channels themselves. A blending factor of 255 will give entirely the foreground, while a blending factor of 0 will give the background. @param [Integer] fg The foreground color. @param [Integer] bg The background color. @param [Integer] alpha The blending factor (fixed 8bit) @return [Integer] The interpolated color.
[ "Interpolates", "the", "foreground", "and", "background", "colors", "by", "the", "given", "alpha", "value", ".", "This", "also", "blends", "the", "alpha", "channels", "themselves", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L419-L431
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.fade
def fade(color, factor) new_alpha = int8_mult(a(color), factor) (color & 0xffffff00) | new_alpha end
ruby
def fade(color, factor) new_alpha = int8_mult(a(color), factor) (color & 0xffffff00) | new_alpha end
[ "def", "fade", "(", "color", ",", "factor", ")", "new_alpha", "=", "int8_mult", "(", "a", "(", "color", ")", ",", "factor", ")", "(", "color", "&", "0xffffff00", ")", "|", "new_alpha", "end" ]
Lowers the intensity of a color, by lowering its alpha by a given factor. @param [Integer] color The color to adjust. @param [Integer] factor Fade factor as an integer between 0 and 255. @return [Integer] The faded color.
[ "Lowers", "the", "intensity", "of", "a", "color", "by", "lowering", "its", "alpha", "by", "a", "given", "factor", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L460-L463
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_color
def decompose_color(color, mask, bg, tolerance = 1) if alpha_decomposable?(color, mask, bg, tolerance) mask & 0xffffff00 | decompose_alpha(color, mask, bg) else mask & 0xffffff00 end end
ruby
def decompose_color(color, mask, bg, tolerance = 1) if alpha_decomposable?(color, mask, bg, tolerance) mask & 0xffffff00 | decompose_alpha(color, mask, bg) else mask & 0xffffff00 end end
[ "def", "decompose_color", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", "=", "1", ")", "if", "alpha_decomposable?", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", ")", "mask", "&", "0xffffff00", "|", "decompose_alpha", "(", "color", ",", "mask", ",", "bg", ")", "else", "mask", "&", "0xffffff00", "end", "end" ]
Decomposes a color, given a color, a mask color and a background color. The returned color will be a variant of the mask color, with the alpha channel set to the best fitting value. This basically is the reverse operation if alpha composition. If the color cannot be decomposed, this method will return the fully transparent variant of the mask color. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value between 0 and 255. @return [Integer] The decomposed color, a variant of the masked color with the alpha channel set to an appropriate value.
[ "Decomposes", "a", "color", "given", "a", "color", "a", "mask", "color", "and", "a", "background", "color", ".", "The", "returned", "color", "will", "be", "a", "variant", "of", "the", "mask", "color", "with", "the", "alpha", "channel", "set", "to", "the", "best", "fitting", "value", ".", "This", "basically", "is", "the", "reverse", "operation", "if", "alpha", "composition", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L481-L487
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.alpha_decomposable?
def alpha_decomposable?(color, mask, bg, tolerance = 1) components = decompose_alpha_components(color, mask, bg) sum = components.inject(0) { |a, b| a + b } max = components.max * 3 components.max <= 255 && components.min >= 0 && (sum + tolerance * 3) >= max end
ruby
def alpha_decomposable?(color, mask, bg, tolerance = 1) components = decompose_alpha_components(color, mask, bg) sum = components.inject(0) { |a, b| a + b } max = components.max * 3 components.max <= 255 && components.min >= 0 && (sum + tolerance * 3) >= max end
[ "def", "alpha_decomposable?", "(", "color", ",", "mask", ",", "bg", ",", "tolerance", "=", "1", ")", "components", "=", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "sum", "=", "components", ".", "inject", "(", "0", ")", "{", "|", "a", ",", "b", "|", "a", "+", "b", "}", "max", "=", "components", ".", "max", "*", "3", "components", ".", "max", "<=", "255", "&&", "components", ".", "min", ">=", "0", "&&", "(", "sum", "+", "tolerance", "*", "3", ")", ">=", "max", "end" ]
Checks whether an alpha channel value can successfully be composed given the resulting color, the mask color and a background color, all of which should be opaque. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value between 0 and 255. @return [Boolean] True if the alpha component can be decomposed successfully. @see #decompose_alpha
[ "Checks", "whether", "an", "alpha", "channel", "value", "can", "successfully", "be", "composed", "given", "the", "resulting", "color", "the", "mask", "color", "and", "a", "background", "color", "all", "of", "which", "should", "be", "opaque", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L502-L507
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha
def decompose_alpha(color, mask, bg) components = decompose_alpha_components(color, mask, bg) (components.inject(0) { |a, b| a + b } / 3.0).round end
ruby
def decompose_alpha(color, mask, bg) components = decompose_alpha_components(color, mask, bg) (components.inject(0) { |a, b| a + b } / 3.0).round end
[ "def", "decompose_alpha", "(", "color", ",", "mask", ",", "bg", ")", "components", "=", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "(", "components", ".", "inject", "(", "0", ")", "{", "|", "a", ",", "b", "|", "a", "+", "b", "}", "/", "3.0", ")", ".", "round", "end" ]
Decomposes the alpha channel value given the resulting color, the mask color and a background color, all of which should be opaque. Make sure to call {#alpha_decomposable?} first to see if the alpha channel value can successfully decomposed with a given tolerance, otherwise the return value of this method is undefined. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Integer] The best fitting alpha channel, a value between 0 and 255. @see #alpha_decomposable?
[ "Decomposes", "the", "alpha", "channel", "value", "given", "the", "resulting", "color", "the", "mask", "color", "and", "a", "background", "color", "all", "of", "which", "should", "be", "opaque", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L523-L526
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha_component
def decompose_alpha_component(channel, color, mask, bg) cc, mc, bc = send(channel, color), send(channel, mask), send(channel, bg) return 0x00 if bc == cc return 0xff if bc == mc return 0xff if cc == mc (((bc - cc).to_f / (bc - mc).to_f) * MAX).round end
ruby
def decompose_alpha_component(channel, color, mask, bg) cc, mc, bc = send(channel, color), send(channel, mask), send(channel, bg) return 0x00 if bc == cc return 0xff if bc == mc return 0xff if cc == mc (((bc - cc).to_f / (bc - mc).to_f) * MAX).round end
[ "def", "decompose_alpha_component", "(", "channel", ",", "color", ",", "mask", ",", "bg", ")", "cc", ",", "mc", ",", "bc", "=", "send", "(", "channel", ",", "color", ")", ",", "send", "(", "channel", ",", "mask", ")", ",", "send", "(", "channel", ",", "bg", ")", "return", "0x00", "if", "bc", "==", "cc", "return", "0xff", "if", "bc", "==", "mc", "return", "0xff", "if", "cc", "==", "mc", "(", "(", "(", "bc", "-", "cc", ")", ".", "to_f", "/", "(", "bc", "-", "mc", ")", ".", "to_f", ")", "*", "MAX", ")", ".", "round", "end" ]
Decomposes an alpha channel for either the r, g or b color channel. @param [:r, :g, :b] channel The channel to decompose the alpha channel from. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Integer] The decomposed alpha value for the channel.
[ "Decomposes", "an", "alpha", "channel", "for", "either", "the", "r", "g", "or", "b", "color", "channel", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L536-L544
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.decompose_alpha_components
def decompose_alpha_components(color, mask, bg) [ decompose_alpha_component(:r, color, mask, bg), decompose_alpha_component(:g, color, mask, bg), decompose_alpha_component(:b, color, mask, bg), ] end
ruby
def decompose_alpha_components(color, mask, bg) [ decompose_alpha_component(:r, color, mask, bg), decompose_alpha_component(:g, color, mask, bg), decompose_alpha_component(:b, color, mask, bg), ] end
[ "def", "decompose_alpha_components", "(", "color", ",", "mask", ",", "bg", ")", "[", "decompose_alpha_component", "(", ":r", ",", "color", ",", "mask", ",", "bg", ")", ",", "decompose_alpha_component", "(", ":g", ",", "color", ",", "mask", ",", "bg", ")", ",", "decompose_alpha_component", "(", ":b", ",", "color", ",", "mask", ",", "bg", ")", ",", "]", "end" ]
Decomposes the alpha channels for the r, g and b color channel. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being composed @param [Integer] bg The background color on which the color was composed. @return [Array<Integer>] The decomposed alpha values for the r, g and b channels.
[ "Decomposes", "the", "alpha", "channels", "for", "the", "r", "g", "and", "b", "color", "channel", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L553-L559
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_hsv
def to_hsv(color, include_alpha = false) hue, chroma, max, _ = hue_and_chroma(color) value = max saturation = chroma.zero? ? 0.0 : chroma.fdiv(value) include_alpha ? [hue, saturation, value, a(color)] : [hue, saturation, value] end
ruby
def to_hsv(color, include_alpha = false) hue, chroma, max, _ = hue_and_chroma(color) value = max saturation = chroma.zero? ? 0.0 : chroma.fdiv(value) include_alpha ? [hue, saturation, value, a(color)] : [hue, saturation, value] end
[ "def", "to_hsv", "(", "color", ",", "include_alpha", "=", "false", ")", "hue", ",", "chroma", ",", "max", ",", "_", "=", "hue_and_chroma", "(", "color", ")", "value", "=", "max", "saturation", "=", "chroma", ".", "zero?", "?", "0.0", ":", "chroma", ".", "fdiv", "(", "value", ")", "include_alpha", "?", "[", "hue", ",", "saturation", ",", "value", ",", "a", "(", "color", ")", "]", ":", "[", "hue", ",", "saturation", ",", "value", "]", "end" ]
Returns an array with the separate HSV components of a color. Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSV colors whose coordinates are float-based. Because of this rounding, #to_hsv and #from_hsv may not be perfect inverses. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element representing alpha channel should be included in the returned array. @return [Array[0]] The hue of the color (0-360) @return [Array[1]] The saturation of the color (0-1) @return [Array[2]] The value of the color (0-1) @return [Array[3]] Optional fourth element for alpha, included if include_alpha=true (0-255) @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Returns", "an", "array", "with", "the", "separate", "HSV", "components", "of", "a", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L594-L601
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_hsl
def to_hsl(color, include_alpha = false) hue, chroma, max, min = hue_and_chroma(color) lightness = 0.5 * (max + min) saturation = chroma.zero? ? 0.0 : chroma.fdiv(1 - (2 * lightness - 1).abs) include_alpha ? [hue, saturation, lightness, a(color)] : [hue, saturation, lightness] end
ruby
def to_hsl(color, include_alpha = false) hue, chroma, max, min = hue_and_chroma(color) lightness = 0.5 * (max + min) saturation = chroma.zero? ? 0.0 : chroma.fdiv(1 - (2 * lightness - 1).abs) include_alpha ? [hue, saturation, lightness, a(color)] : [hue, saturation, lightness] end
[ "def", "to_hsl", "(", "color", ",", "include_alpha", "=", "false", ")", "hue", ",", "chroma", ",", "max", ",", "min", "=", "hue_and_chroma", "(", "color", ")", "lightness", "=", "0.5", "*", "(", "max", "+", "min", ")", "saturation", "=", "chroma", ".", "zero?", "?", "0.0", ":", "chroma", ".", "fdiv", "(", "1", "-", "(", "2", "*", "lightness", "-", "1", ")", ".", "abs", ")", "include_alpha", "?", "[", "hue", ",", "saturation", ",", "lightness", ",", "a", "(", "color", ")", "]", ":", "[", "hue", ",", "saturation", ",", "lightness", "]", "end" ]
Returns an array with the separate HSL components of a color. Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSL colors whose coordinates are float-based. Because of this rounding, #to_hsl and #from_hsl may not be perfect inverses. This implementation follows the modern convention of 0 degrees hue indicating red. @param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element representing alpha channel should be included in the returned array. @return [Array<Fixnum>[0]] The hue of the color (0-360) @return [Array<Fixnum>[1]] The saturation of the color (0-1) @return [Array<Fixnum>[2]] The lightness of the color (0-1) @return [Array<Fixnum>[3]] Optional fourth element for alpha, included if include_alpha=true (0-255) @see http://en.wikipedia.org/wiki/HSL_and_HSV
[ "Returns", "an", "array", "with", "the", "separate", "HSL", "components", "of", "a", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L623-L630
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.to_truecolor_alpha_bytes
def to_truecolor_alpha_bytes(color) [r(color), g(color), b(color), a(color)] end
ruby
def to_truecolor_alpha_bytes(color) [r(color), g(color), b(color), a(color)] end
[ "def", "to_truecolor_alpha_bytes", "(", "color", ")", "[", "r", "(", "color", ")", ",", "g", "(", "color", ")", ",", "b", "(", "color", ")", ",", "a", "(", "color", ")", "]", "end" ]
Returns an array with the separate RGBA values for this color. @param [Integer] color The color to convert. @return [Array<Integer>] An array with 4 Integer elements.
[ "Returns", "an", "array", "with", "the", "separate", "RGBA", "values", "for", "this", "color", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L666-L668
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.html_color
def html_color(color_name, opacity = nil) if color_name.to_s =~ HTML_COLOR_REGEXP opacity ||= $2 ? ($2.to_f * 255.0).round : 0xff base_color_name = $1.gsub(/[^a-z]+/i, "").downcase.to_sym return PREDEFINED_COLORS[base_color_name] | opacity if PREDEFINED_COLORS.key?(base_color_name) end raise ArgumentError, "Unknown color name #{color_name}!" end
ruby
def html_color(color_name, opacity = nil) if color_name.to_s =~ HTML_COLOR_REGEXP opacity ||= $2 ? ($2.to_f * 255.0).round : 0xff base_color_name = $1.gsub(/[^a-z]+/i, "").downcase.to_sym return PREDEFINED_COLORS[base_color_name] | opacity if PREDEFINED_COLORS.key?(base_color_name) end raise ArgumentError, "Unknown color name #{color_name}!" end
[ "def", "html_color", "(", "color_name", ",", "opacity", "=", "nil", ")", "if", "color_name", ".", "to_s", "=~", "HTML_COLOR_REGEXP", "opacity", "||=", "$2", "?", "(", "$2", ".", "to_f", "*", "255.0", ")", ".", "round", ":", "0xff", "base_color_name", "=", "$1", ".", "gsub", "(", "/", "/i", ",", "\"\"", ")", ".", "downcase", ".", "to_sym", "return", "PREDEFINED_COLORS", "[", "base_color_name", "]", "|", "opacity", "if", "PREDEFINED_COLORS", ".", "key?", "(", "base_color_name", ")", "end", "raise", "ArgumentError", ",", "\"Unknown color name #{color_name}!\"", "end" ]
Gets a color value based on a HTML color name. The color name is flexible. E.g. <tt>'yellowgreen'</tt>, <tt>'Yellow green'</tt>, <tt>'YellowGreen'</tt>, <tt>'YELLOW_GREEN'</tt> and <tt>:yellow_green</tt> will all return the same color value. You can include a opacity level in the color name (e.g. <tt>'red @ 0.5'</tt>) or give an explicit opacity value as second argument. If no opacity value is given, the color will be fully opaque. @param [Symbol, String] color_name The color name. It may include an opacity specifier like <tt>@ 0.8</tt> to set the color's opacity. @param [Integer] opacity The opacity value for the color between 0 and 255. Overrides any opacity value given in the color name. @return [Integer] The color value. @raise [ChunkyPNG::Exception] If the color name was not recognized.
[ "Gets", "a", "color", "value", "based", "on", "a", "HTML", "color", "name", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L908-L915
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.samples_per_pixel
def samples_per_pixel(color_mode) case color_mode when ChunkyPNG::COLOR_INDEXED then 1 when ChunkyPNG::COLOR_TRUECOLOR then 3 when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then 4 when ChunkyPNG::COLOR_GRAYSCALE then 1 when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then 2 else raise ChunkyPNG::NotSupported, "Don't know the number of samples for this colormode: #{color_mode}!" end end
ruby
def samples_per_pixel(color_mode) case color_mode when ChunkyPNG::COLOR_INDEXED then 1 when ChunkyPNG::COLOR_TRUECOLOR then 3 when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then 4 when ChunkyPNG::COLOR_GRAYSCALE then 1 when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then 2 else raise ChunkyPNG::NotSupported, "Don't know the number of samples for this colormode: #{color_mode}!" end end
[ "def", "samples_per_pixel", "(", "color_mode", ")", "case", "color_mode", "when", "ChunkyPNG", "::", "COLOR_INDEXED", "then", "1", "when", "ChunkyPNG", "::", "COLOR_TRUECOLOR", "then", "3", "when", "ChunkyPNG", "::", "COLOR_TRUECOLOR_ALPHA", "then", "4", "when", "ChunkyPNG", "::", "COLOR_GRAYSCALE", "then", "1", "when", "ChunkyPNG", "::", "COLOR_GRAYSCALE_ALPHA", "then", "2", "else", "raise", "ChunkyPNG", "::", "NotSupported", ",", "\"Don't know the number of samples for this colormode: #{color_mode}!\"", "end", "end" ]
STATIC UTILITY METHODS Returns the number of sample values per pixel. @param [Integer] color_mode The color mode being used. @return [Integer] The number of sample values per pixel.
[ "STATIC", "UTILITY", "METHODS" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L933-L942
train
wvanbergen/chunky_png
lib/chunky_png/color.rb
ChunkyPNG.Color.pass_bytesize
def pass_bytesize(color_mode, depth, width, height) return 0 if width == 0 || height == 0 (scanline_bytesize(color_mode, depth, width) + 1) * height end
ruby
def pass_bytesize(color_mode, depth, width, height) return 0 if width == 0 || height == 0 (scanline_bytesize(color_mode, depth, width) + 1) * height end
[ "def", "pass_bytesize", "(", "color_mode", ",", "depth", ",", "width", ",", "height", ")", "return", "0", "if", "width", "==", "0", "||", "height", "==", "0", "(", "scanline_bytesize", "(", "color_mode", ",", "depth", ",", "width", ")", "+", "1", ")", "*", "height", "end" ]
Returns the number of bytes used for an image pass @param [Integer] color_mode The color mode in which the pixels are stored. @param [Integer] depth The color depth of the pixels. @param [Integer] width The width of the image pass. @param [Integer] height The height of the image pass. @return [Integer] The number of bytes used per scanline in a datastream.
[ "Returns", "the", "number", "of", "bytes", "used", "for", "an", "image", "pass" ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/color.rb#L983-L986
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.[]=
def []=(x, y, color) assert_xy!(x, y) @pixels[y * width + x] = ChunkyPNG::Color.parse(color) end
ruby
def []=(x, y, color) assert_xy!(x, y) @pixels[y * width + x] = ChunkyPNG::Color.parse(color) end
[ "def", "[]=", "(", "x", ",", "y", ",", "color", ")", "assert_xy!", "(", "x", ",", "y", ")", "@pixels", "[", "y", "*", "width", "+", "x", "]", "=", "ChunkyPNG", "::", "Color", ".", "parse", "(", "color", ")", "end" ]
Replaces a single pixel in this canvas. @param [Integer] x The x-coordinate of the pixel (column) @param [Integer] y The y-coordinate of the pixel (row) @param [Integer] color The new color for the provided coordinates. @return [Integer] The new color value for this pixel, i.e. <tt>color</tt>. @raise [ChunkyPNG::OutOfBounds] when the coordinates are outside of the image's dimensions. @see #set_pixel
[ "Replaces", "a", "single", "pixel", "in", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L133-L136
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.set_pixel_if_within_bounds
def set_pixel_if_within_bounds(x, y, color) return unless include_xy?(x, y) @pixels[y * width + x] = color end
ruby
def set_pixel_if_within_bounds(x, y, color) return unless include_xy?(x, y) @pixels[y * width + x] = color end
[ "def", "set_pixel_if_within_bounds", "(", "x", ",", "y", ",", "color", ")", "return", "unless", "include_xy?", "(", "x", ",", "y", ")", "@pixels", "[", "y", "*", "width", "+", "x", "]", "=", "color", "end" ]
Replaces a single pixel in this canvas, with bounds checking. It will do noting if the provided coordinates are out of bounds. @param [Integer] x The x-coordinate of the pixel (column) @param [Integer] y The y-coordinate of the pixel (row) @param [Integer] color The new color value for the provided coordinates. @return [Integer] The new color value for this pixel, i.e. <tt>color</tt>, or <tt>nil</tt> if the coordinates are out of bounds.
[ "Replaces", "a", "single", "pixel", "in", "this", "canvas", "with", "bounds", "checking", ".", "It", "will", "do", "noting", "if", "the", "provided", "coordinates", "are", "out", "of", "bounds", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L160-L163
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.column
def column(x) assert_x!(x) (0...height).inject([]) { |pixels, y| pixels << get_pixel(x, y) } end
ruby
def column(x) assert_x!(x) (0...height).inject([]) { |pixels, y| pixels << get_pixel(x, y) } end
[ "def", "column", "(", "x", ")", "assert_x!", "(", "x", ")", "(", "0", "...", "height", ")", ".", "inject", "(", "[", "]", ")", "{", "|", "pixels", ",", "y", "|", "pixels", "<<", "get_pixel", "(", "x", ",", "y", ")", "}", "end" ]
Returns an extracted column as vector of pixels. @param [Integer] x The 0-based column index. @return [Array<Integer>] The vector of pixels in the requested column.
[ "Returns", "an", "extracted", "column", "as", "vector", "of", "pixels", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L198-L201
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_row!
def replace_row!(y, vector) assert_y!(y) && assert_width!(vector.length) pixels[y * width, width] = vector end
ruby
def replace_row!(y, vector) assert_y!(y) && assert_width!(vector.length) pixels[y * width, width] = vector end
[ "def", "replace_row!", "(", "y", ",", "vector", ")", "assert_y!", "(", "y", ")", "&&", "assert_width!", "(", "vector", ".", "length", ")", "pixels", "[", "y", "*", "width", ",", "width", "]", "=", "vector", "end" ]
Replaces a row of pixels on this canvas. @param [Integer] y The 0-based row index. @param [Array<Integer>] vector The vector of pixels to replace the row with. @return [void]
[ "Replaces", "a", "row", "of", "pixels", "on", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L208-L211
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_column!
def replace_column!(x, vector) assert_x!(x) && assert_height!(vector.length) for y in 0...height do set_pixel(x, y, vector[y]) end end
ruby
def replace_column!(x, vector) assert_x!(x) && assert_height!(vector.length) for y in 0...height do set_pixel(x, y, vector[y]) end end
[ "def", "replace_column!", "(", "x", ",", "vector", ")", "assert_x!", "(", "x", ")", "&&", "assert_height!", "(", "vector", ".", "length", ")", "for", "y", "in", "0", "...", "height", "do", "set_pixel", "(", "x", ",", "y", ",", "vector", "[", "y", "]", ")", "end", "end" ]
Replaces a column of pixels on this canvas. @param [Integer] x The 0-based column index. @param [Array<Integer>] vector The vector of pixels to replace the column with. @return [void]
[ "Replaces", "a", "column", "of", "pixels", "on", "this", "canvas", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L218-L223
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.inspect
def inspect inspected = "<#{self.class.name} #{width}x#{height} [" for y in 0...height inspected << "\n\t[" << row(y).map { |p| ChunkyPNG::Color.to_hex(p) }.join(" ") << "]" end inspected << "\n]>" end
ruby
def inspect inspected = "<#{self.class.name} #{width}x#{height} [" for y in 0...height inspected << "\n\t[" << row(y).map { |p| ChunkyPNG::Color.to_hex(p) }.join(" ") << "]" end inspected << "\n]>" end
[ "def", "inspect", "inspected", "=", "\"<#{self.class.name} #{width}x#{height} [\"", "for", "y", "in", "0", "...", "height", "inspected", "<<", "\"\\n\\t[\"", "<<", "row", "(", "y", ")", ".", "map", "{", "|", "p", "|", "ChunkyPNG", "::", "Color", ".", "to_hex", "(", "p", ")", "}", ".", "join", "(", "\" \"", ")", "<<", "\"]\"", "end", "inspected", "<<", "\"\\n]>\"", "end" ]
Alternative implementation of the inspect method. @return [String] A nicely formatted string representation of this canvas. @private
[ "Alternative", "implementation", "of", "the", "inspect", "method", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L297-L303
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.replace_canvas!
def replace_canvas!(new_width, new_height, new_pixels) unless new_pixels.length == new_width * new_height raise ArgumentError, "The provided pixel array should have #{new_width * new_height} items" end @width, @height, @pixels = new_width, new_height, new_pixels self end
ruby
def replace_canvas!(new_width, new_height, new_pixels) unless new_pixels.length == new_width * new_height raise ArgumentError, "The provided pixel array should have #{new_width * new_height} items" end @width, @height, @pixels = new_width, new_height, new_pixels self end
[ "def", "replace_canvas!", "(", "new_width", ",", "new_height", ",", "new_pixels", ")", "unless", "new_pixels", ".", "length", "==", "new_width", "*", "new_height", "raise", "ArgumentError", ",", "\"The provided pixel array should have #{new_width * new_height} items\"", "end", "@width", ",", "@height", ",", "@pixels", "=", "new_width", ",", "new_height", ",", "new_pixels", "self", "end" ]
Replaces the image, given a new width, new height, and a new pixel array.
[ "Replaces", "the", "image", "given", "a", "new", "width", "new", "height", "and", "a", "new", "pixel", "array", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L308-L314
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.assert_xy!
def assert_xy!(x, y) unless include_xy?(x, y) raise ChunkyPNG::OutOfBounds, "Coordinates (#{x},#{y}) out of bounds!" end true end
ruby
def assert_xy!(x, y) unless include_xy?(x, y) raise ChunkyPNG::OutOfBounds, "Coordinates (#{x},#{y}) out of bounds!" end true end
[ "def", "assert_xy!", "(", "x", ",", "y", ")", "unless", "include_xy?", "(", "x", ",", "y", ")", "raise", "ChunkyPNG", "::", "OutOfBounds", ",", "\"Coordinates (#{x},#{y}) out of bounds!\"", "end", "true", "end" ]
Throws an exception if the x- or y-coordinate is out of bounds.
[ "Throws", "an", "exception", "if", "the", "x", "-", "or", "y", "-", "coordinate", "is", "out", "of", "bounds", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L333-L338
train
wvanbergen/chunky_png
lib/chunky_png/canvas.rb
ChunkyPNG.Canvas.assert_size!
def assert_size!(matrix_width, matrix_height) if width != matrix_width raise ChunkyPNG::ExpectationFailed, "The width of the matrix does not match the canvas width!" end if height != matrix_height raise ChunkyPNG::ExpectationFailed, "The height of the matrix does not match the canvas height!" end true end
ruby
def assert_size!(matrix_width, matrix_height) if width != matrix_width raise ChunkyPNG::ExpectationFailed, "The width of the matrix does not match the canvas width!" end if height != matrix_height raise ChunkyPNG::ExpectationFailed, "The height of the matrix does not match the canvas height!" end true end
[ "def", "assert_size!", "(", "matrix_width", ",", "matrix_height", ")", "if", "width", "!=", "matrix_width", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"The width of the matrix does not match the canvas width!\"", "end", "if", "height", "!=", "matrix_height", "raise", "ChunkyPNG", "::", "ExpectationFailed", ",", "\"The height of the matrix does not match the canvas height!\"", "end", "true", "end" ]
Throws an exception if the matrix width and height does not match this canvas' dimensions.
[ "Throws", "an", "exception", "if", "the", "matrix", "width", "and", "height", "does", "not", "match", "this", "canvas", "dimensions", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/canvas.rb#L361-L371
train
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.to_trns_chunk
def to_trns_chunk ChunkyPNG::Chunk::Transparency.new("tRNS", map { |c| ChunkyPNG::Color.a(c) }.pack("C*")) end
ruby
def to_trns_chunk ChunkyPNG::Chunk::Transparency.new("tRNS", map { |c| ChunkyPNG::Color.a(c) }.pack("C*")) end
[ "def", "to_trns_chunk", "ChunkyPNG", "::", "Chunk", "::", "Transparency", ".", "new", "(", "\"tRNS\"", ",", "map", "{", "|", "c", "|", "ChunkyPNG", "::", "Color", ".", "a", "(", "c", ")", "}", ".", "pack", "(", "\"C*\"", ")", ")", "end" ]
Creates a tRNS chunk that corresponds with this palette to store the alpha channel of all colors. Note that this chunk can be left out of every color in the palette is opaque, and the image is encoded using indexed colors. @return [ChunkyPNG::Chunk::Transparency] The tRNS chunk.
[ "Creates", "a", "tRNS", "chunk", "that", "corresponds", "with", "this", "palette", "to", "store", "the", "alpha", "channel", "of", "all", "colors", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L163-L165
train
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.to_plte_chunk
def to_plte_chunk @encoding_map = {} colors = [] each_with_index do |color, index| @encoding_map[color] = index colors += ChunkyPNG::Color.to_truecolor_bytes(color) end ChunkyPNG::Chunk::Palette.new("PLTE", colors.pack("C*")) end
ruby
def to_plte_chunk @encoding_map = {} colors = [] each_with_index do |color, index| @encoding_map[color] = index colors += ChunkyPNG::Color.to_truecolor_bytes(color) end ChunkyPNG::Chunk::Palette.new("PLTE", colors.pack("C*")) end
[ "def", "to_plte_chunk", "@encoding_map", "=", "{", "}", "colors", "=", "[", "]", "each_with_index", "do", "|", "color", ",", "index", "|", "@encoding_map", "[", "color", "]", "=", "index", "colors", "+=", "ChunkyPNG", "::", "Color", ".", "to_truecolor_bytes", "(", "color", ")", "end", "ChunkyPNG", "::", "Chunk", "::", "Palette", ".", "new", "(", "\"PLTE\"", ",", "colors", ".", "pack", "(", "\"C*\"", ")", ")", "end" ]
Creates a PLTE chunk that corresponds with this palette to store the r, g, and b channels of all colors. @note A PLTE chunk should only be included if the image is encoded using index colors. After this chunk has been built, the palette becomes suitable for encoding an image. @return [ChunkyPNG::Chunk::Palette] The PLTE chunk. @see ChunkyPNG::Palette#can_encode?
[ "Creates", "a", "PLTE", "chunk", "that", "corresponds", "with", "this", "palette", "to", "store", "the", "r", "g", "and", "b", "channels", "of", "all", "colors", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L176-L186
train
wvanbergen/chunky_png
lib/chunky_png/palette.rb
ChunkyPNG.Palette.best_color_settings
def best_color_settings if black_and_white? [ChunkyPNG::COLOR_GRAYSCALE, 1] elsif grayscale? if opaque? [ChunkyPNG::COLOR_GRAYSCALE, 8] else [ChunkyPNG::COLOR_GRAYSCALE_ALPHA, 8] end elsif indexable? [ChunkyPNG::COLOR_INDEXED, determine_bit_depth] elsif opaque? [ChunkyPNG::COLOR_TRUECOLOR, 8] else [ChunkyPNG::COLOR_TRUECOLOR_ALPHA, 8] end end
ruby
def best_color_settings if black_and_white? [ChunkyPNG::COLOR_GRAYSCALE, 1] elsif grayscale? if opaque? [ChunkyPNG::COLOR_GRAYSCALE, 8] else [ChunkyPNG::COLOR_GRAYSCALE_ALPHA, 8] end elsif indexable? [ChunkyPNG::COLOR_INDEXED, determine_bit_depth] elsif opaque? [ChunkyPNG::COLOR_TRUECOLOR, 8] else [ChunkyPNG::COLOR_TRUECOLOR_ALPHA, 8] end end
[ "def", "best_color_settings", "if", "black_and_white?", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE", ",", "1", "]", "elsif", "grayscale?", "if", "opaque?", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE", ",", "8", "]", "else", "[", "ChunkyPNG", "::", "COLOR_GRAYSCALE_ALPHA", ",", "8", "]", "end", "elsif", "indexable?", "[", "ChunkyPNG", "::", "COLOR_INDEXED", ",", "determine_bit_depth", "]", "elsif", "opaque?", "[", "ChunkyPNG", "::", "COLOR_TRUECOLOR", ",", "8", "]", "else", "[", "ChunkyPNG", "::", "COLOR_TRUECOLOR_ALPHA", ",", "8", "]", "end", "end" ]
Determines the most suitable colormode for this palette. @return [Integer] The colormode which would create the smallest possible file for images that use this exact palette.
[ "Determines", "the", "most", "suitable", "colormode", "for", "this", "palette", "." ]
691f8cb0fbe1816474bf8af8dbea4fb53debb816
https://github.com/wvanbergen/chunky_png/blob/691f8cb0fbe1816474bf8af8dbea4fb53debb816/lib/chunky_png/palette.rb#L191-L207
train
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.Fastbin.title
def title class_name = Helper.color(Helper.class_name(self), sev: :bin) size_str = index.nil? ? nil : "[#{Helper.color(format('%#x', idx_to_size))}]" "#{class_name}#{size_str}: " end
ruby
def title class_name = Helper.color(Helper.class_name(self), sev: :bin) size_str = index.nil? ? nil : "[#{Helper.color(format('%#x', idx_to_size))}]" "#{class_name}#{size_str}: " end
[ "def", "title", "class_name", "=", "Helper", ".", "color", "(", "Helper", ".", "class_name", "(", "self", ")", ",", "sev", ":", ":bin", ")", "size_str", "=", "index", ".", "nil?", "?", "nil", ":", "\"[#{Helper.color(format('%#x', idx_to_size))}]\"", "\"#{class_name}#{size_str}: \"", "end" ]
For pretty inspect. @return [String] Title with color codes.
[ "For", "pretty", "inspect", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L103-L107
train
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.Fastbin.inspect
def inspect title + list.map do |ptr| next "(#{ptr})\n" if ptr.is_a?(Symbol) next " => (nil)\n" if ptr.nil? format(' => %s', Helper.color(format('%#x', ptr))) end.join end
ruby
def inspect title + list.map do |ptr| next "(#{ptr})\n" if ptr.is_a?(Symbol) next " => (nil)\n" if ptr.nil? format(' => %s', Helper.color(format('%#x', ptr))) end.join end
[ "def", "inspect", "title", "+", "list", ".", "map", "do", "|", "ptr", "|", "next", "\"(#{ptr})\\n\"", "if", "ptr", ".", "is_a?", "(", "Symbol", ")", "next", "\" => (nil)\\n\"", "if", "ptr", ".", "nil?", "format", "(", "' => %s'", ",", "Helper", ".", "color", "(", "format", "(", "'%#x'", ",", "ptr", ")", ")", ")", "end", ".", "join", "end" ]
Pretty inspect. @return [String] fastbin layouts wrapper with color codes.
[ "Pretty", "inspect", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L111-L118
train
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.UnsortedBin.pretty_list
def pretty_list(list) center = nil list.map.with_index do |c, idx| next center = Helper.color('[self]', sev: :bin) if c == @base color_c = Helper.color(format('%#x', c)) fwd = fd_of(c) next "#{color_c}(invalid)" if fwd.nil? # invalid c bck = bk_of(c) if center.nil? # bk side format('%s%s', color_c, fwd == list[idx + 1] ? nil : Helper.color(format('(%#x)', fwd))) else # fd side format('%s%s', bck == list[idx - 1] ? nil : Helper.color(format('(%#x)', bck)), color_c) end end.join(' === ') end
ruby
def pretty_list(list) center = nil list.map.with_index do |c, idx| next center = Helper.color('[self]', sev: :bin) if c == @base color_c = Helper.color(format('%#x', c)) fwd = fd_of(c) next "#{color_c}(invalid)" if fwd.nil? # invalid c bck = bk_of(c) if center.nil? # bk side format('%s%s', color_c, fwd == list[idx + 1] ? nil : Helper.color(format('(%#x)', fwd))) else # fd side format('%s%s', bck == list[idx - 1] ? nil : Helper.color(format('(%#x)', bck)), color_c) end end.join(' === ') end
[ "def", "pretty_list", "(", "list", ")", "center", "=", "nil", "list", ".", "map", ".", "with_index", "do", "|", "c", ",", "idx", "|", "next", "center", "=", "Helper", ".", "color", "(", "'[self]'", ",", "sev", ":", ":bin", ")", "if", "c", "==", "@base", "color_c", "=", "Helper", ".", "color", "(", "format", "(", "'%#x'", ",", "c", ")", ")", "fwd", "=", "fd_of", "(", "c", ")", "next", "\"#{color_c}(invalid)\"", "if", "fwd", ".", "nil?", "# invalid c", "bck", "=", "bk_of", "(", "c", ")", "if", "center", ".", "nil?", "# bk side", "format", "(", "'%s%s'", ",", "color_c", ",", "fwd", "==", "list", "[", "idx", "+", "1", "]", "?", "nil", ":", "Helper", ".", "color", "(", "format", "(", "'(%#x)'", ",", "fwd", ")", ")", ")", "else", "# fd side", "format", "(", "'%s%s'", ",", "bck", "==", "list", "[", "idx", "-", "1", "]", "?", "nil", ":", "Helper", ".", "color", "(", "format", "(", "'(%#x)'", ",", "bck", ")", ")", ",", "color_c", ")", "end", "end", ".", "join", "(", "' === '", ")", "end" ]
Wrapper the doubly linked list with color codes. @param [Array<Integer>] list The list from {#link_list}. @return [String] Wrapper with color codes.
[ "Wrapper", "the", "doubly", "linked", "list", "with", "color", "codes", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L188-L204
train
david942j/heapinfo
lib/heapinfo/arena.rb
HeapInfo.UnsortedBin.link_list
def link_list(expand_size) list = [@base] # fd work = proc do |ptr, nxt, append| sz = 0 dup = {} while ptr != @base && sz < expand_size append.call(ptr) break if ptr.nil? || dup[ptr] # invalid or duplicated pointer dup[ptr] = true ptr = __send__(nxt, ptr) sz += 1 end end work.call(@fd, :fd_of, ->(ptr) { list << ptr }) work.call(@bk, :bk_of, ->(ptr) { list.unshift(ptr) }) list end
ruby
def link_list(expand_size) list = [@base] # fd work = proc do |ptr, nxt, append| sz = 0 dup = {} while ptr != @base && sz < expand_size append.call(ptr) break if ptr.nil? || dup[ptr] # invalid or duplicated pointer dup[ptr] = true ptr = __send__(nxt, ptr) sz += 1 end end work.call(@fd, :fd_of, ->(ptr) { list << ptr }) work.call(@bk, :bk_of, ->(ptr) { list.unshift(ptr) }) list end
[ "def", "link_list", "(", "expand_size", ")", "list", "=", "[", "@base", "]", "# fd", "work", "=", "proc", "do", "|", "ptr", ",", "nxt", ",", "append", "|", "sz", "=", "0", "dup", "=", "{", "}", "while", "ptr", "!=", "@base", "&&", "sz", "<", "expand_size", "append", ".", "call", "(", "ptr", ")", "break", "if", "ptr", ".", "nil?", "||", "dup", "[", "ptr", "]", "# invalid or duplicated pointer", "dup", "[", "ptr", "]", "=", "true", "ptr", "=", "__send__", "(", "nxt", ",", "ptr", ")", "sz", "+=", "1", "end", "end", "work", ".", "call", "(", "@fd", ",", ":fd_of", ",", "->", "(", "ptr", ")", "{", "list", "<<", "ptr", "}", ")", "work", ".", "call", "(", "@bk", ",", ":bk_of", ",", "->", "(", "ptr", ")", "{", "list", ".", "unshift", "(", "ptr", ")", "}", ")", "list", "end" ]
Return the double link list with bin in the center. The list will like +[..., bk of bk, bk of bin, bin, fd of bin, fd of fd, ...]+. @param [Integer] expand_size At most expand size. For +size = 2+, the expand list would be <tt>bk, bk, bin, fd, fd</tt>. @return [Array<Integer>] The linked list.
[ "Return", "the", "double", "link", "list", "with", "bin", "in", "the", "center", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/arena.rb#L212-L230
train
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.x
def x(count, address) commands = [address, count * size_t] base = base_of(*commands) res = dump(*commands).unpack(size_t == 4 ? 'L*' : 'Q*') str = res.group_by.with_index { |_, i| i / (16 / size_t) }.map do |round, values| Helper.hex(base + round * 16) + ":\t" + values.map { |v| Helper.color(format("0x%0#{size_t * 2}x", v)) }.join("\t") end.join("\n") puts str end
ruby
def x(count, address) commands = [address, count * size_t] base = base_of(*commands) res = dump(*commands).unpack(size_t == 4 ? 'L*' : 'Q*') str = res.group_by.with_index { |_, i| i / (16 / size_t) }.map do |round, values| Helper.hex(base + round * 16) + ":\t" + values.map { |v| Helper.color(format("0x%0#{size_t * 2}x", v)) }.join("\t") end.join("\n") puts str end
[ "def", "x", "(", "count", ",", "address", ")", "commands", "=", "[", "address", ",", "count", "*", "size_t", "]", "base", "=", "base_of", "(", "commands", ")", "res", "=", "dump", "(", "commands", ")", ".", "unpack", "(", "size_t", "==", "4", "?", "'L*'", ":", "'Q*'", ")", "str", "=", "res", ".", "group_by", ".", "with_index", "{", "|", "_", ",", "i", "|", "i", "/", "(", "16", "/", "size_t", ")", "}", ".", "map", "do", "|", "round", ",", "values", "|", "Helper", ".", "hex", "(", "base", "+", "round", "*", "16", ")", "+", "\":\\t\"", "+", "values", ".", "map", "{", "|", "v", "|", "Helper", ".", "color", "(", "format", "(", "\"0x%0#{size_t * 2}x\"", ",", "v", ")", ")", "}", ".", "join", "(", "\"\\t\"", ")", "end", ".", "join", "(", "\"\\n\"", ")", "puts", "str", "end" ]
Show dump results like in gdb's command +x+. Details are in {HeapInfo::Process#x}. @param [Integer] count The number of result need to dump. @param [Symbol, String, Integer] address The base address to be dumped. @return [void] @example x 3, 0x400000 # 0x400000: 0x00010102464c457f 0x0000000000000000 # 0x400010: 0x00000001003e0002
[ "Show", "dump", "results", "like", "in", "gdb", "s", "command", "+", "x", "+", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L68-L77
train
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.cstring
def cstring(address) base = base_of(address) len = 1 cur = '' loop do cur << (dump(base + len - 1, len) || '') break if cur.index("\x00") len <<= 1 return cur if cur.size != len - 1 # reached undumpable memory end cur[0, cur.index("\x00")] end
ruby
def cstring(address) base = base_of(address) len = 1 cur = '' loop do cur << (dump(base + len - 1, len) || '') break if cur.index("\x00") len <<= 1 return cur if cur.size != len - 1 # reached undumpable memory end cur[0, cur.index("\x00")] end
[ "def", "cstring", "(", "address", ")", "base", "=", "base_of", "(", "address", ")", "len", "=", "1", "cur", "=", "''", "loop", "do", "cur", "<<", "(", "dump", "(", "base", "+", "len", "-", "1", ",", "len", ")", "||", "''", ")", "break", "if", "cur", ".", "index", "(", "\"\\x00\"", ")", "len", "<<=", "1", "return", "cur", "if", "cur", ".", "size", "!=", "len", "-", "1", "# reached undumpable memory", "end", "cur", "[", "0", ",", "cur", ".", "index", "(", "\"\\x00\"", ")", "]", "end" ]
Dump data from +address+ until reach null-byte. @return [String]
[ "Dump", "data", "from", "+", "address", "+", "until", "reach", "null", "-", "byte", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L82-L94
train
david942j/heapinfo
lib/heapinfo/dumper.rb
HeapInfo.Dumper.base_len_of
def base_len_of(arg, len = DUMP_BYTES) segments = @info.call(:segments) || {} segments = segments.each_with_object({}) do |(k, seg), memo| memo[k] = seg.base end base = case arg when Integer then arg when Symbol then segments[arg] when String then Helper.evaluate(arg, store: segments) end raise ArgumentError, "Invalid base: #{arg.inspect}" unless base.is_a?(Integer) # invalid usage [base, len] end
ruby
def base_len_of(arg, len = DUMP_BYTES) segments = @info.call(:segments) || {} segments = segments.each_with_object({}) do |(k, seg), memo| memo[k] = seg.base end base = case arg when Integer then arg when Symbol then segments[arg] when String then Helper.evaluate(arg, store: segments) end raise ArgumentError, "Invalid base: #{arg.inspect}" unless base.is_a?(Integer) # invalid usage [base, len] end
[ "def", "base_len_of", "(", "arg", ",", "len", "=", "DUMP_BYTES", ")", "segments", "=", "@info", ".", "call", "(", ":segments", ")", "||", "{", "}", "segments", "=", "segments", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "k", ",", "seg", ")", ",", "memo", "|", "memo", "[", "k", "]", "=", "seg", ".", "base", "end", "base", "=", "case", "arg", "when", "Integer", "then", "arg", "when", "Symbol", "then", "segments", "[", "arg", "]", "when", "String", "then", "Helper", ".", "evaluate", "(", "arg", ",", "store", ":", "segments", ")", "end", "raise", "ArgumentError", ",", "\"Invalid base: #{arg.inspect}\"", "unless", "base", ".", "is_a?", "(", "Integer", ")", "# invalid usage", "[", "base", ",", "len", "]", "end" ]
Get the base address and length. +@info+ will be used for getting the segment base, so we can support use symbol as base address. @param [Integer, Symbol, String] arg The base address, see examples. @param [Integer] len An integer. @example base_len_of(123, 321) #=> [123, 321] base_len_of(123) #=> [123, DUMP_BYTES] base_len_of(:heap, 10) #=> [0x603000, 10] # assume heap base @ 0x603000 base_len_of('heap+0x30', 10) #=> [0x603030, 10] base_len_of('elf+0x3*2-1') #=> [0x400005, DUMP_BYTES]
[ "Get", "the", "base", "address", "and", "length", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/dumper.rb#L174-L187
train
david942j/heapinfo
lib/heapinfo/process_info.rb
HeapInfo.ProcessInfo.segments
def segments EXPORT.map do |sym| seg = __send__(sym) [sym, seg] if seg.is_a?(Segment) end.compact.to_h end
ruby
def segments EXPORT.map do |sym| seg = __send__(sym) [sym, seg] if seg.is_a?(Segment) end.compact.to_h end
[ "def", "segments", "EXPORT", ".", "map", "do", "|", "sym", "|", "seg", "=", "__send__", "(", "sym", ")", "[", "sym", ",", "seg", "]", "if", "seg", ".", "is_a?", "(", "Segment", ")", "end", ".", "compact", ".", "to_h", "end" ]
Return segemnts load currently. @return [Hash{Symbol => Segment}] The segments in hash format.
[ "Return", "segemnts", "load", "currently", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process_info.rb#L72-L77
train
david942j/heapinfo
lib/heapinfo/process_info.rb
HeapInfo.ProcessInfo.to_segment
def to_segment(sym) return nil unless EXPORT.include?(sym) seg = __send__(sym) return nil unless seg.is_a?(Segment) seg end
ruby
def to_segment(sym) return nil unless EXPORT.include?(sym) seg = __send__(sym) return nil unless seg.is_a?(Segment) seg end
[ "def", "to_segment", "(", "sym", ")", "return", "nil", "unless", "EXPORT", ".", "include?", "(", "sym", ")", "seg", "=", "__send__", "(", "sym", ")", "return", "nil", "unless", "seg", ".", "is_a?", "(", "Segment", ")", "seg", "end" ]
Convert symbol to segment. @return [HeapInfo::Segment?] The segment object.
[ "Convert", "symbol", "to", "segment", "." ]
0608067e2d7601249cf01e725f7b8389e390d3f6
https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process_info.rb#L83-L90
train