idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
38,300
public static MatrixAccumulator asSumAccumulator ( final double neutral ) { return new MatrixAccumulator ( ) { private BigDecimal result = BigDecimal . valueOf ( neutral ) ; @ Override public void update ( int i , int j , double value ) { result = result . add ( BigDecimal . valueOf ( value ) ) ; } @ Override public do...
Creates a sum matrix accumulator that calculates the sum of all elements in the matrix .
137
18
38,301
public static MatrixProcedure asAccumulatorProcedure ( final MatrixAccumulator accumulator ) { return new MatrixProcedure ( ) { @ Override public void apply ( int i , int j , double value ) { accumulator . update ( i , j , value ) ; } } ; }
Creates an accumulator procedure that adapts a matrix accumulator for procedure interface . This is useful for reusing a single accumulator for multiple fold operations in multiple matrices .
65
36
38,302
public void swapRows ( int i , int j ) { if ( i != j ) { Vector ii = getRow ( i ) ; Vector jj = getRow ( j ) ; setRow ( i , jj ) ; setRow ( j , ii ) ; } }
Swaps the specified rows of this matrix .
58
9
38,303
public void swapColumns ( int i , int j ) { if ( i != j ) { Vector ii = getColumn ( i ) ; Vector jj = getColumn ( j ) ; setColumn ( i , jj ) ; setColumn ( j , ii ) ; } }
Swaps the specified columns of this matrix .
58
9
38,304
public Matrix transpose ( ) { Matrix result = blankOfShape ( columns , rows ) ; MatrixIterator it = result . iterator ( ) ; while ( it . hasNext ( ) ) { it . next ( ) ; int i = it . rowIndex ( ) ; int j = it . columnIndex ( ) ; it . set ( get ( j , i ) ) ; } return result ; }
Transposes this matrix .
82
5
38,305
public double trace ( ) { double result = 0.0 ; for ( int i = 0 ; i < rows ; i ++ ) { result += get ( i , i ) ; } return result ; }
Calculates the trace of this matrix .
42
9
38,306
public double diagonalProduct ( ) { BigDecimal result = BigDecimal . ONE ; for ( int i = 0 ; i < rows ; i ++ ) { result = result . multiply ( BigDecimal . valueOf ( get ( i , i ) ) ) ; } return result . setScale ( Matrices . ROUND_FACTOR , RoundingMode . CEILING ) . doubleValue ( ) ; }
Calculates the product of diagonal elements of this matrix .
87
12
38,307
public double determinant ( ) { if ( rows != columns ) { throw new IllegalStateException ( "Can not compute determinant of non-square matrix." ) ; } if ( rows == 0 ) { return 0.0 ; } else if ( rows == 1 ) { return get ( 0 , 0 ) ; } else if ( rows == 2 ) { return get ( 0 , 0 ) * get ( 1 , 1 ) - get ( 0 , 1 ) * get ( 1 ,...
Calculates the determinant of this matrix .
501
10
38,308
public int rank ( ) { if ( rows == 0 || columns == 0 ) { return 0 ; } // TODO: // handle small (1x1, 1xn, nx1, 2x2, 2xn, nx2, 3x3, 3xn, nx3) // matrices without SVD MatrixDecompositor decompositor = withDecompositor ( LinearAlgebra . SVD ) ; Matrix [ ] usv = decompositor . decompose ( ) ; // TODO: Where is my pattern m...
Calculates the rank of this matrix .
201
9
38,309
public Matrix insertRow ( int i , Vector row ) { if ( i > rows || i < 0 ) { throw new IndexOutOfBoundsException ( "Illegal row number, must be 0.." + rows ) ; } Matrix result ; if ( columns == 0 ) { result = blankOfShape ( rows + 1 , row . length ( ) ) ; } else { result = blankOfShape ( rows + 1 , columns ) ; } for ( i...
Adds one row to matrix .
168
6
38,310
public Matrix insertColumn ( int j , Vector column ) { if ( j > columns || j < 0 ) { throw new IndexOutOfBoundsException ( "Illegal column number, must be 0.." + columns ) ; } Matrix result ; if ( rows == 0 ) { result = blankOfShape ( column . length ( ) , columns + 1 ) ; } else { result = blankOfShape ( rows , columns...
Adds one column to matrix .
178
6
38,311
public Matrix removeRow ( int i ) { if ( i >= rows || i < 0 ) { throw new IndexOutOfBoundsException ( "Illegal row number, must be 0.." + ( rows - 1 ) ) ; } Matrix result = blankOfShape ( rows - 1 , columns ) ; for ( int ii = 0 ; ii < i ; ii ++ ) { result . setRow ( ii , getRow ( ii ) ) ; } for ( int ii = i + 1 ; ii < ...
Removes one row from matrix .
131
7
38,312
public Matrix removeColumn ( int j ) { if ( j >= columns || j < 0 ) { throw new IndexOutOfBoundsException ( "Illegal column number, must be 0.." + ( columns - 1 ) ) ; } Matrix result = blankOfShape ( rows , columns - 1 ) ; for ( int jj = 0 ; jj < j ; jj ++ ) { result . setColumn ( jj , getColumn ( jj ) ) ; } for ( int ...
Removes one column from matrix .
141
7
38,313
public Matrix shuffle ( ) { Matrix result = copy ( ) ; // Conduct Fisher-Yates shuffle Random random = new Random ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < columns ; j ++ ) { int ii = random . nextInt ( rows - i ) + i ; int jj = random . nextInt ( columns - j ) + j ; double a = result . get ( ii...
Shuffles this matrix .
138
6
38,314
public Matrix slice ( int fromRow , int fromColumn , int untilRow , int untilColumn ) { ensureIndexArgumentsAreInBounds ( fromRow , fromColumn ) ; ensureIndexArgumentsAreInBounds ( untilRow - 1 , untilColumn - 1 ) ; if ( untilRow - fromRow < 0 || untilColumn - fromColumn < 0 ) { fail ( "Wrong slice range: [" + fromRow ...
Retrieves the specified sub - matrix of this matrix . The sub - matrix is specified by intervals for row indices and column indices .
197
27
38,315
public RowMajorMatrixIterator rowMajorIterator ( ) { return new RowMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private int i = - 1 ; @ Override public int rowIndex ( ) { return i / columns ; } @ Override public int columnIndex ( ) { return i - rowIndex ( ) * columns ; } @ Ove...
Returns a row - major matrix iterator .
195
8
38,316
public ColumnMajorMatrixIterator columnMajorIterator ( ) { return new ColumnMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private int i = - 1 ; @ Override public int rowIndex ( ) { return i - columnIndex ( ) * rows ; } @ Override public int columnIndex ( ) { return i / rows ; }...
Returns a column - major matrix iterator .
195
8
38,317
public RowMajorMatrixIterator nonZeroRowMajorIterator ( ) { return new RowMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private long i = - 1 ; @ Override public int rowIndex ( ) { return ( int ) ( i / columns ) ; } @ Override public int columnIndex ( ) { return ( int ) ( i - ( ...
Returns a non - zero row - major matrix iterator .
257
11
38,318
public static ParseException create ( List < ParseError > errors ) { if ( errors . size ( ) == 1 ) { return new ParseException ( errors . get ( 0 ) . getMessage ( ) , errors ) ; } else if ( errors . size ( ) > 1 ) { return new ParseException ( String . format ( "%d errors occured. First: %s" , errors . size ( ) , error...
Creates a new exception based on the list of errors .
127
12
38,319
public static Token create ( TokenType type , Position pos ) { Token result = new Token ( ) ; result . type = type ; result . line = pos . getLine ( ) ; result . pos = pos . getPos ( ) ; return result ; }
Creates a new token with the given type using the given position as location info .
53
17
38,320
public static Token createAndFill ( TokenType type , Char ch ) { Token result = new Token ( ) ; result . type = type ; result . line = ch . getLine ( ) ; result . pos = ch . getPos ( ) ; result . contents = ch . getStringValue ( ) ; result . trigger = ch . getStringValue ( ) ; result . source = ch . toString ( ) ; retu...
Creates a new token with the given type using the Char a initial trigger and content .
90
18
38,321
@ SuppressWarnings ( "squid:S1698" ) public boolean matches ( TokenType type , String trigger ) { if ( ! is ( type ) ) { return false ; } if ( trigger == null ) { throw new IllegalArgumentException ( "trigger must not be null" ) ; } return getTrigger ( ) == trigger . intern ( ) ; }
Determines if this token has the given type and trigger .
78
13
38,322
@ SuppressWarnings ( "squid:S1698" ) public boolean wasTriggeredBy ( String ... triggers ) { if ( triggers . length == 0 ) { return false ; } for ( String aTrigger : triggers ) { if ( aTrigger != null && aTrigger . intern ( ) == getTrigger ( ) ) { return true ; } } return false ; }
Determines if this token was triggered by one of the given triggers .
80
15
38,323
public static Expression parse ( String input ) throws ParseException { return new Parser ( new StringReader ( input ) , new Scope ( ) ) . parse ( ) ; }
Parses the given input into an expression .
36
10
38,324
protected Expression functionCall ( ) { FunctionCall call = new FunctionCall ( ) ; Token funToken = tokenizer . consume ( ) ; Function fun = functionTable . get ( funToken . getContents ( ) ) ; if ( fun == null ) { errors . add ( ParseError . error ( funToken , String . format ( "Unknown function: '%s'" , funToken . ge...
Parses a function call .
331
7
38,325
protected boolean canConsumeThisString ( String string , boolean consume ) { if ( string == null ) { return false ; } for ( int i = 0 ; i < string . length ( ) ; i ++ ) { if ( ! input . next ( i ) . is ( string . charAt ( i ) ) ) { return false ; } } if ( consume ) { input . consume ( string . length ( ) ) ; } return t...
Checks if the next characters starting from the current match the given string .
93
15
38,326
protected void skipBlockComment ( ) { while ( ! input . current ( ) . isEndOfInput ( ) ) { if ( isAtEndOfBlockComment ( ) ) { return ; } input . consume ( ) ; } problemCollector . add ( ParseError . error ( input . current ( ) , "Premature end of block comment" ) ) ; }
Checks if we re looking at an end of block comment
77
12
38,327
protected Token fetchString ( ) { char separator = input . current ( ) . getValue ( ) ; char escapeChar = stringDelimiters . get ( input . current ( ) . getValue ( ) ) ; Token result = Token . create ( Token . TokenType . STRING , input . current ( ) ) ; result . addToTrigger ( input . consume ( ) ) ; while ( ! input ....
Reads and returns a string constant .
310
8
38,328
protected Token fetchId ( ) { Token result = Token . create ( Token . TokenType . ID , input . current ( ) ) ; result . addToContent ( input . consume ( ) ) ; while ( isIdentifierChar ( input . current ( ) ) ) { result . addToContent ( input . consume ( ) ) ; } if ( ! input . current ( ) . isEndOfInput ( ) && specialId...
Reads and returns an identifier
212
6
38,329
protected Token handleKeywords ( Token idToken ) { String keyword = keywords . get ( keywordsCaseSensitive ? idToken . getContents ( ) . intern ( ) : idToken . getContents ( ) . toLowerCase ( ) . intern ( ) ) ; if ( keyword != null ) { Token keywordToken = Token . create ( Token . TokenType . KEYWORD , idToken ) ; keyw...
Checks if the given identifier is a keyword and returns an appropriate Token
131
14
38,330
protected Token fetchSpecialId ( ) { Token result = Token . create ( Token . TokenType . SPECIAL_ID , input . current ( ) ) ; result . addToTrigger ( input . consume ( ) ) ; while ( isIdentifierChar ( input . current ( ) ) ) { result . addToContent ( input . consume ( ) ) ; } return handleKeywords ( result ) ; }
Reads and returns a special id .
82
8
38,331
protected Token fetchNumber ( ) { Token result = Token . create ( Token . TokenType . INTEGER , input . current ( ) ) ; result . addToContent ( input . consume ( ) ) ; while ( input . current ( ) . isDigit ( ) || input . current ( ) . is ( decimalSeparator ) || ( input . current ( ) . is ( groupingSeparator ) && input ...
Reads and returns a number .
293
7
38,332
public Set < String > getNames ( ) { if ( parent == null ) { return getLocalNames ( ) ; } Set < String > result = new TreeSet <> ( ) ; result . addAll ( parent . getNames ( ) ) ; result . addAll ( getLocalNames ( ) ) ; return result ; }
Returns all names of variables known to this scope or one of its parent scopes .
68
17
38,333
public Collection < Variable > getVariables ( ) { if ( parent == null ) { return getLocalVariables ( ) ; } List < Variable > result = new ArrayList <> ( ) ; result . addAll ( parent . getVariables ( ) ) ; result . addAll ( getLocalVariables ( ) ) ; return result ; }
Returns all variables known to this scope or one of its parent scopes .
72
15
38,334
public static < T > T ifNull ( final T reference , final T defaultValue ) { if ( reference == null ) { return defaultValue ; } return reference ; }
If our reference is null then return a default value instead .
35
12
38,335
private Buffer consumeUntil ( final Buffer name ) { try { while ( this . params . hasReadableBytes ( ) ) { SipParser . consumeSEMI ( this . params ) ; final Buffer [ ] keyValue = SipParser . consumeGenericParam ( this . params ) ; ensureParamsMap ( ) ; final Buffer value = keyValue [ 1 ] == null ? Buffers . EMPTY_BUFFE...
Internal helper method that will consume all raw parameters until we find the specified name or if the name is null then that will be the same as consume all .
232
31
38,336
private void ensureParams ( ) { if ( this . isDirty ) { // note, it would only be dirty if we actually have inserted a value // so therefore no need to check that the parammap is null final Buffer restOfParams = this . params ; this . params = allcoateNewParamBuffer ( ) ; for ( final Map . Entry < Buffer , Buffer > ent...
Make sure that the internal params buffer is actually valid etc .
229
12
38,337
public static void basicExample001 ( ) throws IOException { final String rawMessage = new StringBuilder ( "BYE sip:bob@127.0.0.1:5060 SIP/2.0\r\n" ) . append ( "Via: SIP/2.0/UDP 127.0.1.1:5061;branch=z9hG4bK-28976-1-7\r\n" ) . append ( "From: alice <sip:alice@127.0.1.1:5061>;tag=28976SIPpTag001\r\n" ) . append ( "To: b...
This is the most basic example showing how you can parse a SIP message based off of a String . In this example we are the ones creating that raw message ourselves but typically you would read this off of the network or perhaps from a file if you are building a tool of some sort .
603
58
38,338
public static void basicExample003 ( ) throws Exception { // Generate a request again final SipRequest invite = SipRequest . invite ( "sip:alice@aboutsip.com" ) . withFromHeader ( "sip:bob@pkts.io" ) . build ( ) ; // Create a 200 OK to that INVITE and also add a generic // header for good measure. final SipResponse res...
Creating responses is typically done based off a request and SIP Lib allows you to do so but of course the object returned will be a builder .
135
29
38,339
private void init ( ) { this . currentState = CallState . START ; this . callTransitions = new ArrayList < CallState > ( ) ; this . messages = new TreeSet < SipPacket > ( new PacketComparator ( ) ) ; }
Start over from a clean slate ...
56
7
38,340
private void handleInCancellingState ( final SipPacket msg ) throws SipPacketParseException { // we don't move over to cancelled state even if // we receive a 200 OK to the cancel request. // therefore, not even checking it... if ( msg . isCancel ( ) ) { transition ( CallState . CANCELLING , msg ) ; return ; } if ( msg...
When in the cancelling state we may actually end up going back to IN_CALL in case we see a 2xx to the invite so pay attention for that .
199
34
38,341
private void handleInCompletedState ( final SipPacket msg ) throws SipPacketParseException { if ( msg . isRequest ( ) ) { // TODO: } else { if ( msg . isBye ( ) ) { transition ( CallState . COMPLETED , msg ) ; } } }
Handle state transitions for when we are already in the completed state .
65
13
38,342
private void handleInConfirmedState ( final SipPacket msg ) throws SipPacketParseException { if ( msg . isRequest ( ) ) { if ( msg . isBye ( ) ) { if ( this . byeRequest == null ) { this . byeRequest = msg . toRequest ( ) ; } transition ( CallState . COMPLETED , msg ) ; } else if ( msg . isAck ( ) ) { this . handshakeI...
We will only get to the confirmed state on a 2xx response to the INVITE . From here we can stay in the confirmed state if we get an ACK or transition over to completed if we get a BYE request .
193
46
38,343
private void transition ( final CallState nextState , final SipPacket msg ) { final CallState previousState = this . currentState ; this . currentState = nextState ; if ( previousState != nextState ) { // don't add the same transition twice this . callTransitions . add ( nextState ) ; } if ( logger . isInfoEnabled ( ) ...
Helper method for doing transitions .
118
6
38,344
private void setMacAddress ( final String macAddress , final boolean setSourceMacAddress ) throws IllegalArgumentException { if ( macAddress == null || macAddress . isEmpty ( ) ) { throw new IllegalArgumentException ( "Null or empty string cannot be a valid MAC Address." ) ; } // very naive implementation first. final ...
Helper method for setting the mac address in the header buffer .
204
12
38,345
private int calculateChecksum ( ) { long sum = 0 ; for ( int i = 0 ; i < this . headers . capacity ( ) - 1 ; i += 2 ) { if ( i != 10 ) { sum += this . headers . getUnsignedShort ( i ) ; } } while ( sum >> 16 != 0 ) { sum = ( sum & 0xffff ) + ( sum >> 16 ) ; } return ( int ) ~ sum & 0xFFFF ; }
Algorithm adopted from RFC 1071 - Computing the Internet Checksum
99
13
38,346
private void setIP ( final int startIndex , final String address ) { final String [ ] parts = address . split ( "\\." ) ; this . headers . setByte ( startIndex + 0 , ( byte ) Integer . parseInt ( parts [ 0 ] ) ) ; this . headers . setByte ( startIndex + 1 , ( byte ) Integer . parseInt ( parts [ 1 ] ) ) ; this . headers...
Very naive initial implementation . Should be changed to do a better job and its performance probably can go up a lot as well .
149
25
38,347
@ Override public int getHeaderLength ( ) { try { final byte b = this . headers . getByte ( 0 ) ; // length is encoded as the number of 32-bit words, so to get number of bytes we must multiply by 4 return ( b & 0x0F ) * 4 ; } catch ( final IOException e ) { throw new RuntimeException ( "unable to get the header length ...
The length of the ipv4 headers
100
8
38,348
public static Function < SipHeader , ? extends SipHeader > getFramer ( final Buffer b ) { // For headers that have the expected capitalization, do a quick case-sensitive // search. If that fails do a slower case-insensitive search. final Function < SipHeader , ? extends SipHeader > framer = framers . get ( b ) ; if ( f...
For the given header name return a function that will convert a generic header instance into one with the correct subtype .
155
23
38,349
public static boolean isUDP ( final Buffer t ) { try { return t . capacity ( ) == 3 && t . getByte ( 0 ) == ' ' && t . getByte ( 1 ) == ' ' && t . getByte ( 2 ) == ' ' ; } catch ( final IOException e ) { return false ; } }
Check whether the buffer is exactly three bytes long and has the bytes UDP in it .
70
17
38,350
public static boolean isUDPLower ( final Buffer t ) { try { return t . capacity ( ) == 3 && t . getByte ( 0 ) == ' ' && t . getByte ( 1 ) == ' ' && t . getByte ( 2 ) == ' ' ; } catch ( final IOException e ) { return false ; } }
Check whether the buffer is exactly three bytes long and has the bytes udp in it . Note in SIP there is a different between transport specified in a Via - header and a transport - param specified in a SIP URI . One is upper case one is lower case . Another really annoying thing with SIP .
71
63
38,351
public static boolean isNext ( final Buffer buffer , final byte b ) throws IOException { if ( buffer . hasReadableBytes ( ) ) { final byte actual = buffer . peekByte ( ) ; return actual == b ; } return false ; }
Will check whether the next readable byte in the buffer is a certain byte
51
14
38,352
public static boolean isNextDigit ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { if ( buffer . hasReadableBytes ( ) ) { final char next = ( char ) buffer . peekByte ( ) ; return next >= 48 && next <= 57 ; } return false ; }
Check whether the next byte is a digit or not
63
10
38,353
public static Buffer expectDigit ( final Buffer buffer ) throws SipParseException { final int start = buffer . getReaderIndex ( ) ; try { while ( buffer . hasReadableBytes ( ) && isNextDigit ( buffer ) ) { // consume it buffer . readByte ( ) ; } if ( start == buffer . getReaderIndex ( ) ) { throw new SipParseException ...
Will expect at least 1 digit and will continue consuming bytes until a non - digit is encountered
180
18
38,354
public static int expectWS ( final Buffer buffer ) throws SipParseException { int consumed = 0 ; try { if ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . getByte ( buffer . getReaderIndex ( ) ) ; if ( b == SP || b == HTAB ) { // ok, it was a WS so consume the byte buffer . readByte ( ) ; ++ consumed ; } els...
Expect the next byte to be a white space
197
10
38,355
public static Buffer consumeAlphaNum ( final Buffer buffer ) throws IOException { final int count = getAlphaNumCount ( buffer ) ; if ( count == 0 ) { return null ; } return buffer . readBytes ( count ) ; }
Consumes a alphanum .
48
7
38,356
public static int getAlphaNumCount ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { boolean done = false ; int count = 0 ; final int index = buffer . getReaderIndex ( ) ; while ( buffer . hasReadableBytes ( ) && ! done ) { final byte b = buffer . readByte ( ) ; if ( isAlphaNum ( b ) ) { ++ count...
Helper method that counts the number of bytes that are considered part of the next alphanum block .
106
20
38,357
public static boolean isNextAlphaNum ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { if ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . peekByte ( ) ; return isAlphaNum ( b ) ; } return false ; }
Check whether next byte is a alpha numeric one .
59
10
38,358
public static boolean isHostPortCharacter ( final char ch ) { return isAlphaNum ( ch ) || ch == DASH || ch == PERIOD || ch == COLON ; }
Checks whether the character could be part of the host portion of a SIP URI .
38
18
38,359
public static int consumeCRLF ( final Buffer buffer ) throws SipParseException { try { buffer . markReaderIndex ( ) ; final byte cr = buffer . readByte ( ) ; final byte lf = buffer . readByte ( ) ; if ( cr == CR && lf == LF ) { return 2 ; } } catch ( final IndexOutOfBoundsException e ) { // fall through } catch ( final...
Consume CR + LF
139
5
38,360
private static boolean isHeaderAllowingMultipleValues ( final Buffer headerName ) { final int size = headerName . getReadableBytes ( ) ; if ( size == 7 ) { return ! isSubjectHeader ( headerName ) ; } else if ( size == 5 ) { return ! isAllowHeader ( headerName ) ; } else if ( size == 4 ) { return ! isDateHeader ( header...
Not all headers allow for multiple values on a single line . This is a basic check for validating whether or not that the header allows it or not . Note for headers such as Contact it depends!
131
40
38,361
private static boolean isDateHeader ( final Buffer name ) { try { return name . getByte ( 0 ) == ' ' && name . getByte ( 1 ) == ' ' && name . getByte ( 2 ) == ' ' && name . getByte ( 3 ) == ' ' ; } catch ( final IOException e ) { return false ; } }
The date header also allows for comma within the value of the header .
73
14
38,362
public static SipHeader nextHeader ( final Buffer buffer ) throws SipParseException { try { final int startIndex = buffer . getReaderIndex ( ) ; int nameIndex = 0 ; while ( buffer . hasReadableBytes ( ) && nameIndex == 0 ) { if ( isNext ( buffer , SP ) || isNext ( buffer , HTAB ) || isNext ( buffer , COLON ) ) { nameIn...
Get the next header which may actually be returning multiple if there are multiple headers on the same line .
514
20
38,363
public static Buffer wrap ( final byte [ ] buffer ) { if ( buffer == null || buffer . length == 0 ) { throw new IllegalArgumentException ( "the buffer cannot be null or empty" ) ; } return new ByteBuffer ( buffer ) ; }
Wrap the supplied byte array
53
6
38,364
public static Buffer wrap ( final Buffer one , final Buffer two ) { // TODO: create an actual composite buffer. final int size1 = one != null ? one . getReadableBytes ( ) : 0 ; final int size2 = two != null ? two . getReadableBytes ( ) : 0 ; if ( size1 == 0 && size2 > 0 ) { return two . slice ( ) ; } else if ( size2 ==...
Combine two buffers into one . The resulting buffer will share the underlying byte storage so changing the value in one will affect the other . However the original two buffers will still have their own reader and writer index .
169
42
38,365
public static Buffer wrap ( final byte [ ] buffer , final int lowerBoundary , final int upperBoundary ) { if ( buffer == null || buffer . length == 0 ) { throw new IllegalArgumentException ( "the buffer cannot be null or empty" ) ; } if ( upperBoundary > buffer . length ) { throw new IllegalArgumentException ( "The upp...
Wrap the supplied byte array specifying the allowed range of visible bytes .
193
14
38,366
public void write ( final OutputStream out ) throws IOException { if ( this . byteOrder == ByteOrder . BIG_ENDIAN ) { out . write ( MAGIC_BIG_ENDIAN ) ; } else { out . write ( MAGIC_LITTLE_ENDIAN ) ; } out . write ( this . body ) ; }
Will write this header to the output stream .
72
9
38,367
public static PcapRecordHeader createDefaultHeader ( final long timestamp ) { final byte [ ] body = new byte [ SIZE ] ; // time stamp seconds // body[0] = (byte) 0x00; // body[1] = (byte) 0x00; // body[2] = (byte) 0x00; // body[3] = (byte) 0x00; // Time stamp microseconds // body[4] = (byte) 0x00; // body[5] = (byte) 0...
Create a default record header which you must alter later on to match whatever it is you are writing into the pcap stream .
328
25
38,368
public boolean process ( final byte [ ] newData ) { if ( newData != null ) { buffer . write ( newData ) ; } boolean done = false ; while ( ! done ) { final int index = buffer . getReaderIndex ( ) ; final State currentState = state ; state = actions [ state . ordinal ( ) ] . apply ( buffer ) ; done = state == currentSta...
Process more incoming data .
103
5
38,369
private final State onInit ( final Buffer buffer ) { try { while ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . peekByte ( ) ; if ( b == SipParser . SP || b == SipParser . HTAB || b == SipParser . CR || b == SipParser . LF ) { buffer . readByte ( ) ; } else { start = buffer . getReaderIndex ( ) ; return St...
While in the INIT state we are just consuming any empty space before heading off to start parsing the initial line
144
22
38,370
private final State onInitialLine ( final Buffer buffer ) { try { buffer . markReaderIndex ( ) ; final Buffer part1 = buffer . readUntilSafe ( config . getMaxAllowedInitialLineSize ( ) , SipParser . SP ) ; final Buffer part2 = buffer . readUntilSafe ( config . getMaxAllowedInitialLineSize ( ) , SipParser . SP ) ; final...
Since it is quite uncommon to not have enough data on the line to read the entire first line we are taking the simple approach of just resetting the entire effort and we ll retry later . This of course means that in the worst case scenario we will actually iterate over data we have already seen before . However seemed ...
199
83
38,371
private final State onCheckEndHeaderSection ( final Buffer buffer ) { // can't tell. We need two bytes at least to check if there is // more headers or not if ( buffer . getReadableBytes ( ) < 2 ) { return State . CHECK_FOR_END_OF_HEADER_SECTION ; } // ok, so there was a CRLF so we are going to fetch the payload // if ...
Every time we have parsed a header we need to check if there are more headers or if we have reached the end of the section and as such there may be a body we need to take care of . We know this by checking if there is a CRLF up next or not .
136
58
38,372
private final State onPayload ( final Buffer buffer ) { if ( contentLength == 0 ) { return State . DONE ; } if ( buffer . getReadableBytes ( ) >= contentLength ) { try { payload = buffer . readBytes ( contentLength ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Unable to read from stream due to IOE...
We may or may not have a payload which depends on whether there is a Content - length header available or not . If yes then we will just slice out that entire thing once we have enough readable bytes in the buffer .
103
44
38,373
private java . nio . ByteBuffer getWritingRow ( ) { final int row = this . writerIndex / this . localCapacity ; if ( row >= this . storage . size ( ) ) { final java . nio . ByteBuffer buf = java . nio . ByteBuffer . allocate ( this . localCapacity ) ; this . storage . add ( buf ) ; return buf ; } return this . storage ...
Get which row we currently are working with for writing
93
10
38,374
private java . nio . ByteBuffer getReadingRow ( ) { final int row = this . readerIndex / this . localCapacity ; return this . storage . get ( row ) ; }
Get which row we currently are working with for reading
40
10
38,375
@ Override public boolean accept ( final Buffer data ) throws IOException { // a RTP packet has at least 12 bytes. Check that if ( data . getReadableBytes ( ) < 12 ) { // not enough bytes but see if we actually could // get another 12 bytes by forcing the underlying // implementation to read further ahead data . markRe...
There is no real good test to make sure that the data indeed is an RTP packet . Appendix 2 in RFC3550 describes one way of doing it but you really need a sequence of packets in order to be able to determine if this indeed is a RTP packet or not . The best is to analyze the session negotiation but here we are just looki...
330
81
38,376
@ Override public final void write ( final OutputStream out ) throws IOException { if ( this . nextPacket != null ) { this . nextPacket . write ( out ) ; } else { this . write ( out , this . payload ) ; } }
The write strategy is fairly simple . If we have a nextPacket it means that we have been asked to frame our payload which also means that that payload may have changed and therefore ask the nextPacket to write itself back out to the stream . If there is no nextPacket we can just take the raw payload and write it out as...
55
81
38,377
private short addTrackedHeader ( final short index , final SipHeader header ) { if ( index != - 1 ) { headers . set ( index , header . ensure ( ) ) ; return index ; } return addHeader ( header . ensure ( ) ) ; }
There are several headers that we want to know their position and in that case we use this method to add them since we want to either add them to a particular position or we want to remember which index we added them to .
55
45
38,378
private < T > Consumer < T > chainConsumers ( final Consumer < T > currentConsumer , final Consumer < T > consumer ) { if ( currentConsumer != null ) { return currentConsumer . andThen ( consumer ) ; } return consumer ; }
Helper function to chain consumers together or return the new one if the current consumer isn t set .
51
19
38,379
public EvolutionaryOperator < List < ColouredPolygon > > createEvolutionPipeline ( PolygonImageFactory factory , Dimension canvasSize , Random rng ) { List < EvolutionaryOperator < List < ColouredPolygon >>> operators = new LinkedList < EvolutionaryOperator < List < ColouredPolygon > > > ( ) ; operators . add ( new Lis...
Construct the combination of evolutionary operators that will be used to evolve the polygon - based images .
398
19
38,380
private SwingBackgroundTask < List < String > > createTask ( final Collection < String > cities ) { final TravellingSalesmanStrategy strategy = strategyPanel . getStrategy ( ) ; return new SwingBackgroundTask < List < String > > ( ) { private long elapsedTime = 0 ; @ Override protected List < String > performTask ( ) {...
Helper method to create a background task for running the travelling salesman algorithm .
187
14
38,381
private String createResultString ( String strategyDescription , List < String > shortestRoute , double distance , long elapsedTime ) { StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( ' ' ) ; buffer . append ( strategyDescription ) ; buffer . append ( "]\n" ) ; buffer . append ( "ROUTE: " ) ; for ( Str...
Helper method for formatting a result as a string for display .
216
12
38,382
@ Override public void setEnabled ( boolean b ) { itineraryPanel . setEnabled ( b ) ; strategyPanel . setEnabled ( b ) ; executionPanel . setEnabled ( b ) ; super . setEnabled ( b ) ; }
Toggles whether the controls are enabled for input or not .
49
12
38,383
public double getFitness ( String candidate , List < ? extends String > population ) { int errors = 0 ; for ( int i = 0 ; i < candidate . length ( ) ; i ++ ) { if ( candidate . charAt ( i ) != targetString . charAt ( i ) ) { ++ errors ; } } return errors ; }
Assigns one penalty point for every character in the candidate string that differs from the corresponding position in the target string .
71
24
38,384
public List < Node > apply ( List < Node > selectedCandidates , Random rng ) { List < Node > evolved = new ArrayList < Node > ( selectedCandidates . size ( ) ) ; for ( Node node : selectedCandidates ) { evolved . add ( probability . nextEvent ( rng ) ? node . simplify ( ) : node ) ; } return evolved ; }
Simplify the expressions represented by the candidates . Each expression is simplified according to the configured probability .
79
20
38,385
public < S > List < S > select ( List < EvaluatedCandidate < S > > population , boolean naturalFitnessScores , int selectionSize , Random rng ) { List < S > selection = new ArrayList < S > ( selectionSize ) ; double ratio = selectionRatio . nextValue ( ) ; assert ratio < 1 && ratio > 0 : "Selection ratio out-of-range: ...
Selects the fittest candidates . If the selectionRatio results in fewer selected candidates than required then these candidates are selected multiple times to make up the shortfall .
198
32
38,386
protected void doReplacement ( List < EvaluatedCandidate < T > > existingPopulation , List < EvaluatedCandidate < T > > newCandidates , int eliteCount , Random rng ) { assert newCandidates . size ( ) < existingPopulation . size ( ) - eliteCount : "Too many new candidates for replacement." ; // If this is strictly stead...
Add the offspring to the population removing the same number of existing individuals to make space for them . This method randomly chooses which individuals should be replaced but it can be over - ridden in sub - classes if alternative behaviour is required .
275
45
38,387
public Biomorph generateRandomCandidate ( Random rng ) { int [ ] genes = new int [ Biomorph . GENE_COUNT ] ; for ( int i = 0 ; i < Biomorph . GENE_COUNT - 1 ; i ++ ) { // First 8 genes have values between -5 and 5. genes [ i ] = rng . nextInt ( 11 ) - 5 ; } // Last genes ha a value between 1 and 7. genes [ Biomorph . L...
Generates a random biomorph by providing a random value for each gene .
139
15
38,388
public static void main ( String [ ] args ) { String target = args . length == 0 ? "HELLO WORLD" : convertArgs ( args ) ; String result = evolveString ( target ) ; System . out . println ( "Evolution result: " + result ) ; }
Entry point for the sample application . Any data specified on the command line is considered to be the target String . If no target is specified a default of HELLOW WORLD is used instead .
59
37
38,389
private static String convertArgs ( String [ ] args ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { result . append ( args [ i ] ) ; if ( i < args . length - 1 ) { result . append ( ' ' ) ; } } return result . toString ( ) . toUpperCase ( ) ; }
Converts an arguments array into a single String of words separated by spaces .
86
15
38,390
public List < Biomorph > apply ( List < Biomorph > selectedCandidates , Random rng ) { List < Biomorph > mutatedPopulation = new ArrayList < Biomorph > ( selectedCandidates . size ( ) ) ; for ( Biomorph biomorph : selectedCandidates ) { mutatedPopulation . add ( mutateBiomorph ( biomorph , rng ) ) ; } return mutatedPop...
Randomly mutate each selected candidate .
83
8
38,391
private Biomorph mutateBiomorph ( Biomorph biomorph , Random rng ) { int [ ] genes = biomorph . getGenotype ( ) ; assert genes . length == Biomorph . GENE_COUNT : "Biomorphs must have " + Biomorph . GENE_COUNT + " genes." ; for ( int i = 0 ; i < Biomorph . GENE_COUNT - 1 ; i ++ ) { if ( mutationProbability . nextEvent ...
Mutates a single biomorph .
353
7
38,392
private Node makeNode ( Random rng , int maxDepth ) { if ( functionProbability . nextEvent ( rng ) && maxDepth > 1 ) { // Max depth for sub-trees is one less than max depth for this node. int depth = maxDepth - 1 ; switch ( rng . nextInt ( 5 ) ) { case 0 : return new Addition ( makeNode ( rng , depth ) , makeNode ( rng...
Recursively constructs a tree of Nodes up to the specified maximum depth .
272
16
38,393
public List < List < T > > apply ( List < List < T > > selectedCandidates , Random rng ) { List < List < T >> output = new ArrayList < List < T > > ( selectedCandidates . size ( ) ) ; for ( List < T > item : selectedCandidates ) { output . add ( delegate . apply ( item , rng ) ) ; } return output ; }
Applies the configured operator to each list candidate operating on the elements that make up a candidate rather than on the list of candidates . candidates and returns the results .
86
32
38,394
public List < Biomorph > apply ( List < Biomorph > selectedCandidates , Random rng ) { List < Biomorph > mutatedPopulation = new ArrayList < Biomorph > ( selectedCandidates . size ( ) ) ; int mutatedGene = 0 ; int mutation = 1 ; for ( Biomorph b : selectedCandidates ) { int [ ] genes = b . getGenotype ( ) ; mutation *=...
Mutate a population of biomorphs non - randomly ensuring that each selected candidate is mutated differently .
284
20
38,395
private Color mutateColour ( Color colour , Random rng ) { if ( mutationProbability . nextValue ( ) . nextEvent ( rng ) ) { return new Color ( mutateColourComponent ( colour . getRed ( ) ) , mutateColourComponent ( colour . getGreen ( ) ) , mutateColourComponent ( colour . getBlue ( ) ) , mutateColourComponent ( colour...
Mutate the specified colour .
104
6
38,396
public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable , nameGenerator . nextID ( ) ) ; thread . setPriority ( priority ) ; thread . setDaemon ( daemon ) ; thread . setUncaughtExceptionHandler ( uncaughtExceptionHandler ) ; return thread ; }
Creates a new thread configured according to this factory s parameters .
70
13
38,397
public List < T > apply ( List < T > selectedCandidates , Random rng ) { List < T > output = new ArrayList < T > ( selectedCandidates . size ( ) ) ; for ( T candidate : selectedCandidates ) { output . add ( replacementProbability . nextValue ( ) . nextEvent ( rng ) ? factory . generateRandomCandidate ( rng ) : candidat...
Randomly replace zero or more of the selected candidates with new independent individuals that are randomly created .
92
19
38,398
public void paintBorder ( Component component , Graphics graphics , int x , int y , int width , int height ) { if ( top ) { graphics . fillRect ( x , y , width , thickness ) ; } if ( bottom ) { graphics . fillRect ( x , y + height - thickness , width , thickness ) ; } if ( left ) { graphics . fillRect ( x , y , thickne...
Renders borders for the specified component based on the configuration of this border object .
113
16
38,399
private void updateDomainAxisRange ( ) { int count = dataSet . getSeries ( 0 ) . getItemCount ( ) ; if ( count < SHOW_FIXED_GENERATIONS ) { domainAxis . setRangeWithMargins ( 0 , SHOW_FIXED_GENERATIONS ) ; } else if ( allDataButton . isSelected ( ) ) { domainAxis . setRangeWithMargins ( 0 , Math . max ( SHOW_FIXED_GENE...
If all data is selected set the range of the domain axis to include all values . Otherwise set it to show the most recent 200 generations .
137
28