idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
8,000
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 .
8,001
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
8,002
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 .
8,003
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 .
8,004
def get ( path , api_version , data = { } , headers = { } ) execute :get , path , api_version , data , headers end
Perform a GET request .
8,005
def post ( path , api_version , data = { } , headers = { } ) execute :post , path , api_version , data , headers end
Perform a POST request .
8,006
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" => "appl...
Perform a POST request sending XML data .
8,007
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 e...
Perform a PUT request sending XML data .
8,008
def execute ( request_method , path , api_version , data , headers ) 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 .
8,009
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 .
8,010
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 .
8,011
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 .
8,012
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 .
8,013
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 .
8,014
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
8,015
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 .
8,016
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 .
8,017
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 .
8,018
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 .
8,019
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 .
8,020
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 .
8,021
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 .
8,022
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 ) self . pages...
Creates an instance of CategoryIndex for each category page renders it and writes the output to a file .
8,023
def write_category_indexes if self . layouts . key? 'category_index' self . categories . keys . each do | category | self . write_category_index ( category ) end else throw "No 'category_index' layout found." end end
Loops through the list of category pages and processes each one .
8,024
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 .
8,025
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 'in...
All resources or organizations should be invitable .
8,026
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
8,027
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
8,028
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
8,029
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_directo...
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
8,030
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 ...
creates a new heroku app via the API
8,031
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
8,032
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 ) +...
Builds a VTResult object based on the hash and results passed to it
8,033
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 <<...
Outputs the result to XML
8,034
def load_strings ( strings_filename ) strings = { } comments = { } file = File . open ( strings_filename , "r:utf-16:utf-8" ) begin contents = file . read if RUBY_VERSION == "1.9.2" require 'iconv' ic = Iconv . new ( 'UTF-8//IGNORE' , 'UTF-8' ) contents = ic . iconv ( contents + ' ' ) [ 0 .. - 2 ] end rescue Encoding :...
Load all strings of a given file
8,035
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 return unless row . count > 1 else next if row == nil or row [ @keys_column ] . nil? end row . size . times do | i ...
Convert csv file to multiple Localizable . strings files for each column
8,036
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 puts "Creating #{...
Process files and create csv
8,037
def basename ( file_path ) filename = File . basename ( file_path ) return filename . split ( '.' ) [ 0 ] . to_sym if file_path end
Basename of given file
8,038
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 ...
Create the resulting file
8,039
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
8,040
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 .
8,041
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 .
8,042
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
8,043
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 .
8,044
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 .
8,045
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_respons...
Make an RPC request and return its response .
8,046
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
8,047
def find_solution ( solution_constraints , valid_packages = nil ) packages_to_include_in_solve = trim_unreachable_packages ( dep_graph , solution_constraints ) begin solve ( dep_graph . clone , solution_constraints , valid_packages , packages_to_include_in_solve ) rescue Exceptions :: NoSolutionFound , Exceptions :: Ti...
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 n...
8,048
def process_soln_constraints ( workspace , solution_constraints , valid_packages ) gecode = workspace . gecode_wrapper soln_constraints_pkg_id = gecode . add_package ( 0 , 0 , 0 ) soln_constraints_on_non_existent_packages = [ ] soln_constraints_that_match_no_versions = [ ] solution_constraints . each do | soln_constrai...
This method validates SolutionConstraints and adds their corresponding constraints to the workspace .
8,049
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
8,050
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 .
8,051
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 . n...
Validates that each partial upload exists and is marked as one .
8,052
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 .
8,053
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 .
8,054
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 .
8,055
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 .
8,056
def to_blob str = StringIO . new str . set_encoding ( "ASCII-8BIT" ) write ( str ) str . string end
Encodes this datastream into a string .
8,057
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 .
8,058
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 ...
CONSTRUCTING COLOR VALUES
8,059
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 .
8,060
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 ...
Creates a new color from an HSV triple .
8,061
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} w...
Creates a new color from an HSL triple .
8,062
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 , ch...
Convert one HSL or HSV triple and associated chroma to a scaled rgb triple
8,063
def grayscale? ( value ) r ( value ) == b ( value ) && b ( value ) == g ( value ) end
Returns true if this color is fully transparent .
8,064
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...
Composes two colors with an alpha channel using integer math .
8,065
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 ) ) . ...
Composes two colors with an alpha channel using floating point math .
8,066
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 (...
Interpolates the foreground and background colors by the given alpha value . This also blends the alpha channels themselves .
8,067
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 .
8,068
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 .
8,069
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 .
8,070
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 .
8,071
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 .
8,072
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 .
8,073
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 .
8,074
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 .
8,075
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 .
8,076
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 Arg...
Gets a color value based on a HTML color name .
8,077
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 t...
STATIC UTILITY METHODS
8,078
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
8,079
def []= ( x , y , color ) assert_xy! ( x , y ) @pixels [ y * width + x ] = ChunkyPNG :: Color . parse ( color ) end
Replaces a single pixel in this canvas .
8,080
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 .
8,081
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 .
8,082
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 .
8,083
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 .
8,084
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 .
8,085
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 .
8,086
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 .
8,087
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 .
8,088
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 .
8,089
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 .
8,090
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 ] e...
Determines the most suitable colormode for this palette .
8,091
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 .
8,092
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 .
8,093
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? bck = bk_of ( c ) if center . nil? format ( '%s%s' , color_c , fw...
Wrapper the doubly linked list with color codes .
8,094
def link_list ( expand_size ) list = [ @base ] work = proc do | ptr , nxt , append | sz = 0 dup = { } while ptr != @base && sz < expand_size append . call ( ptr ) break if ptr . nil? || dup [ ptr ] dup [ ptr ] = true ptr = __send__ ( nxt , ptr ) sz += 1 end end work . call ( @fd , :fd_of , -> ( ptr ) { list << ptr } ) ...
Return the double link list with bin in the center .
8,095
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...
Show dump results like in gdb s command + x + .
8,096
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 end cur [ 0 , cur . index ( "\x00" ) ] end
Dump data from + address + until reach null - byte .
8,097
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...
Get the base address and length .
8,098
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 .
8,099
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 .