idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
17,000 | def execute purge_id_or_progress_uri purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri response = self . class . get purge_id_or_progress_uri , basic_auth : AkamaiApi . auth parse_response response end | Checks the status of the requested associated with the given argument |
17,001 | def execute retrieve_content = false with_soap_error_handling do response = client_call :get_info , message : request_body ( retrieve_content ) . to_s FindResponse . new response [ :eccu_info ] end end | Returns the details of an ECCU request |
17,002 | def execute * items akamai = Akamai :: Edgegrid :: HTTP . new ( address = baseuri . host , port = baseuri . port ) akamai . setup_edgegrid ( creds ) http = Net :: HTTP . new ( address = baseuri . host , port = baseuri . port ) http . use_ssl = true items = Array . wrap ( items . first ) if items . length == 1 req = Net... | Clean the requested resources . |
17,003 | def request_body items { type : type , action : action , domain : domain , objects : items } . to_json end | Request body to send to the API . |
17,004 | def purge action , type , items , opts = { } request = Purge :: Request . new action , type , domain : opts [ :domain ] request . execute items end | Purges one or more resources |
17,005 | def run ( string ) string = string . to_s ltr_count = chars_count ( string , ltr_regex ) rtl_count = chars_count ( string , rtl_regex ) diff = ltr_count - rtl_count return ltr if diff > 0 return rtl if diff < 0 nil end | Get the number of ltr and rtl characters in the supplied string and infer direction from the most common type . For this strategy the direction can be ltr or rtl but never bidi . In case of draw it returns nil . |
17,006 | def file content64 = get_if_handleable ( raw [ :contents ] ) { :content => content64 ? Base64 . decode64 ( content64 ) : nil , :size => raw [ :file_size ] . to_i , :name => get_if_handleable ( raw [ :filename ] ) , :md5 => get_if_handleable ( raw [ :md5_digest ] ) } . reject { | k , v | v . nil? } end | Uploaded file details |
17,007 | def property { :name => get_if_handleable ( raw [ :property_name ] ) , :exact_match => ( raw [ :property_name_exact_match ] == true ) , :type => get_if_handleable ( raw [ :property_type ] ) } . reject { | k , v | v . nil? } end | Digital property details |
17,008 | def get_if_handleable value case value when String then value when DateTime then value . to_time . utc . xmlschema ( 3 ) else nil end end | This method is used because for nil values savon will respond with an hash containing all other attributes . If we check that the expected type is matched we can prevent to retrieve wrong values |
17,009 | def run ( string ) string = string . to_s if ltr_mark? ( string ) && rtl_mark? ( string ) bidi elsif ltr_mark? ( string ) ltr elsif rtl_mark? ( string ) rtl end end | Look for the presence of unicode marks in given string and infers from them its direction |
17,010 | def add pattern node = @root if String ( pattern ) == pattern pattern . each_char do | char | if node . goto ( char ) == nil node = node . add ( char ) else node = node . goto ( char ) end end else for item in pattern if node . goto ( item ) == nil node = node . add ( item ) else node = node . goto ( item ) end end end... | Creates an empty AhoC Trie with only a root node |
17,011 | def can? ( action , subject , * extra_args ) while subject . is_a? ( Draper :: Decorator ) subject = subject . model end super ( action , subject , * extra_args ) end | actually don t need any code in my gem s namespace .. |
17,012 | def method_missing ( meth , * args , & blk ) assert_exists meth = selector_to_attribute ( meth ) if self . class :: ATTRIBUTES . include? ( meth ) || ( self . class == Element && @object . hasAttribute ( meth . to_s ) ) return @object . getAttribute ( meth . to_s ) end Log . warn "Element\#method_missing calling super ... | Dynamically get element attributes . |
17,013 | def get_pixel ( x , y ) index = ( y * @width + x ) pointindex = index * 3 Color . from_rgba ( @array [ pointindex + 2 ] . ord , @array [ pointindex + 1 ] . ord , @array [ pointindex ] . ord , @alpha ? @alpha [ index ] . ord : 255 ) end | return a Color object of a given x and y coord |
17,014 | def set_pixel ( x , y , color ) index = ( y * @width + x ) pointindex = index * 3 @array [ pointindex + 2 ] = color . r . chr @array [ pointindex + 1 ] = color . g . chr @array [ pointindex ] = color . b . chr if color . a != 255 then @alpha = 255 . chr * ( @height * @width ) unless @alpha @alpha [ index ] = color . a ... | Creates a duplicate of the image set a color value for a image |
17,015 | def traverse_subnodes ( aParentNode ) subnodes = aParentNode . subnodes broadcast ( :before_subnodes , aParentNode , subnodes ) subnodes . each { | a_node | a_node . accept ( self ) } broadcast ( :after_subnodes , aParentNode , subnodes ) end | Visit event . The visitor is about to visit the subnodes of a non terminal node . |
17,016 | def broadcast ( msg , * args ) subscribers . each do | subscr | next unless subscr . respond_to? ( msg ) || subscr . respond_to? ( :accept_all ) subscr . send ( msg , * args ) end end | Send a notification to all subscribers . |
17,017 | def goto ( uri , headers = nil ) uri = "http://#{uri}" unless uri =~ %r{ } request = HtmlUnit :: WebRequest . new ( :: Java :: JavaNet :: URL . new ( uri ) ) request . setAdditionalHeaders ( headers ) if headers request . setCharset ( @charset ) rescue_status_code_exception do self . page = @webclient . getPage ( reque... | Goto the given URL |
17,018 | def send_keys ( keys ) keys = keys . gsub ( / \s / , '' ) . scan ( / \{ \} /u ) . flatten keys . each do | key | element = @page . getFocusedElement case key when "{TAB}" @page . tabToNextElement when / \w / element . type ( key ) else raise NotImplementedError end end end | experimental - should be removed? |
17,019 | def resynchronized ( & block ) old_controller = @webclient . ajaxController @webclient . setAjaxController ( :: HtmlUnit :: NicelyResynchronizingAjaxController . new ) yield self @webclient . setAjaxController ( old_controller ) end | Allows you to temporarily switch to HtmlUnit s NicelyResynchronizingAjaxController to resynchronize ajax calls . |
17,020 | def confirm ( bool , & block ) blk = lambda { bool } listener . add_listener ( :confirm , & blk ) yield listener . remove_listener ( :confirm , blk ) end | Specify a boolean value to click either OK or Cancel in any confirm dialogs that might show up during the duration of the given block . |
17,021 | def add_checker ( checker = nil , & block ) if block_given? @error_checkers << block elsif Proc === checker @error_checkers << checker else raise ArgumentError , "argument must be a Proc or block" end end | Add a checker proc that will be run on every page load |
17,022 | def page = ( value ) return if @page == value @page = value if @page . respond_to? ( "getDocumentElement" ) @object = @page . getDocumentElement || @object elsif @page . is_a? HtmlUnit :: UnexpectedPage raise UnexpectedPageException , @page . getWebResponse . getContentType end render unless @viewer == DefaultViewer ru... | Sets the current page object for the browser |
17,023 | def enable_event_listener @event_listener ||= lambda do | event | self . page = @page ? @page . getEnclosingWindow . getEnclosedPage : event . getNewPage end listener . add_listener ( :web_window_event , & @event_listener ) end | Enable Celerity s internal WebWindowEventListener |
17,024 | def render @viewer . render_html ( self . send ( @render_type ) , url ) rescue Errno :: ECONNREFUSED , Errno :: ECONNRESET , Errno :: EPIPE @viewer = DefaultViewer end | Render the current page on the connected viewer . |
17,025 | def [] ( x , y ) if x . instance_of? Fixnum and y . instance_of? Fixnum get_pixel ( fixx ( x ) , fixy ( y ) ) else x = ( fixx ( x ) .. fixx ( x ) ) if x . instance_of? Fixnum y = ( fixy ( y ) .. fixy ( y ) ) if y . instance_of? Fixnum if x . instance_of? Range x = ( fixx ( x . first ) .. fixx ( x . last ) ) end if y . ... | Returs the color of a pixel locate in the given x and y coordinates or a rectangle section of the image if a range is specified |
17,026 | def []= ( x , y , obj ) if x . instance_of? Fixnum and y . instance_of? Fixnum set_pixel ( x , y , obj ) else x = ( x .. x ) if x . instance_of? Fixnum y = ( y .. y ) if y . instance_of? Fixnum width = x . count ( 0 .. y . count - 1 ) . each do | y_ | origpointer = y_ * obj . width * 3 destpointer = ( ( y . first + y_ ... | Set the color of a pixel locate in the given x and y coordinates or replace a rectangle section of the image with other image of equal dimensions if a range is specified |
17,027 | def each_pixel ( 0 .. @width - 1 ) . each do | x | ( 0 .. @height - 1 ) . each do | y | yield ( x , y , get_pixel ( x , y ) ) end end end | Walks each pixel on the image block is mandantory to call this function and return as yield block calls x y and pixel color for each pixel of the image |
17,028 | def map_pixel Image . new ( @width , @height ) do | x , y | yield ( x , y , get_pixel ( x , y ) ) end end | Creates a new image of same dimensions in which each pixel is replaced with the value returned by the block passed as parameter the block receives the coordinates and color of each pixel |
17,029 | def map_pixel! each_pixel do | x , y , color | set_pixel ( x , y , yield ( x , y , get_pixel ( x , y ) ) ) end self end | Replace each pixel of the image with the value returned by the block passed as parameter the block receives the coordinates and color of each pixel |
17,030 | def color_replace ( color1 , color2 ) newimage = self . dup newimage . color_replace! ( color1 , color2 ) newimage end | Duplicate the image and then call color_replace! method with the given parameters |
17,031 | def color_replace! ( color1 , color2 ) strcolor1 = color1 . to_s strcolor2 = color2 . to_s a = color2 . a . chr ( 0 .. width * height ) . each do | i | if pixel_data [ i * 3 .. i * 3 + 2 ] == strcolor1 then pixel_data [ i * 3 .. i * 3 + 2 ] = strcolor2 alpha_data [ i ] = a end end end | Replace the color given in the first argument by the color given in the second with alpha values |
17,032 | def mask ( color1 = nil ) color1 = color1 || Color . from_rgb ( 255 , 255 , 255 ) color2 = color1 . dup color2 . a = 0 color_replace ( color1 , color2 ) end | Replace a color with %100 transparency useful for mask drawing |
17,033 | def tdiff_unordered ( tree , & block ) return enum_for ( :tdiff_unordered , tree ) unless block unless tdiff_equal ( tree ) yield '-' , self yield '+' , tree return self end yield ' ' , self tdiff_recursive_unordered ( tree , & block ) return self end | Finds the differences between self and another tree not respecting the order of the nodes . |
17,034 | def tdiff_recursive_unordered ( tree , & block ) x = enum_for ( :tdiff_each_child , self ) y = enum_for ( :tdiff_each_child , tree ) unchanged = { } changes = [ ] x . each_with_index do | xi , i | y . each_with_index do | yj , j | if ( ! unchanged . has_value? ( yj ) && xi . tdiff_equal ( yj ) ) unchanged [ xi ] = yj c... | Recursively compares the differences between the children nodes without respecting the order of the nodes . |
17,035 | def get_drive drive_id url = base_api_url + "/drives/#{drive_id}" @drives = JSON . parse ( HTTParty . get ( url , headers : set_headers ) . body ) end | Get a drive by ID |
17,036 | def get_users_drive id_or_user_principal_name url = base_api_url + "/users/#{id_or_user_principal_name}/drive" @drives = JSON . parse ( HTTParty . get ( url , headers : set_headers ) . body ) end | Get a user s OneDrive |
17,037 | def get_my_drive url = base_api_url + "/me/drive" @my_drive = JSON . parse ( HTTParty . get ( url , headers : set_headers ) . body ) end | Get a current user s OneDrive |
17,038 | def get_library_for_site site_id url = base_api_url + "/sites/#{site_id}/drive" @drives = JSON . parse ( HTTParty . get ( url , headers : set_headers ) . body ) end | Get the document library for a site |
17,039 | def get_special_folder_by_name name url = base_api_url + "/me/drive/special/#{name}" @special_drive = JSON . parse ( HTTParty . get ( url , headers : set_headers ) . body ) end | Get a special folder by name |
17,040 | def child_cell ( index ) assert_exists if ( index - Celerity . index_offset ) >= @cells . length raise UnknownCellException , "Unable to locate a cell at index #{index}" end TableCell . new ( self , :object , @cells [ index - Celerity . index_offset ] ) end | Get the child cell at the given index |
17,041 | def to_a assert_exists rows . map do | table_row | table_row . map { | td | td . text } end end | Returns the text of each cell in the the table as a two - dimensional array . |
17,042 | def start! @buffer = @env [ Thin :: Request :: RACK_INPUT ] . read + @buffer @env . delete Thin :: Request :: RACK_INPUT @env . delete Thin :: Request :: ASYNC_CALLBACK @env . delete Thin :: Request :: ASYNC_CLOSE @version = @env [ 'HTTP_SEC_WEBSOCKET_VERSION' ] @version ||= "hixie-76" if @env . has_key? ( 'HTTP_SEC_WE... | Start the websocket connection |
17,043 | def send_frame opcode , payload = "" , masked = false payload = payload . dup . force_encoding ( "ASCII-8BIT" ) if payload . respond_to? :force_encoding payload_length = payload . bytesize fin_byte = 0x80 send_data [ fin_byte | opcode ] . pack ( "C" ) masked_byte = masked ? 0x80 : 0x00 if payload_length <= 125 send_dat... | This is for post - hixie - 76 versions only |
17,044 | def finish! if hixie_75? or hixie_76? send_data "\xff\x00" else send_frame OPCODE_CLOSE end EM . next_tick { callback ( :on_finish , self ) rescue error! "Error in finish callback" } EM . next_tick { close_connection_after_writing } @state = :finished rescue error! "Error finishing WebSocket connection" end | Finish the connection read for closing |
17,045 | def elements_by_xpath ( xpath ) assert_exists objects = @page . getByXPath ( xpath ) objects . map { | o | element_from_dom_node ( o ) } end | Get all the elements matching the given XPath . |
17,046 | def element_from_dom_node ( obj , identifier_string = nil ) element_class = Util . htmlunit2celerity ( obj . class ) || Element element = element_class . new ( self , :object , obj ) element . identifier_string = identifier_string element . extend ( ClickableElement ) unless element . is_a? ( ClickableElement ) element... | Convert the given HtmlUnit DomNode to a Celerity object |
17,047 | def contains_text ( expected_text ) assert_exists case expected_text when Regexp value ( ) =~ expected_text when String value ( ) . index ( expected_text ) else raise TypeError , "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}" end end | Check if the given text fields contains the given String or Regexp . |
17,048 | def merge_resultset ( array ) new_array = dup array . each_with_index do | element , i | pair = [ element , new_array [ i ] ] new_array [ i ] = if pair . any? ( & :nil? ) && pair . map ( & :to_i ) . all? ( & :zero? ) nil else element . to_i + new_array [ i ] . to_i end end new_array end | Merges an array of coverage results with self |
17,049 | def file_created_date assert_exists web_response = @object . getWebResponse ( true ) Time . parse ( web_response . getResponseHeaderValue ( "Last-Modified" ) . to_s ) end | returns the file created date of the image |
17,050 | def save ( filename ) assert_exists image_reader = @object . getImageReader file = java . io . File . new ( filename ) buffered_image = image_reader . read ( 0 ) ; javax . imageio . ImageIO . write ( buffered_image , image_reader . getFormatName ( ) , file ) ; end | Saves the image to the given file |
17,051 | def matches? ( string , what ) Regexp === what ? string . strip =~ what : string == what . to_s end | Used internally . |
17,052 | def add_listener ( type , & block ) case type when :status @webclient . setStatusHandler ( self ) when :alert @webclient . setAlertHandler ( self ) when :attachment @webclient . setAttachmentHandler ( self ) when :web_window_event @webclient . addWebWindowListener ( self ) when :html_parser @webclient . setHTMLParserLi... | Add a listener block for one of the available types . |
17,053 | def traverse_children ( aParentNode ) children = aParentNode . children broadcast ( :before_subnodes , aParentNode , children ) children . each_with_index do | a_node , i | edge_sign = aParentNode . signatures [ i ] if a_node . kind_of? ( SPPF :: CompositeNode ) push_node ( a_node , edge_sign ) access_paths = node_acce... | Visit event . The visitor is about to visit the children of a non terminal node . |
17,054 | def [] ( n ) if @elements && @elements [ n - Celerity . index_offset ] element_class . new ( @container , :object , @elements [ n - Celerity . index_offset ] ) else iterator_object ( n - Celerity . index_offset ) end end | Get the element at the given index . By default this is 1 - indexed to keep compatibility with Watir . |
17,055 | def selected? ( value ) assert_exists raise UnknownObjectException , "unknown option with value #{value.inspect} for select_list #{@conditions.inspect}" unless include? ( value ) ! ! @object . getOptions . find { | e | matches_option? ( e , value ) && e . isSelected } end | Returns true if any of the selected options match the given value . |
17,056 | def contains_text ( expected_text ) assert_exists return nil unless respond_to? :text case expected_text when Regexp text ( ) =~ expected_text when String text ( ) . index ( expected_text ) else raise TypeError , "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}" end end | Check if the element contains the given text . |
17,057 | def parse ( aTokenizer ) tokens = [ ] aTokenizer . each do | a_token | next unless a_token term_name = a_token . terminal term_symb = grammar . name2symbol [ term_name ] a_token . instance_variable_set ( :@terminal , term_symb ) tokens << a_token end parser = build_parser ( grammar ) parser . gf_graph . diagnose if con... | Parse the sequence of tokens produced by the given tokenizer object . |
17,058 | def to_ptree ( aRawParse ) factory = ParseRep :: ParseTreeFactory . new ( aRawParse ) if configuration . repr_builder == :default result = factory . create ( nil ) else result = factory . create ( configuration . repr_builder ) end return result end | Convert raw parse result into a parse tree representation |
17,059 | def to_pforest ( aRawParse ) factory = ParseRep :: ParseForestFactory . new ( aRawParse ) if configuration . repr_builder == :default result = factory . create ( nil ) else result = factory . create ( configuration . repr_builder ) end return result end | Convert raw parse result into a parse forest representation |
17,060 | def with_nullpointer_retry ( max_retries = 3 ) tries = 0 yield rescue java . lang . NullPointerException => e raise e if tries >= max_retries tries += 1 warn "warning: celerity caught #{e} - retry ##{tries}" retry end | HtmlUnit throws NPEs sometimes when we re locating elements Retry seems to work fine . |
17,061 | def click_and_attach assert_exists_and_enabled browser = Browser . new ( @browser . options . dup ) browser . webclient . set_cookie_manager ( @browser . webclient . get_cookie_manager ) @browser . disable_event_listener do rescue_status_code_exception { browser . page = @object . click } end browser end | Click the element and return a new Browser instance with the resulting page . This is useful for elements that trigger popups when clicked . |
17,062 | def value? ( value ) value = Erlang . from ( value ) each { | k , v | return true if value == v } return false end | Return true if this Map has one or more keys which map to the provided value . |
17,063 | def get ( key ) key = Erlang . from ( key ) entry = @trie . get ( key ) if entry return entry [ 1 ] elsif @default return @default . call ( key ) end end | Retrieve the value corresponding to the provided key object . If not found and this Map has a default block the default block is called to provide the value . Otherwise return nil . |
17,064 | def fetch ( key , default = Undefined ) key = Erlang . from ( key ) entry = @trie . get ( key ) if entry return entry [ 1 ] elsif block_given? return yield ( key ) elsif not Undefined . equal? ( default ) return Erlang . from ( default ) else raise KeyError , "key not found: #{key.inspect}" end end | Retrieve the value corresponding to the given key object or use the provided default value or block or otherwise raise a KeyError . |
17,065 | def slice ( * wanted ) trie = Trie . new ( 0 ) wanted . each { | key | key = Erlang . from ( key ) trie . put! ( key , get ( key ) ) if key? ( key ) } return self . class . alloc ( trie , @default ) end | Return a new Map with only the associations for the wanted keys retained . |
17,066 | def poll_queue @job = reserve_job if @job . nil? @log . info ( 'No job found' ) else @log . info ( 'Job starting' ) begin @current_job_start_time = Time . now execute_job rescue => e @log . info ( "Error running test: #{e.message}\n : #{e.backtrace.join("\n :")}" ) end cleanup end end | The main worker process loop Check the queues for work |
17,067 | def reserve_job @log . info "Trying to reserve job for queues: #{@queues.join(', ')}" job = job_message_klass . reserve ( @queues , reservation_details ) @log . debug "Job: #{job.inspect}" raise InvalidJobReservationError . new ( "Invalid Job Reserved" ) if ! ( job . nil? || job . valid? ) job end | Try to find and reserve a job |
17,068 | def diagnostics retn = true protect retn = @diagnostic_runner . run if ! @diagnostic_runner . nil? unprotect @log . info ( 'Diagnostics failed' ) if not retn status = device_status status = set_device_status ( 'happy' ) if status == 'busy' raise DeviceNotReady . new ( "Current device status: '#{status}'" ) if status !=... | Diagnostics function to be extended in child class as required |
17,069 | def upload_files ( job , * paths ) @log . info ( "Uploading assets" ) paths . each do | path | @log . info ( "Uploading files from #{path}" ) Dir . foreach ( path ) do | item | @log . info ( "File: #{item}" ) next if item == '.' or item == '..' begin artifact = job . report_artifact ( "#{path}/#{item}" ) @log . info ( ... | Upload any files from the test |
17,070 | def checkout_code ( repository , checkout_directory , branch ) CodeCache . repo ( repository ) . checkout ( :head , checkout_directory , branch ) or raise "Unable to checkout repository #{repository}" end | Get a checkout of the repository |
17,071 | def gremlins { space : "\u2420" , tab : "\u21B9" , carriage_return : "\u23CE" , line_feed : "\u240A" , control_c : "\u2404" , control_d : "\u2403" , control_r : "\u2412" , escape : "\u238B" , backspace : "\u2408" , delete : "\u232B" , up : "\u2191" , down : "\u2193" , left : "\u2190" , right : "\u2192" } end | Glyphs and Alternate Names |
17,072 | def bitslice ( arg , length = ( missing_length = true ) ) if missing_length if arg . is_a? ( Range ) from , to = arg . begin , arg . end from += bitsize if from < 0 return nil if from < 0 to += bitsize if to < 0 to += 1 if ! arg . exclude_end? length = to - from length = 0 if length < 0 length = bitsize - from if ( fro... | Return specific objects from the Bitstring . All overloads return nil if the starting index is out of range . |
17,073 | def each_bit return enum_for ( :each_bit ) unless block_given? index = 0 headbits = ( self . bytesize - 1 ) * 8 skipbits = 8 - @bits @data . each_byte do | byte | loop do break if index == @bitsize if index >= headbits bit = ( byte >> ( 7 - ( ( index + skipbits ) & 7 ) ) ) & 1 else bit = ( byte >> ( 7 - ( index & 7 ) )... | Call the given block once for each bit in the Bitstring passing each bit from first to last successively to the block . If no block is given returns an Enumerator . |
17,074 | def start_crmux! ( opts ) self . chrome_debugging_port = find_free_port ( Capybara :: ChromeDevTools . preferred_port ) self . crmux_listen_port = find_free_port ( chrome_debugging_port + 1 ) opts [ :options ] . args << "--remote-debugging-port=#{chrome_debugging_port}" @debug_crmux = true command = "npx crmux #{'-d' i... | Starts crmux and adds debuggerAddress to opts that points to crmux listen address . |
17,075 | def start parent_pid = Process . pid @worker_pid = Process . fork do object = Object @worker_class . split ( '::' ) . each { | sub | object = object . const_get ( sub ) } object . new ( @options . merge ( 'parent_pid' => parent_pid , 'device_identity' => self . identity , 'port_allocator' => self . port_allocator , 'hi... | Initialise the device Start the worker process |
17,076 | def stop protect_file = File . expand_path ( "#{@worker_pid}.protect" , PIDS_DIRECTORY ) Hive . logger . debug ( "Checking for protected file: #{protect_file}" ) if File . exists? File . expand_path ( "#{@worker_pid}.protect" , PIDS_DIRECTORY ) Hive . logger . debug ( "PID #{@worker_pid} is protected" ) false else @sto... | Terminate the worker process |
17,077 | def padded_line ( iteration , elapsed_time ) meter_line = line ( iteration , elapsed_time ) pad_size = [ @last_printed_length - meter_line . size , 0 ] . max @last_printed_length = meter_line . size meter_line + ' ' * pad_size end | Initialize a new Printer . |
17,078 | def put ( index , element = yield ( get ( index ) ) ) raise IndexError , "index #{index} outside of tuple bounds" if index < - @size element = Erlang . from ( element ) index += @size if index < 0 if index > @size suffix = Array . new ( index - @size , nil ) suffix << element return replace_suffix ( @size , suffix ) el... | Return a new Tuple with a new value at the given index . If index is greater than the length of the tuple the returned tuple will be padded with nil s to the correct size . |
17,079 | def fetch ( index , default = ( missing_default = true ) ) if index >= - @size && index < @size return get ( index ) elsif block_given? return Erlang . from ( yield ( index ) ) elsif ! missing_default return Erlang . from ( default ) else raise IndexError , "index #{index} outside of tuple bounds" end end | Retrieve the value at index with optional default . |
17,080 | def slice ( arg , length = ( missing_length = true ) ) if missing_length if arg . is_a? ( Range ) from , to = arg . begin , arg . end from += @size if from < 0 to += @size if to < 0 to += 1 if ! arg . exclude_end? length = to - from length = 0 if length < 0 return subsequence ( from , length ) else return get ( arg ) e... | Return specific objects from the Tuple . All overloads return nil if the starting index is out of range . |
17,081 | def insert ( index , * elements ) raise IndexError if index < - @size index += @size if index < 0 elements = elements . map { | element | Erlang . from ( element ) } if index < @size suffix = flatten_suffix ( @root , @levels * BITS_PER_LEVEL , index , [ ] ) suffix . unshift ( * elements ) elsif index == @size suffix = ... | Return a new Tuple with the given values inserted before the element at index . If index is greater than the current length nil values are added to pad the Tuple to the required size . |
17,082 | def delete_at ( index ) return self if index >= @size || index < - @size index += @size if index < 0 suffix = flatten_suffix ( @root , @levels * BITS_PER_LEVEL , index , [ ] ) return replace_suffix ( index , suffix . tap { | a | a . shift } ) end | Return a new Tuple with the element at index removed . If the given index does not exist return self . |
17,083 | def select return enum_for ( :select ) unless block_given? return reduce ( self . class . empty ) { | tuple , element | yield ( element ) ? tuple . add ( element ) : tuple } end | Return a new Tuple containing all elements for which the given block returns true . |
17,084 | def shuffle return self . class . new ( ( ( array = to_a ) . frozen? ? array . shuffle : array . shuffle! ) . freeze ) end | Return a new Tuple with the same elements as this one but randomly permuted . |
17,085 | def reverse return self . class . new ( ( ( array = to_a ) . frozen? ? array . reverse : array . reverse! ) . freeze ) end | Return a new Tuple with the same elements as this one but in reverse order . |
17,086 | def rotate ( count = 1 ) return self if ( count % @size ) == 0 return self . class . new ( ( ( array = to_a ) . frozen? ? array . rotate ( count ) : array . rotate! ( count ) ) . freeze ) end | Return a new Tuple with the same elements but rotated so that the one at index count is the first element of the new tuple . If count is positive the elements will be shifted left and those shifted past the lowest position will be moved to the end . If count is negative the elements will be shifted right and those shif... |
17,087 | def sort ( & comparator ) comparator = Erlang . method ( :compare ) unless block_given? array = super ( & comparator ) return self . class . new ( array ) end | Return a new Tuple with the same elements but sorted . |
17,088 | def drop ( n ) return self if n == 0 return self . class . empty if n >= @size raise ArgumentError , "attempt to drop negative size" if n < 0 return self . class . new ( flatten_suffix ( @root , @levels * BITS_PER_LEVEL , n , [ ] ) ) end | Drop the first n elements and return the rest in a new Tuple . |
17,089 | def * ( times ) return self . class . empty if times == 0 return self if times == 1 result = ( to_a * times ) return result . is_a? ( Array ) ? self . class . new ( result ) : result end | Repetition . Return a new Tuple built by concatenating times copies of this one together . |
17,090 | def combination ( n ) return enum_for ( :combination , n ) if not block_given? return self if n < 0 || @size < n if n == 0 yield [ ] elsif n == 1 each { | element | yield [ element ] } elsif n == @size yield self . to_a else combos = lambda do | result , index , remaining | while @size - index > remaining if remaining ... | When invoked with a block yields all combinations of length n of elements from the Tuple and then returns self . There is no guarantee about which order the combinations will be yielded . |
17,091 | def repeated_combination ( n ) return enum_for ( :repeated_combination , n ) if not block_given? if n < 0 elsif n == 0 yield [ ] elsif n == 1 each { | element | yield [ element ] } elsif @size == 0 else combos = lambda do | result , index , remaining | while index < @size - 1 if remaining == 1 yield result . dup << get... | When invoked with a block yields all repeated combinations of length n of tuples from the Tuple and then returns self . A repeated combination is one in which any tuple from the Tuple can appear consecutively any number of times . |
17,092 | def permutation ( n = @size ) return enum_for ( :permutation , n ) if not block_given? if n < 0 || @size < n elsif n == 0 yield [ ] elsif n == 1 each { | element | yield [ element ] } else used , result = [ ] , [ ] perms = lambda do | index | 0 . upto ( @size - 1 ) do | i | if ! used [ i ] result [ index ] = get ( i ) ... | Yields all permutations of length n of elements from the Tuple and then returns self . If no length n is specified permutations of all elements will be yielded . |
17,093 | def product ( * tuples ) tuples = tuples . map { | tuple | Erlang . from ( tuple ) } return super if tuples . empty? tuples . unshift ( self ) if tuples . any? ( & :empty? ) return block_given? ? self : [ ] end counters = Array . new ( tuples . size , 0 ) bump_counters = lambda do i = tuples . size - 1 counters [ i ] +... | Cartesian product or multiplication . |
17,094 | def rindex ( obj = ( missing_arg = true ) ) obj = Erlang . from ( obj ) i = @size - 1 if missing_arg if block_given? reverse_each { | element | return i if yield element ; i -= 1 } return nil else return enum_for ( :rindex ) end else reverse_each { | element | return i if element == obj ; i -= 1 } return nil end end | Find the index of an element starting from the end of the tuple . Returns nil if no element is found . |
17,095 | def partition return enum_for ( :partition ) if not block_given? a , b = super return Erlang :: Tuple [ self . class . new ( a ) , self . class . new ( b ) ] end | Return 2 collections the first containing all the elements for which the block evaluates to true the second containing the rest . |
17,096 | def inspect result = "#{self.class}[" each_with_index { | obj , i | result << ', ' if i > 0 ; result << obj . inspect } return result << "]" end | Convert this collection to a programmer - readable String representation . |
17,097 | def each raise Erlang :: ImproperListError if improper? return to_enum unless block_given? list = self until list . empty? yield ( list . head ) list = list . tail end return self end | Call the given block once for each item in the list passing each item from first to last successively to the block . If no block is given returns an Enumerator . |
17,098 | def flat_map ( & block ) raise Erlang :: ImproperListError if improper? return enum_for ( :flat_map ) unless block_given? return self if empty? out = tail = Erlang :: Cons . allocate list = self until list . empty? head_list = Erlang :: List . from_enum ( yield ( list . head ) ) if head_list . empty? list = list . tail... | Return a List which is realized by transforming each item into a List and flattening the resulting lists . |
17,099 | def select ( & block ) raise Erlang :: ImproperListError if improper? return enum_for ( :select ) unless block_given? out = tail = Erlang :: Cons . allocate list = self while ! list . empty? if yield ( list . head ) new_node = Erlang :: Cons . allocate new_node . instance_variable_set ( :@head , list . head ) new_node ... | Return a List which contains all the items for which the given block returns true . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.