idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
156,600
|
public static ZProxy newProxy ( ZContext ctx , String name , Proxy sockets , String motdelafin , Object ... args ) { return new ZProxy ( ctx , name , sockets , new ZmqPump ( ) , motdelafin , args ) ; }
|
Creates a new low - level proxy for better performances .
| 59
| 12
|
156,601
|
public String restart ( ZMsg hot ) { ZMsg msg = new ZMsg ( ) ; msg . add ( RESTART ) ; final boolean cold = hot == null ; if ( cold ) { msg . add ( Boolean . toString ( false ) ) ; } else { msg . add ( Boolean . toString ( true ) ) ; msg . append ( hot ) ; } String status = EXITED ; if ( agent . send ( msg ) ) { status = status ( false ) ; } return status ; }
|
Restarts the proxy . Stays alive .
| 105
| 9
|
156,602
|
public String exit ( ) { agent . send ( EXIT ) ; exit . awaitSilent ( ) ; agent . close ( ) ; return EXITED ; }
|
Stops the proxy and exits . The call is synchronous .
| 33
| 13
|
156,603
|
public String status ( boolean sync ) { if ( exit . isExited ( ) ) { return EXITED ; } try { String status = recvStatus ( ) ; if ( agent . send ( STATUS ) && sync ) { // wait for the response to emulate sync status = recvStatus ( ) ; // AND refill a status if ( EXITED . equals ( status ) || ! agent . send ( STATUS ) ) { return EXITED ; } } return status ; } catch ( ZMQException e ) { return EXITED ; } }
|
Inquires for the status of the proxy .
| 113
| 10
|
156,604
|
private String recvStatus ( ) { if ( ! agent . sign ( ) ) { return EXITED ; } // receive the status response final ZMsg msg = agent . recv ( ) ; if ( msg == null ) { return EXITED ; } String status = msg . popString ( ) ; msg . destroy ( ) ; return status ; }
|
receives the last known state of the proxy
| 72
| 10
|
156,605
|
public boolean containsPublicKey ( byte [ ] publicKey ) { Utils . checkArgument ( publicKey . length == 32 , "publickey needs to have a size of 32 bytes. got only " + publicKey . length ) ; return containsPublicKey ( ZMQ . Curve . z85Encode ( publicKey ) ) ; }
|
Check if a public key is in the certificate store .
| 70
| 11
|
156,606
|
public boolean containsPublicKey ( String publicKey ) { Utils . checkArgument ( publicKey . length ( ) == 40 , "z85 publickeys should have a length of 40 bytes but got " + publicKey . length ( ) ) ; reloadIfNecessary ( ) ; return publicKeys . containsKey ( publicKey ) ; }
|
check if a z85 - based public key is in the certificate store . This method will scan the folder for changes on every call
| 72
| 26
|
156,607
|
boolean checkForChanges ( ) { // initialize with last checked files final Map < File , byte [ ] > presents = new HashMap <> ( fingerprints ) ; boolean modified = traverseDirectory ( location , new IFileVisitor ( ) { @ Override public boolean visitFile ( File file ) { return modified ( presents . remove ( file ) , file ) ; } @ Override public boolean visitDir ( File dir ) { return modified ( presents . remove ( dir ) , dir ) ; } } ) ; // if some files remain, that means they have been deleted since last scan return modified || ! presents . isEmpty ( ) ; }
|
Check if files in the certificate folders have been added or removed .
| 132
| 13
|
156,608
|
public ZAuth configureCurve ( String location ) { Objects . requireNonNull ( location , "Location has to be supplied" ) ; return send ( Mechanism . CURVE . name ( ) , location ) ; }
|
Configure CURVE authentication
| 46
| 6
|
156,609
|
public ZapReply nextReply ( boolean wait ) { if ( ! repliesEnabled ) { System . out . println ( "ZAuth: replies are disabled. Please use replies(true);" ) ; return null ; } return ZapReply . recv ( replies , wait ) ; }
|
Retrieves the next ZAP reply .
| 57
| 9
|
156,610
|
public static int send ( SocketBase s , String str , int flags ) { byte [ ] data = str . getBytes ( CHARSET ) ; return send ( s , data , data . length , flags ) ; }
|
Sending functions .
| 46
| 4
|
156,611
|
public static Msg recv ( SocketBase s , int flags ) { checkSocket ( s ) ; Msg msg = recvMsg ( s , flags ) ; if ( msg == null ) { return null ; } // At the moment an oversized message is silently truncated. // TODO: Build in a notification mechanism to report the overflows. //int to_copy = nbytes < len_ ? nbytes : len_; return msg ; }
|
Receiving functions .
| 94
| 5
|
156,612
|
public static String getMessageMetadata ( Msg msg , String property ) { String data = null ; Metadata metadata = msg . getMetadata ( ) ; if ( metadata != null ) { data = metadata . get ( property ) ; } return data ; }
|
Get message metadata string
| 54
| 4
|
156,613
|
public static boolean proxy ( SocketBase frontend , SocketBase backend , SocketBase capture ) { Utils . checkArgument ( frontend != null , "Frontend socket has to be present for proxy" ) ; Utils . checkArgument ( backend != null , "Backend socket has to be present for proxy" ) ; return Proxy . proxy ( frontend , backend , capture , null ) ; }
|
The proxy functionality
| 84
| 3
|
156,614
|
public final ZMonitor start ( ) { if ( started ) { System . out . println ( "ZMonitor: Unable to start while already started." ) ; return this ; } agent . send ( START ) ; agent . recv ( ) ; started = true ; return this ; }
|
Starts the monitoring . Event types have to be added before the start or they will take no effect .
| 58
| 21
|
156,615
|
public final ZMonitor verbose ( boolean verbose ) { if ( started ) { System . out . println ( "ZMonitor: Unable to change verbosity while already started." ) ; return this ; } agent . send ( VERBOSE , true ) ; agent . send ( Boolean . toString ( verbose ) ) ; agent . recv ( ) ; return this ; }
|
Sets verbosity of the monitor .
| 78
| 8
|
156,616
|
public final ZMonitor add ( Event ... events ) { if ( started ) { System . out . println ( "ZMonitor: Unable to add events while already started." ) ; return this ; } ZMsg msg = new ZMsg ( ) ; msg . add ( ADD_EVENTS ) ; for ( Event evt : events ) { msg . add ( evt . name ( ) ) ; } agent . send ( msg ) ; agent . recv ( ) ; return this ; }
|
Adds event types to monitor .
| 100
| 6
|
156,617
|
public final ZEvent nextEvent ( boolean wait ) { if ( ! started ) { System . out . println ( "ZMonitor: Start before getting events." ) ; return null ; } ZMsg msg = agent . recv ( wait ) ; if ( msg == null ) { return null ; } return new ZEvent ( msg ) ; }
|
Gets the next event blocking for it until available if requested .
| 70
| 13
|
156,618
|
public boolean sendFrame ( ZFrame frame , int flags ) { final byte [ ] data = frame . getData ( ) ; final Msg msg = new Msg ( data ) ; if ( socketBase . send ( msg , flags ) ) { return true ; } mayRaise ( ) ; return false ; }
|
Send a frame
| 65
| 3
|
156,619
|
public static Pipe [ ] pair ( ZObject [ ] parents , int [ ] hwms , boolean [ ] conflates ) { Pipe [ ] pipes = new Pipe [ 2 ] ; // Creates two pipe objects. These objects are connected by two ypipes, // each to pass messages in one direction. YPipeBase < Msg > upipe1 = conflates [ 0 ] ? new YPipeConflate <> ( ) : new YPipe < Msg > ( Config . MESSAGE_PIPE_GRANULARITY . getValue ( ) ) ; YPipeBase < Msg > upipe2 = conflates [ 1 ] ? new YPipeConflate <> ( ) : new YPipe < Msg > ( Config . MESSAGE_PIPE_GRANULARITY . getValue ( ) ) ; pipes [ 0 ] = new Pipe ( parents [ 0 ] , upipe1 , upipe2 , hwms [ 1 ] , hwms [ 0 ] , conflates [ 0 ] ) ; pipes [ 1 ] = new Pipe ( parents [ 1 ] , upipe2 , upipe1 , hwms [ 0 ] , hwms [ 1 ] , conflates [ 1 ] ) ; pipes [ 0 ] . setPeer ( pipes [ 1 ] ) ; pipes [ 1 ] . setPeer ( pipes [ 0 ] ) ; return pipes ; }
|
terminates straight away .
| 309
| 5
|
156,620
|
public boolean checkRead ( ) { if ( ! inActive ) { return false ; } if ( state != State . ACTIVE && state != State . WAITING_FOR_DELIMITER ) { return false ; } // Check if there's an item in the pipe. if ( ! inpipe . checkRead ( ) ) { inActive = false ; return false ; } // If the next item in the pipe is message delimiter, // initiate termination process. if ( isDelimiter ( inpipe . probe ( ) ) ) { Msg msg = inpipe . read ( ) ; assert ( msg != null ) ; processDelimiter ( ) ; return false ; } return true ; }
|
Returns true if there is at least one message to read in the pipe .
| 147
| 15
|
156,621
|
public Msg read ( ) { if ( ! inActive ) { return null ; } if ( state != State . ACTIVE && state != State . WAITING_FOR_DELIMITER ) { return null ; } while ( true ) { Msg msg = inpipe . read ( ) ; if ( msg == null ) { inActive = false ; return null ; } // If this is a credential, save a copy and receive next message. if ( msg . isCredential ( ) ) { credential = Blob . createBlob ( msg ) ; continue ; } // If delimiter was read, start termination process of the pipe. if ( msg . isDelimiter ( ) ) { processDelimiter ( ) ; return null ; } if ( ! msg . hasMore ( ) && ! msg . isIdentity ( ) ) { msgsRead ++ ; } if ( lwm > 0 && msgsRead % lwm == 0 ) { sendActivateWrite ( peer , msgsRead ) ; } return msg ; } }
|
Reads a message to the underlying pipe .
| 220
| 9
|
156,622
|
public boolean checkWrite ( ) { if ( ! outActive || state != State . ACTIVE ) { return false ; } // TODO DIFF V4 small change, it is done like this in 4.2.2 boolean full = ! checkHwm ( ) ; if ( full ) { outActive = false ; return false ; } return true ; }
|
the message would cause high watermark the function returns false .
| 74
| 12
|
156,623
|
public boolean write ( Msg msg ) { if ( ! checkWrite ( ) ) { return false ; } boolean more = msg . hasMore ( ) ; boolean identity = msg . isIdentity ( ) ; outpipe . write ( msg , more ) ; if ( ! more && ! identity ) { msgsWritten ++ ; } return true ; }
|
message cannot be written because high watermark was reached .
| 72
| 11
|
156,624
|
public void rollback ( ) { // Remove incomplete message from the outbound pipe. Msg msg ; if ( outpipe != null ) { while ( ( msg = outpipe . unwrite ( ) ) != null ) { assert ( msg . hasMore ( ) ) ; } } }
|
Remove unfinished parts of the outbound message from the pipe .
| 59
| 12
|
156,625
|
public void flush ( ) { // The peer does not exist anymore at this point. if ( state == State . TERM_ACK_SENT ) { return ; } if ( outpipe != null && ! outpipe . flush ( ) ) { sendActivateRead ( peer ) ; } }
|
Flush the messages downstream .
| 61
| 6
|
156,626
|
public void terminate ( boolean delay ) { // Overload the value specified at pipe creation. this . delay = delay ; // If terminate was already called, we can ignore the duplicit invocation. if ( state == State . TERM_REQ_SENT_1 || state == State . TERM_REQ_SENT_2 ) { return ; } // If the pipe is in the final phase of async termination, it's going to // closed anyway. No need to do anything special here. else if ( state == State . TERM_ACK_SENT ) { return ; } // The simple sync termination case. Ask the peer to terminate and wait // for the ack. else if ( state == State . ACTIVE ) { sendPipeTerm ( peer ) ; state = State . TERM_REQ_SENT_1 ; } // There are still pending messages available, but the user calls // 'terminate'. We can act as if all the pending messages were read. else if ( state == State . WAITING_FOR_DELIMITER && ! this . delay ) { outpipe = null ; sendPipeTermAck ( peer ) ; state = State . TERM_ACK_SENT ; } // If there are pending messages still available, do nothing. else if ( state == State . WAITING_FOR_DELIMITER ) { // do nothing } // We've already got delimiter, but not term command yet. We can ignore // the delimiter and ack synchronously terminate as if we were in // active state. else if ( state == State . DELIMITER_RECEIVED ) { sendPipeTerm ( peer ) ; state = State . TERM_REQ_SENT_1 ; } // There are no other states. else { assert ( false ) ; } // Stop outbound flow of messages. outActive = false ; if ( outpipe != null ) { // Drop any unfinished outbound messages. rollback ( ) ; // Write the delimiter into the pipe. Note that watermarks are not // checked; thus the delimiter can be written even when the pipe is full. Msg msg = new Msg ( ) ; msg . initDelimiter ( ) ; outpipe . write ( msg , false ) ; flush ( ) ; } }
|
before actual shutdown .
| 490
| 4
|
156,627
|
private void processDelimiter ( ) { assert ( state == State . ACTIVE || state == State . WAITING_FOR_DELIMITER ) ; if ( state == State . ACTIVE ) { state = State . DELIMITER_RECEIVED ; } else { outpipe = null ; sendPipeTermAck ( peer ) ; state = State . TERM_ACK_SENT ; } }
|
Handler for delimiter read from the pipe .
| 91
| 9
|
156,628
|
public void hiccup ( ) { // If termination is already under way do nothing. if ( state != State . ACTIVE ) { return ; } // We'll drop the pointer to the inpipe. From now on, the peer is // responsible for deallocating it. inpipe = null ; // Create new inpipe. if ( conflate ) { inpipe = new YPipeConflate <> ( ) ; } else { inpipe = new YPipe <> ( Config . MESSAGE_PIPE_GRANULARITY . getValue ( ) ) ; } inActive = true ; // Notify the peer about the hiccup. sendHiccup ( peer , inpipe ) ; }
|
in the peer .
| 153
| 4
|
156,629
|
protected boolean rollback ( ) { if ( currentOut != null ) { currentOut . rollback ( ) ; currentOut = null ; moreOut = false ; } return true ; }
|
Rollback any message parts that were sent but not yet flushed .
| 38
| 13
|
156,630
|
@ Override public final int encode ( ValueReference < ByteBuffer > data , int size ) { int bufferSize = size ; ByteBuffer buf = data . get ( ) ; if ( buf == null ) { buf = this . buffer ; bufferSize = this . bufferSize ; buffer . clear ( ) ; } if ( inProgress == null ) { return 0 ; } int pos = 0 ; buf . limit ( buf . capacity ( ) ) ; while ( pos < bufferSize ) { // If there are no more data to return, run the state machine. // If there are still no data, return what we already have // in the buffer. if ( toWrite == 0 ) { if ( newMsgFlag ) { inProgress = null ; break ; } next ( ) ; } // If there are no data in the buffer yet and we are able to // fill whole buffer in a single go, let's use zero-copy. // There's no disadvantage to it as we cannot stuck multiple // messages into the buffer anyway. Note that subsequent // write(s) are non-blocking, thus each single write writes // at most SO_SNDBUF bytes at once not depending on how large // is the chunk returned from here. // As a consequence, large messages being sent won't block // other engines running in the same I/O thread for excessive // amounts of time. if ( pos == 0 && data . get ( ) == null && toWrite >= bufferSize ) { writeBuf . limit ( writeBuf . capacity ( ) ) ; data . set ( writeBuf ) ; pos = toWrite ; writeBuf = null ; toWrite = 0 ; return pos ; } // Copy data to the buffer. If the buffer is full, return. int toCopy = Math . min ( toWrite , bufferSize - pos ) ; int limit = writeBuf . limit ( ) ; writeBuf . limit ( Math . min ( writeBuf . capacity ( ) , writeBuf . position ( ) + toCopy ) ) ; int current = buf . position ( ) ; buf . put ( writeBuf ) ; toCopy = buf . position ( ) - current ; writeBuf . limit ( limit ) ; pos += toCopy ; toWrite -= toCopy ; } data . set ( buf ) ; return pos ; }
|
is NULL ) encoder will provide buffer of its own .
| 484
| 12
|
156,631
|
private void nextStep ( byte [ ] buf , int toWrite , Runnable next , boolean newMsgFlag ) { if ( buf != null ) { writeBuf = ByteBuffer . wrap ( buf ) ; writeBuf . limit ( toWrite ) ; } else { writeBuf = null ; } this . toWrite = toWrite ; this . next = next ; this . newMsgFlag = newMsgFlag ; }
|
to the buffer and schedule next state machine action .
| 89
| 10
|
156,632
|
public void addTimer ( long timeout , IPollEvents sink , int id ) { assert ( Thread . currentThread ( ) == worker ) ; final long expiration = clock ( ) + timeout ; TimerInfo info = new TimerInfo ( sink , id ) ; timers . insert ( expiration , info ) ; changed = true ; }
|
argument set to id_ .
| 68
| 6
|
156,633
|
public void cancelTimer ( IPollEvents sink , int id ) { assert ( Thread . currentThread ( ) == worker ) ; TimerInfo copy = new TimerInfo ( sink , id ) ; // Complexity of this operation is O(n). We assume it is rarely used. TimerInfo timerInfo = timers . find ( copy ) ; if ( timerInfo != null ) { // let's defer the removal during the loop timerInfo . cancelled = true ; } }
|
Cancel the timer created by sink_ object with ID equal to id_ .
| 98
| 16
|
156,634
|
protected long executeTimers ( ) { assert ( Thread . currentThread ( ) == worker ) ; changed = false ; // Fast track. if ( timers . isEmpty ( ) ) { return 0L ; } // Get the current time. long current = clock ( ) ; // Execute the timers that are already due. for ( Entry < TimerInfo , Long > entry : timers . entries ( ) ) { final TimerInfo timerInfo = entry . getKey ( ) ; if ( timerInfo . cancelled ) { timers . remove ( entry . getValue ( ) , timerInfo ) ; continue ; } // If we have to wait to execute the item, same will be true about // all the following items (multimap is sorted). Thus we can stop // checking the subsequent timers and return the time to wait for // the next timer (at least 1ms). final Long key = entry . getValue ( ) ; if ( key > current ) { return key - current ; } // Remove it from the list of active timers. timers . remove ( key , timerInfo ) ; // Trigger the timer. timerInfo . sink . timerEvent ( timerInfo . id ) ; } // Remove empty list object for ( Entry < TimerInfo , Long > entry : timers . entries ( ) ) { final Long key = entry . getValue ( ) ; if ( ! timers . hasValues ( key ) ) { timers . remove ( key ) ; } } if ( changed ) { return executeTimers ( ) ; } // There are no more timers. return 0L ; }
|
to wait to match the next timer or 0 meaning no timers .
| 324
| 13
|
156,635
|
@ Override protected void processTerm ( int linger ) { // Double termination should never happen. assert ( ! terminating ) ; // Send termination request to all owned objects. for ( Own it : owned ) { sendTerm ( it , linger ) ; } registerTermAcks ( owned . size ( ) ) ; owned . clear ( ) ; // Start termination process and check whether by chance we cannot // terminate immediately. terminating = true ; checkTermAcks ( ) ; }
|
steps to the beginning of the termination process .
| 96
| 9
|
156,636
|
public boolean rm ( Pipe pipe , IMtrieHandler func , XPub pub ) { assert ( pipe != null ) ; assert ( func != null ) ; return rmHelper ( pipe , new byte [ 0 ] , 0 , 0 , func , pub ) ; }
|
supplied callback function .
| 54
| 5
|
156,637
|
public boolean rm ( Msg msg , Pipe pipe ) { assert ( msg != null ) ; assert ( pipe != null ) ; return rmHelper ( msg , 1 , msg . size ( ) - 1 , pipe ) ; }
|
actually removed rather than de - duplicated .
| 46
| 9
|
156,638
|
public void match ( ByteBuffer data , int size , IMtrieHandler func , XPub pub ) { assert ( data != null ) ; assert ( func != null ) ; assert ( pub != null ) ; Mtrie current = this ; int idx = 0 ; while ( true ) { // Signal the pipes attached to this node. if ( current . pipes != null ) { for ( Pipe it : current . pipes ) { func . invoke ( it , null , 0 , pub ) ; } } // If we are at the end of the message, there's nothing more to match. if ( size == 0 ) { break ; } // If there are no subnodes in the trie, return. if ( current . count == 0 ) { break ; } byte c = data . get ( idx ) ; // If there's one subnode (optimisation). if ( current . count == 1 ) { if ( c != current . min ) { break ; } current = current . next [ 0 ] ; idx ++ ; size -- ; continue ; } // If there are multiple subnodes. if ( c < current . min || c >= current . min + current . count ) { break ; } if ( current . next [ c - current . min ] == null ) { break ; } current = current . next [ c - current . min ] ; idx ++ ; size -- ; } }
|
Signal all the matching pipes .
| 292
| 7
|
156,639
|
private void close ( ) { assert ( fd != null ) ; try { fd . close ( ) ; socket . eventClosed ( endpoint , fd ) ; } catch ( IOException e ) { socket . eventCloseFailed ( endpoint , ZError . exccode ( e ) ) ; } fd = null ; }
|
Close the listening socket .
| 70
| 5
|
156,640
|
private SocketChannel accept ( ) throws IOException { // The situation where connection cannot be accepted due to insufficient // resources is considered valid and treated by ignoring the connection. // Accept one connection and deal with different failure modes. assert ( fd != null ) ; SocketChannel sock = fd . accept ( ) ; if ( ! options . tcpAcceptFilters . isEmpty ( ) ) { boolean matched = false ; for ( TcpAddress . TcpAddressMask am : options . tcpAcceptFilters ) { if ( am . matchAddress ( address . address ( ) ) ) { matched = true ; break ; } } if ( ! matched ) { try { sock . close ( ) ; } catch ( IOException e ) { } return null ; } } if ( options . tos != 0 ) { TcpUtils . setIpTypeOfService ( sock , options . tos ) ; } // Set the socket buffer limits for the underlying socket. if ( options . sndbuf != 0 ) { TcpUtils . setTcpSendBuffer ( sock , options . sndbuf ) ; } if ( options . rcvbuf != 0 ) { TcpUtils . setTcpReceiveBuffer ( sock , options . rcvbuf ) ; } if ( ! isWindows ) { TcpUtils . setReuseAddress ( sock , true ) ; } return sock ; }
|
or was denied because of accept filters .
| 289
| 8
|
156,641
|
public void attach ( Pipe pipe ) { // If we are in the middle of sending a message, we'll add new pipe // into the list of eligible pipes. Otherwise we add it to the list // of active pipes. if ( more ) { pipes . add ( pipe ) ; Collections . swap ( pipes , eligible , pipes . size ( ) - 1 ) ; eligible ++ ; } else { pipes . add ( pipe ) ; Collections . swap ( pipes , active , pipes . size ( ) - 1 ) ; active ++ ; eligible ++ ; } }
|
Adds the pipe to the distributor object .
| 112
| 8
|
156,642
|
public void match ( Pipe pipe ) { int idx = pipes . indexOf ( pipe ) ; // If pipe is already matching do nothing. if ( idx < matching ) { return ; } // If the pipe isn't eligible, ignore it. if ( idx >= eligible ) { return ; } // Mark the pipe as matching. Collections . swap ( pipes , idx , matching ) ; matching ++ ; }
|
will send message also to this pipe .
| 85
| 8
|
156,643
|
public void terminated ( Pipe pipe ) { // Remove the pipe from the list; adjust number of matching, active and/or // eligible pipes accordingly. if ( pipes . indexOf ( pipe ) < matching ) { Collections . swap ( pipes , pipes . indexOf ( pipe ) , matching - 1 ) ; matching -- ; } if ( pipes . indexOf ( pipe ) < active ) { Collections . swap ( pipes , pipes . indexOf ( pipe ) , active - 1 ) ; active -- ; } if ( pipes . indexOf ( pipe ) < eligible ) { Collections . swap ( pipes , pipes . indexOf ( pipe ) , eligible - 1 ) ; eligible -- ; } pipes . remove ( pipe ) ; }
|
Removes the pipe from the distributor object .
| 146
| 9
|
156,644
|
public void activated ( Pipe pipe ) { // Move the pipe from passive to eligible state. Collections . swap ( pipes , pipes . indexOf ( pipe ) , eligible ) ; eligible ++ ; // If there's no message being sent at the moment, move it to // the active state. if ( ! more ) { Collections . swap ( pipes , eligible - 1 , active ) ; active ++ ; } }
|
Activates pipe that have previously reached high watermark .
| 82
| 11
|
156,645
|
public boolean sendToMatching ( Msg msg ) { // Is this end of a multipart message? boolean msgMore = msg . hasMore ( ) ; // Push the message to matching pipes. distribute ( msg ) ; // If mutlipart message is fully sent, activate all the eligible pipes. if ( ! msgMore ) { active = eligible ; } more = msgMore ; return true ; }
|
Send the message to the matching outbound pipes .
| 83
| 10
|
156,646
|
private void distribute ( Msg msg ) { // If there are no matching pipes available, simply drop the message. if ( matching == 0 ) { return ; } // TODO isVsm // Push copy of the message to each matching pipe. for ( int idx = 0 ; idx < matching ; ++ idx ) { if ( ! write ( pipes . get ( idx ) , msg ) ) { -- idx ; // Retry last write because index will have been swapped } } }
|
Put the message to all active pipes .
| 103
| 8
|
156,647
|
private boolean write ( Pipe pipe , Msg msg ) { if ( ! pipe . write ( msg ) ) { Collections . swap ( pipes , pipes . indexOf ( pipe ) , matching - 1 ) ; matching -- ; Collections . swap ( pipes , pipes . indexOf ( pipe ) , active - 1 ) ; active -- ; Collections . swap ( pipes , active , eligible - 1 ) ; eligible -- ; return false ; } if ( ! msg . hasMore ( ) ) { pipe . flush ( ) ; } return true ; }
|
fails . In such a case false is returned .
| 109
| 11
|
156,648
|
public final boolean register ( final SelectableChannel channel , final EventsHandler handler ) { return register ( channel , handler , IN | OUT | ERR ) ; }
|
Registers a SelectableChannel for polling on all events .
| 33
| 12
|
156,649
|
public final boolean unregister ( final Object socketOrChannel ) { if ( socketOrChannel == null ) { return false ; } CompositePollItem items = this . items . remove ( socketOrChannel ) ; boolean rc = items != null ; if ( rc ) { all . remove ( items ) ; } return rc ; }
|
Unregister a Socket or SelectableChannel for polling on the specified events .
| 66
| 15
|
156,650
|
protected int poll ( final long timeout , final boolean dispatchEvents ) { // get all the raw items final Set < PollItem > pollItems = new HashSet <> ( ) ; for ( CompositePollItem it : all ) { pollItems . add ( it . item ( ) ) ; } // polling time final int rc = poll ( selector , timeout , pollItems ) ; if ( ! dispatchEvents ) { // raw result return rc ; } if ( dispatch ( all , pollItems . size ( ) ) ) { // returns event counts after dispatch if everything went fine return rc ; } // error in dispatching return - 1 ; }
|
Issue a poll call using the specified timeout value .
| 130
| 10
|
156,651
|
protected int poll ( final Selector selector , final long tout , final Collection < zmq . poll . PollItem > items ) { final int size = items . size ( ) ; return zmq . ZMQ . poll ( selector , items . toArray ( new PollItem [ size ] ) , size , tout ) ; }
|
does the effective polling
| 71
| 4
|
156,652
|
protected boolean dispatch ( final Collection < ? extends ItemHolder > all , int size ) { ItemHolder [ ] array = all . toArray ( new ItemHolder [ all . size ( ) ] ) ; // protected against handlers unregistering during this loop for ( ItemHolder holder : array ) { EventsHandler handler = holder . handler ( ) ; if ( handler == null ) { handler = globalHandler ; } if ( handler == null ) { // no handler, short-circuit continue ; } final PollItem item = holder . item ( ) ; final int events = item . readyOps ( ) ; if ( events <= 0 ) { // no events, short-circuit continue ; } final Socket socket = holder . socket ( ) ; final SelectableChannel channel = holder . item ( ) . getRawSocket ( ) ; if ( socket != null ) { assert ( channel == null ) ; // dispatch on socket if ( ! handler . events ( socket , events ) ) { return false ; } } if ( channel != null ) { // dispatch on channel assert ( socket == null ) ; if ( ! handler . events ( channel , events ) ) { return false ; } } } return true ; }
|
Dispatches the polled events .
| 250
| 7
|
156,653
|
public boolean readable ( final Object socketOrChannel ) { final PollItem it = filter ( socketOrChannel , READABLE ) ; if ( it == null ) { return false ; } return it . isReadable ( ) ; }
|
checks for read event
| 47
| 4
|
156,654
|
public boolean writable ( final Object socketOrChannel ) { final PollItem it = filter ( socketOrChannel , WRITABLE ) ; if ( it == null ) { return false ; } return it . isWritable ( ) ; }
|
checks for write event
| 49
| 4
|
156,655
|
public boolean error ( final Object socketOrChannel ) { final PollItem it = filter ( socketOrChannel , ERR ) ; if ( it == null ) { return false ; } return it . isError ( ) ; }
|
checks for error event
| 46
| 4
|
156,656
|
protected boolean add ( Object socketOrChannel , final ItemHolder holder ) { if ( socketOrChannel == null ) { Socket socket = holder . socket ( ) ; SelectableChannel ch = holder . item ( ) . getRawSocket ( ) ; if ( ch == null ) { // not a channel assert ( socket != null ) ; socketOrChannel = socket ; } else if ( socket == null ) { // not a socket socketOrChannel = ch ; } } assert ( socketOrChannel != null ) ; CompositePollItem aggregate = items . get ( socketOrChannel ) ; if ( aggregate == null ) { aggregate = new CompositePollItem ( socketOrChannel ) ; items . put ( socketOrChannel , aggregate ) ; } final boolean rc = aggregate . holders . add ( holder ) ; if ( rc ) { all . add ( aggregate ) ; } return rc ; }
|
add an item to this poller
| 180
| 7
|
156,657
|
protected Collection < ? extends ItemHolder > items ( ) { for ( CompositePollItem item : all ) { item . handler ( globalHandler ) ; } return all ; }
|
gets all the items of this poller
| 36
| 8
|
156,658
|
protected Iterable < ItemHolder > items ( final Object socketOrChannel ) { final CompositePollItem aggregate = items . get ( socketOrChannel ) ; if ( aggregate == null ) { return Collections . emptySet ( ) ; } return aggregate . holders ; }
|
gets all the items of this poller regarding the given input
| 54
| 12
|
156,659
|
protected PollItem filter ( final Object socketOrChannel , int events ) { if ( socketOrChannel == null ) { return null ; } CompositePollItem item = items . get ( socketOrChannel ) ; if ( item == null ) { return null ; } PollItem pollItem = item . item ( ) ; if ( pollItem == null ) { return null ; } if ( pollItem . hasEvent ( events ) ) { return pollItem ; } return null ; }
|
filters items to get the first one matching the criteria or null if none found
| 97
| 16
|
156,660
|
public String getShortString ( ) { String value = Wire . getShortString ( needle , needle . position ( ) ) ; forward ( value . length ( ) + 1 ) ; return value ; }
|
Get a string from the frame
| 41
| 6
|
156,661
|
public String getLongString ( ) { String value = Wire . getLongString ( needle , needle . position ( ) ) ; forward ( value . length ( ) + 4 ) ; return value ; }
|
Get a long string from the frame
| 41
| 7
|
156,662
|
public void putList ( Collection < String > elements ) { if ( elements == null ) { putNumber1 ( 0 ) ; } else { Utils . checkArgument ( elements . size ( ) < 256 , "Collection has to be smaller than 256 elements" ) ; putNumber1 ( elements . size ( ) ) ; for ( String string : elements ) { putString ( string ) ; } } }
|
Put a collection of strings to the frame
| 84
| 8
|
156,663
|
public void putMap ( Map < String , String > map ) { if ( map == null ) { putNumber1 ( 0 ) ; } else { Utils . checkArgument ( map . size ( ) < 256 , "Map has to be smaller than 256 elements" ) ; putNumber1 ( map . size ( ) ) ; for ( Entry < String , String > entry : map . entrySet ( ) ) { if ( entry . getKey ( ) . contains ( "=" ) ) { throw new IllegalArgumentException ( "Keys cannot contain '=' sign. " + entry ) ; } if ( entry . getValue ( ) . contains ( "=" ) ) { throw new IllegalArgumentException ( "Values cannot contain '=' sign. " + entry ) ; } String val = entry . getKey ( ) + "=" + entry . getValue ( ) ; putString ( val ) ; } } }
|
Put a map of strings to the frame
| 190
| 8
|
156,664
|
public void push ( T val ) { backChunk . values [ backPos ] = val ; backChunk = endChunk ; backPos = endPos ; if ( ++ endPos != size ) { return ; } Chunk < T > sc = spareChunk ; if ( sc != beginChunk ) { spareChunk = spareChunk . next ; endChunk . next = sc ; sc . prev = endChunk ; } else { endChunk . next = new Chunk <> ( size , memoryPtr ) ; memoryPtr += size ; endChunk . next . prev = endChunk ; } endChunk = endChunk . next ; endPos = 0 ; }
|
Adds an element to the back end of the queue .
| 147
| 11
|
156,665
|
public void unpush ( ) { // First, move 'back' one position backwards. if ( backPos > 0 ) { -- backPos ; } else { backPos = size - 1 ; backChunk = backChunk . prev ; } // Now, move 'end' position backwards. Note that obsolete end chunk // is not used as a spare chunk. The analysis shows that doing so // would require free and atomic operation per chunk deallocated // instead of a simple free. if ( endPos > 0 ) { -- endPos ; } else { endPos = size - 1 ; endChunk = endChunk . prev ; endChunk . next = null ; } }
|
unsynchronised thread .
| 142
| 6
|
156,666
|
public T pop ( ) { T val = beginChunk . values [ beginPos ] ; beginChunk . values [ beginPos ] = null ; beginPos ++ ; if ( beginPos == size ) { beginChunk = beginChunk . next ; beginChunk . prev = null ; beginPos = 0 ; } return val ; }
|
Removes an element from the front end of the queue .
| 71
| 12
|
156,667
|
private void rebuild ( ) { pollact = null ; pollSize = pollers . size ( ) ; if ( pollset != null ) { pollset . close ( ) ; } pollset = context . poller ( pollSize ) ; assert ( pollset != null ) ; pollact = new SPoller [ pollSize ] ; int itemNbr = 0 ; for ( SPoller poller : pollers ) { pollset . register ( poller . item ) ; pollact [ itemNbr ] = poller ; itemNbr ++ ; } dirty = false ; }
|
activity on pollers . Returns 0 on success - 1 on failure .
| 119
| 14
|
156,668
|
public int addPoller ( PollItem pollItem , IZLoopHandler handler , Object arg ) { if ( pollItem . getRawSocket ( ) == null && pollItem . getSocket ( ) == null ) { return - 1 ; } SPoller poller = new SPoller ( pollItem , handler , arg ) ; pollers . add ( poller ) ; dirty = true ; if ( verbose ) { System . out . printf ( "I: zloop: register %s poller (%s, %s)\n" , pollItem . getSocket ( ) != null ? pollItem . getSocket ( ) . getType ( ) : "RAW" , pollItem . getSocket ( ) , pollItem . getRawSocket ( ) ) ; } return 0 ; }
|
corresponding handler .
| 162
| 5
|
156,669
|
public int removeTimer ( Object arg ) { Objects . requireNonNull ( arg , "Argument has to be supplied" ) ; // We cannot touch self->timers because we may be executing that // from inside the poll loop. So, we hold the arg on the zombie // list, and process that list when we're done executing timers. zombies . add ( arg ) ; if ( verbose ) { System . out . printf ( "I: zloop: cancel timer\n" ) ; } return 0 ; }
|
Returns 0 on success .
| 108
| 5
|
156,670
|
public ANRWatchDog setANRListener ( ANRListener listener ) { if ( listener == null ) { _anrListener = DEFAULT_ANR_LISTENER ; } else { _anrListener = listener ; } return this ; }
|
Sets an interface for when an ANR is detected . If not set the default behavior is to throw an error and crash the application .
| 55
| 28
|
156,671
|
public ANRWatchDog setANRInterceptor ( ANRInterceptor interceptor ) { if ( interceptor == null ) { _anrInterceptor = DEFAULT_ANR_INTERCEPTOR ; } else { _anrInterceptor = interceptor ; } return this ; }
|
Sets an interface to intercept ANRs before they are reported . If set you can define if given the current duration of the detected ANR and external context it is necessary to report the ANR .
| 60
| 40
|
156,672
|
public ANRWatchDog setInterruptionListener ( InterruptionListener listener ) { if ( listener == null ) { _interruptionListener = DEFAULT_INTERRUPTION_LISTENER ; } else { _interruptionListener = listener ; } return this ; }
|
Sets an interface for when the watchdog thread is interrupted . If not set the default behavior is to just log the interruption message .
| 55
| 26
|
156,673
|
private static Type processTypeForDescendantLookup ( Type type ) { if ( type instanceof ParameterizedType ) { return ( ( ParameterizedType ) type ) . getRawType ( ) ; } else { return type ; } }
|
Given a type returns the type that should be used for the purpose of looking up implementations of that type .
| 51
| 21
|
156,674
|
private static < T > Stream < T > generateStream ( T seed , Predicate < ? super T > hasNext , UnaryOperator < T > next ) { final Spliterator < T > spliterator = Spliterators . spliteratorUnknownSize ( new Iterator < T > ( ) { private T last = seed ; @ Override public boolean hasNext ( ) { return hasNext . test ( last ) ; } @ Override public T next ( ) { final T current = last ; last = next . apply ( last ) ; return current ; } } , Spliterator . ORDERED ) ; return StreamSupport . stream ( spliterator , false ) ; }
|
remove on Java 9 and replace with Stream . iterate
| 138
| 11
|
156,675
|
private static Set < TsBeanModel > writeBeanAndParentsFieldSpecs ( Writer writer , Settings settings , TsModel model , Set < TsBeanModel > emittedSoFar , TsBeanModel bean ) { if ( emittedSoFar . contains ( bean ) ) { return new HashSet <> ( ) ; } final TsBeanModel parentBean = getBeanModelByType ( model , bean . getParent ( ) ) ; final Set < TsBeanModel > emittedBeans = parentBean != null ? writeBeanAndParentsFieldSpecs ( writer , settings , model , emittedSoFar , parentBean ) : new HashSet < TsBeanModel > ( ) ; final String parentClassName = parentBean != null ? getBeanModelClassName ( parentBean ) + "Fields" : "Fields" ; writer . writeIndentedLine ( "" ) ; writer . writeIndentedLine ( "class " + getBeanModelClassName ( bean ) + "Fields extends " + parentClassName + " {" ) ; writer . writeIndentedLine ( settings . indentString + "constructor(parent?: Fields, name?: string) { super(parent, name); }" ) ; for ( TsPropertyModel property : bean . getProperties ( ) ) { writeBeanProperty ( writer , settings , model , bean , property ) ; } writer . writeIndentedLine ( "}" ) ; emittedBeans . add ( bean ) ; return emittedBeans ; }
|
Emits a bean and its parent beans before if needed . Returns the list of beans that were emitted .
| 321
| 21
|
156,676
|
private static boolean isOriginalTsType ( TsType type ) { if ( type instanceof TsType . BasicType ) { TsType . BasicType basicType = ( TsType . BasicType ) type ; return ! ( basicType . name . equals ( "null" ) || basicType . name . equals ( "undefined" ) ) ; } return true ; }
|
is this type an original TS type or a contextual information? null undefined and optional info are not original types everything else is original
| 76
| 25
|
156,677
|
private static TsType extractOriginalTsType ( TsType type ) { if ( type instanceof TsType . OptionalType ) { return extractOriginalTsType ( ( ( TsType . OptionalType ) type ) . type ) ; } if ( type instanceof TsType . UnionType ) { TsType . UnionType union = ( TsType . UnionType ) type ; List < TsType > originalTypes = new ArrayList <> ( ) ; for ( TsType curType : union . types ) { if ( isOriginalTsType ( curType ) ) { originalTypes . add ( curType ) ; } } return originalTypes . size ( ) == 1 ? extractOriginalTsType ( originalTypes . get ( 0 ) ) : type ; } if ( type instanceof TsType . BasicArrayType ) { return extractOriginalTsType ( ( ( TsType . BasicArrayType ) type ) . elementType ) ; } return type ; }
|
If the type is optional of number|null|undefined or list of of integer we want to be able to recognize it as number to link the member to another class . = > extract the original type while ignoring the |null|undefined and optional informations .
| 193
| 54
|
156,678
|
public static int findUnlinked ( int pos , int end , DBIDArrayIter ix , PointerHierarchyRepresentationBuilder builder ) { while ( pos < end ) { if ( ! builder . isLinked ( ix . seek ( pos ) ) ) { return pos ; } ++ pos ; } return - 1 ; }
|
Find an unlinked object .
| 70
| 6
|
156,679
|
private DoubleObjPair < Polygon > buildHullsRecursively ( Cluster < Model > clu , Hierarchy < Cluster < Model > > hier , Map < Object , DoubleObjPair < Polygon > > hulls , Relation < ? extends NumberVector > coords ) { final DBIDs ids = clu . getIDs ( ) ; FilteredConvexHull2D hull = new FilteredConvexHull2D ( ) ; for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { hull . add ( coords . get ( iter ) . toArray ( ) ) ; } double weight = ids . size ( ) ; if ( hier != null ) { final int numc = hier . numChildren ( clu ) ; if ( numc > 0 ) { for ( It < Cluster < Model > > iter = hier . iterChildren ( clu ) ; iter . valid ( ) ; iter . advance ( ) ) { final Cluster < Model > iclu = iter . get ( ) ; DoubleObjPair < Polygon > poly = hulls . get ( iclu ) ; if ( poly == null ) { poly = buildHullsRecursively ( iclu , hier , hulls , coords ) ; } // Add inner convex hull to outer convex hull. for ( ArrayListIter < double [ ] > vi = poly . second . iter ( ) ; vi . valid ( ) ; vi . advance ( ) ) { hull . add ( vi . get ( ) ) ; } weight += poly . first / numc ; } } } DoubleObjPair < Polygon > pair = new DoubleObjPair <> ( weight , hull . getHull ( ) ) ; hulls . put ( clu , pair ) ; return pair ; }
|
Recursively step through the clusters to build the hulls .
| 394
| 13
|
156,680
|
public static final Color getColorForValue ( double val ) { // Color positions double [ ] pos = new double [ ] { 0.0 , 0.6 , 0.8 , 1.0 } ; // Colors at these positions Color [ ] cols = new Color [ ] { new Color ( 0.0f , 0.0f , 0.0f , 0.6f ) , new Color ( 0.0f , 0.0f , 1.0f , 0.8f ) , new Color ( 1.0f , 0.0f , 0.0f , 0.9f ) , new Color ( 1.0f , 1.0f , 0.0f , 1.0f ) } ; assert ( pos . length == cols . length ) ; if ( val < pos [ 0 ] ) { val = pos [ 0 ] ; } // Linear interpolation: for ( int i = 1 ; i < pos . length ; i ++ ) { if ( val <= pos [ i ] ) { Color prev = cols [ i - 1 ] ; Color next = cols [ i ] ; final double mix = ( val - pos [ i - 1 ] ) / ( pos [ i ] - pos [ i - 1 ] ) ; final int r = ( int ) ( ( 1 - mix ) * prev . getRed ( ) + mix * next . getRed ( ) ) ; final int g = ( int ) ( ( 1 - mix ) * prev . getGreen ( ) + mix * next . getGreen ( ) ) ; final int b = ( int ) ( ( 1 - mix ) * prev . getBlue ( ) + mix * next . getBlue ( ) ) ; final int a = ( int ) ( ( 1 - mix ) * prev . getAlpha ( ) + mix * next . getAlpha ( ) ) ; Color col = new Color ( r , g , b , a ) ; return col ; } } return cols [ cols . length - 1 ] ; }
|
Get color from a simple heatmap .
| 424
| 8
|
156,681
|
public static int showSaveDialog ( SVGPlot plot , int width , int height ) { JFileChooser fc = new JFileChooser ( new File ( "." ) ) ; fc . setDialogTitle ( DEFAULT_TITLE ) ; // fc.setFileFilter(new ImageFilter()); SaveOptionsPanel optionsPanel = new SaveOptionsPanel ( fc , width , height ) ; fc . setAccessory ( optionsPanel ) ; int ret = fc . showSaveDialog ( null ) ; if ( ret == JFileChooser . APPROVE_OPTION ) { fc . setDialogTitle ( "Saving... Please wait." ) ; File file = fc . getSelectedFile ( ) ; String format = optionsPanel . getSelectedFormat ( ) ; width = optionsPanel . getSelectedWidth ( ) ; height = optionsPanel . getSelectedHeight ( ) ; if ( format == null || AUTOMAGIC_FORMAT . equals ( format ) ) { format = guessFormat ( file . getName ( ) ) ; } try { if ( format == null ) { showError ( fc , "Error saving image." , "File format not recognized." ) ; } else if ( "jpeg" . equals ( format ) || "jpg" . equals ( format ) ) { float quality = optionsPanel . getJPEGQuality ( ) ; plot . saveAsJPEG ( file , width , height , quality ) ; } else if ( "png" . equals ( format ) ) { plot . saveAsPNG ( file , width , height ) ; } else if ( "ps" . equals ( format ) ) { plot . saveAsPS ( file ) ; } else if ( "eps" . equals ( format ) ) { plot . saveAsEPS ( file ) ; } else if ( "pdf" . equals ( format ) ) { plot . saveAsPDF ( file ) ; } else if ( "svg" . equals ( format ) ) { plot . saveAsSVG ( file ) ; } else { showError ( fc , "Error saving image." , "Unsupported format: " + format ) ; } } catch ( java . lang . IncompatibleClassChangeError e ) { showError ( fc , "Error saving image." , "It seems that your Java version is incompatible with this version of Batik and Jpeg writing. Sorry." ) ; } catch ( ClassNotFoundException e ) { showError ( fc , "Error saving image." , "A class was not found when saving this image. Maybe installing Apache FOP will help (for PDF, PS and EPS output).\n" + e . toString ( ) ) ; } catch ( TransformerFactoryConfigurationError | Exception e ) { LOG . exception ( e ) ; showError ( fc , "Error saving image." , e . toString ( ) ) ; } } else if ( ret == JFileChooser . ERROR_OPTION ) { showError ( fc , "Error in file dialog." , "Unknown Error." ) ; } else if ( ret == JFileChooser . CANCEL_OPTION ) { // do nothing - except return result } return ret ; }
|
Show a Save as dialog .
| 675
| 6
|
156,682
|
public static String guessFormat ( String name ) { String ext = FileUtil . getFilenameExtension ( name ) ; for ( String format : FORMATS ) { if ( format . equalsIgnoreCase ( ext ) ) { return ext ; } } return null ; }
|
Guess a supported format from the file name . For auto format handling .
| 56
| 15
|
156,683
|
@ SuppressWarnings ( "unchecked" ) public static < F > FeatureVectorAdapter < F > featureVectorAdapter ( FeatureVector < F > prototype ) { return ( FeatureVectorAdapter < F > ) FEATUREVECTORADAPTER ; }
|
Get the static instance .
| 53
| 5
|
156,684
|
public static < A > int getIndexOfMaximum ( A array , NumberArrayAdapter < ? , A > adapter ) throws IndexOutOfBoundsException { final int size = adapter . size ( array ) ; int index = 0 ; double max = adapter . getDouble ( array , 0 ) ; for ( int i = 1 ; i < size ; i ++ ) { double val = adapter . getDouble ( array , i ) ; if ( val > max ) { max = val ; index = i ; } } return index ; }
|
Returns the index of the maximum of the given values . If no value is bigger than the first the index of the first entry is returned .
| 110
| 28
|
156,685
|
public byte [ ] asByteArray ( NumberVector vector ) { final long [ ] longValueList = new long [ dimensionality ] ; for ( int dim = 0 ; dim < dimensionality ; ++ dim ) { final double minValue = minValues [ dim ] ; final double maxValue = maxValues [ dim ] ; double dimValue = vector . doubleValue ( dim ) ; dimValue = ( dimValue - minValue ) / ( maxValue - minValue ) ; longValueList [ dim ] = ( long ) ( dimValue * ( Long . MAX_VALUE ) ) ; } final byte [ ] bytes = new byte [ Long . SIZE * dimensionality * ( Long . SIZE / Byte . SIZE ) ] ; int shiftCounter = 0 ; for ( int i = 0 ; i < Long . SIZE ; ++ i ) { for ( int dim = 0 ; dim < dimensionality ; ++ dim ) { long byteValue = longValueList [ dim ] ; int localShift = shiftCounter % Byte . SIZE ; bytes [ ( bytes . length - 1 ) - ( shiftCounter / Byte . SIZE ) ] |= ( ( byteValue >> i ) & 0x01 ) << localShift ; shiftCounter ++ ; } } return bytes ; }
|
Transform a single vector .
| 262
| 5
|
156,686
|
public OutlierResult run ( Relation < V > relation ) { SimilarityQuery < V > snnInstance = similarityFunction . instantiate ( relation ) ; FiniteProgress progress = LOG . isVerbose ( ) ? new FiniteProgress ( "Assigning Subspace Outlier Degree" , relation . size ( ) , LOG ) : null ; WritableDoubleDataStore sod_scores = DataStoreUtil . makeDoubleStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_STATIC ) ; WritableDataStore < SODModel > sod_models = models ? DataStoreUtil . makeStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_STATIC , SODModel . class ) : null ; DoubleMinMax minmax = new DoubleMinMax ( ) ; for ( DBIDIter iter = relation . iterDBIDs ( ) ; iter . valid ( ) ; iter . advance ( ) ) { DBIDs neighborhood = getNearestNeighbors ( relation , snnInstance , iter ) ; double [ ] center ; long [ ] weightVector = null ; double sod = 0. ; if ( neighborhood . size ( ) > 0 ) { center = Centroid . make ( relation , neighborhood ) . getArrayRef ( ) ; // Note: per-dimension variances; no covariances. double [ ] variances = computePerDimensionVariances ( relation , center , neighborhood ) ; double expectationOfVariance = Mean . of ( variances ) ; weightVector = BitsUtil . zero ( variances . length ) ; for ( int d = 0 ; d < variances . length ; d ++ ) { if ( variances [ d ] < alpha * expectationOfVariance ) { BitsUtil . setI ( weightVector , d ) ; } } sod = subspaceOutlierDegree ( relation . get ( iter ) , center , weightVector ) ; } else { center = relation . get ( iter ) . toArray ( ) ; } if ( sod_models != null ) { sod_models . put ( iter , new SODModel ( center , weightVector ) ) ; } sod_scores . putDouble ( iter , sod ) ; minmax . put ( sod ) ; LOG . incrementProcessed ( progress ) ; } LOG . ensureCompleted ( progress ) ; // combine results. OutlierScoreMeta meta = new BasicOutlierScoreMeta ( minmax . getMin ( ) , minmax . getMax ( ) ) ; OutlierResult sodResult = new OutlierResult ( meta , new MaterializedDoubleRelation ( "Subspace Outlier Degree" , "sod-outlier" , sod_scores , relation . getDBIDs ( ) ) ) ; if ( sod_models != null ) { sodResult . addChildResult ( new MaterializedRelation <> ( "Subspace Outlier Model" , "sod-outlier" , new SimpleTypeInformation <> ( SODModel . class ) , sod_models , relation . getDBIDs ( ) ) ) ; } return sodResult ; }
|
Performs the SOD algorithm on the given database .
| 651
| 11
|
156,687
|
private DBIDs getNearestNeighbors ( Relation < V > relation , SimilarityQuery < V > simQ , DBIDRef queryObject ) { Heap < DoubleDBIDPair > nearestNeighbors = new TiedTopBoundedHeap <> ( knn ) ; for ( DBIDIter iter = relation . iterDBIDs ( ) ; iter . valid ( ) ; iter . advance ( ) ) { if ( DBIDUtil . equal ( iter , queryObject ) ) { continue ; } double sim = simQ . similarity ( queryObject , iter ) ; if ( sim > 0. ) { nearestNeighbors . add ( DBIDUtil . newPair ( sim , iter ) ) ; } } // Collect DBIDs ArrayModifiableDBIDs dbids = DBIDUtil . newArray ( nearestNeighbors . size ( ) ) ; while ( nearestNeighbors . size ( ) > 0 ) { dbids . add ( nearestNeighbors . poll ( ) ) ; } return dbids ; }
|
Get the k nearest neighbors in terms of the shared nearest neighbor distance .
| 214
| 14
|
156,688
|
private static double [ ] computePerDimensionVariances ( Relation < ? extends NumberVector > relation , double [ ] center , DBIDs neighborhood ) { final int dim = center . length ; double [ ] variances = new double [ dim ] ; for ( DBIDIter iter = neighborhood . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { NumberVector databaseObject = relation . get ( iter ) ; for ( int d = 0 ; d < dim ; d ++ ) { final double deviation = databaseObject . doubleValue ( d ) - center [ d ] ; variances [ d ] += deviation * deviation ; } } return VMath . timesEquals ( variances , 1. / neighborhood . size ( ) ) ; }
|
Compute the per - dimension variances for the given neighborhood and center .
| 158
| 15
|
156,689
|
private double subspaceOutlierDegree ( V queryObject , double [ ] center , long [ ] weightVector ) { final int card = BitsUtil . cardinality ( weightVector ) ; if ( card == 0 ) { return 0 ; } final SubspaceEuclideanDistanceFunction df = new SubspaceEuclideanDistanceFunction ( weightVector ) ; return df . distance ( queryObject , DoubleVector . wrap ( center ) ) / card ; }
|
Compute SOD score .
| 97
| 6
|
156,690
|
public static long parseLongBase10 ( final CharSequence str , final int start , final int end ) { // Current position and character. int pos = start ; char cur = str . charAt ( pos ) ; // Match sign boolean isNegative = ( cur == ' ' ) ; // Carefully consume the - character, update c and i: if ( ( isNegative || ( cur == ' ' ) ) && ( ++ pos < end ) ) { cur = str . charAt ( pos ) ; } // Begin parsing real numbers! if ( ( cur < ' ' ) || ( cur > ' ' ) ) { throw NOT_A_NUMBER ; } // Parse digits into a long, remember offset of decimal point. long decimal = 0 ; while ( true ) { final int digit = cur - ' ' ; if ( ( digit >= 0 ) && ( digit <= 9 ) ) { final long tmp = ( decimal << 3 ) + ( decimal << 1 ) + digit ; if ( tmp < decimal ) { throw PRECISION_OVERFLOW ; } decimal = tmp ; } else { // No more digits, or a second dot. break ; } if ( ++ pos < end ) { cur = str . charAt ( pos ) ; } else { break ; } } if ( pos != end ) { throw TRAILING_CHARACTERS ; } return isNegative ? - decimal : decimal ; }
|
Parse a long integer from a character sequence .
| 295
| 10
|
156,691
|
private static boolean matchInf ( byte [ ] str , byte firstchar , int start , int end ) { final int len = end - start ; // The wonders of unicode. The infinity symbol \u221E is three bytes: if ( len == 3 && firstchar == - 0x1E && str [ start + 1 ] == - 0x78 && str [ start + 2 ] == - 0x62 ) { return true ; } if ( ( len != 3 && len != INFINITY_LENGTH ) // || ( firstchar != ' ' && firstchar != ' ' ) ) { return false ; } for ( int i = 1 , j = INFINITY_LENGTH + 1 ; i < INFINITY_LENGTH ; i ++ , j ++ ) { final byte c = str [ start + i ] ; if ( c != INFINITY_PATTERN [ i ] && c != INFINITY_PATTERN [ j ] ) { return false ; } if ( i == 2 && len == 3 ) { return true ; } } return true ; }
|
Match inf infinity in a number of different capitalizations .
| 227
| 11
|
156,692
|
private static boolean matchNaN ( byte [ ] str , byte firstchar , int start , int end ) { final int len = end - start ; if ( len < 2 || len > 3 || ( firstchar != ' ' && firstchar != ' ' ) ) { return false ; } final byte c1 = str [ start + 1 ] ; if ( c1 != ' ' && c1 != ' ' ) { return false ; } // Accept just "NA", too: if ( len == 2 ) { return true ; } final byte c2 = str [ start + 2 ] ; return c2 == ' ' || c2 == ' ' ; }
|
Match NaN in a number of different capitalizations .
| 136
| 11
|
156,693
|
public static void setLookAndFeel ( ) { try { if ( PREFER_GTK ) { LookAndFeelInfo [ ] lfs = UIManager . getInstalledLookAndFeels ( ) ; for ( LookAndFeelInfo lf : lfs ) { if ( lf . getClassName ( ) . contains ( "GTK" ) ) { UIManager . setLookAndFeel ( lf . getClassName ( ) ) ; return ; } } } // Fallback: UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { // ignore } }
|
Setup look at feel .
| 144
| 5
|
156,694
|
public static void logUncaughtExceptions ( Logging logger ) { try { Thread . setDefaultUncaughtExceptionHandler ( ( t , e ) -> logger . exception ( e ) ) ; } catch ( SecurityException e ) { logger . warning ( "Could not set the Default Uncaught Exception Handler" , e ) ; } }
|
Setup logging of uncaught exceptions .
| 70
| 7
|
156,695
|
protected List < OneItemset > buildFrequentOneItemsets ( final Relation < ? extends SparseFeatureVector < ? > > relation , final int dim , final int needed ) { // TODO: use TIntList and prefill appropriately to avoid knowing "dim" // beforehand? int [ ] counts = new int [ dim ] ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { SparseFeatureVector < ? > bv = relation . get ( iditer ) ; for ( int it = bv . iter ( ) ; bv . iterValid ( it ) ; it = bv . iterAdvance ( it ) ) { counts [ bv . iterDim ( it ) ] ++ ; } } if ( LOG . isStatistics ( ) ) { LOG . statistics ( new LongStatistic ( STAT + "1-items.candidates" , dim ) ) ; } // Generate initial candidates of length 1. List < OneItemset > frequent = new ArrayList <> ( dim ) ; for ( int i = 0 ; i < dim ; i ++ ) { if ( counts [ i ] >= needed ) { frequent . add ( new OneItemset ( i , counts [ i ] ) ) ; } } return frequent ; }
|
Build the 1 - itemsets .
| 279
| 7
|
156,696
|
protected List < SparseItemset > buildFrequentTwoItemsets ( List < OneItemset > oneitems , final Relation < BitVector > relation , final int dim , final int needed , DBIDs ids , ArrayModifiableDBIDs survivors ) { int f1 = 0 ; long [ ] mask = BitsUtil . zero ( dim ) ; for ( OneItemset supported : oneitems ) { BitsUtil . setI ( mask , supported . item ) ; f1 ++ ; } if ( LOG . isStatistics ( ) ) { LOG . statistics ( new LongStatistic ( STAT + "2-items.candidates" , f1 * ( long ) ( f1 - 1 ) ) ) ; } // We quite aggressively size the map, assuming that almost each combination // is present somewhere. If this won't fit into memory, we're likely running // OOM somewhere later anyway! Long2IntOpenHashMap map = new Long2IntOpenHashMap ( ( f1 * ( f1 - 1 ) ) >>> 1 ) ; final long [ ] scratch = BitsUtil . zero ( dim ) ; for ( DBIDIter iditer = ids . iter ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { BitsUtil . setI ( scratch , mask ) ; relation . get ( iditer ) . andOnto ( scratch ) ; int lives = 0 ; for ( int i = BitsUtil . nextSetBit ( scratch , 0 ) ; i >= 0 ; i = BitsUtil . nextSetBit ( scratch , i + 1 ) ) { for ( int j = BitsUtil . nextSetBit ( scratch , i + 1 ) ; j >= 0 ; j = BitsUtil . nextSetBit ( scratch , j + 1 ) ) { long key = ( ( ( long ) i ) << 32 ) | j ; map . put ( key , 1 + map . get ( key ) ) ; ++ lives ; } } if ( lives > 2 ) { survivors . add ( iditer ) ; } } // Generate candidates of length 2. List < SparseItemset > frequent = new ArrayList <> ( f1 * ( int ) FastMath . sqrt ( f1 ) ) ; for ( ObjectIterator < Long2IntMap . Entry > iter = map . long2IntEntrySet ( ) . fastIterator ( ) ; iter . hasNext ( ) ; ) { Long2IntMap . Entry entry = iter . next ( ) ; if ( entry . getIntValue ( ) >= needed ) { int ii = ( int ) ( entry . getLongKey ( ) >>> 32 ) ; int ij = ( int ) ( entry . getLongKey ( ) & - 1L ) ; frequent . add ( new SparseItemset ( new int [ ] { ii , ij } , entry . getIntValue ( ) ) ) ; } } // The hashmap may produce them out of order. Collections . sort ( frequent ) ; if ( LOG . isStatistics ( ) ) { LOG . statistics ( new LongStatistic ( STAT + "2-items.frequent" , frequent . size ( ) ) ) ; } return frequent ; }
|
Build the 2 - itemsets .
| 669
| 7
|
156,697
|
protected List < ? extends Itemset > frequentItemsets ( List < ? extends Itemset > candidates , Relation < BitVector > relation , int needed , DBIDs ids , ArrayModifiableDBIDs survivors , int length ) { if ( candidates . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Itemset first = candidates . get ( 0 ) ; // We have an optimized codepath for large and sparse itemsets. // It probably pays off when #cands >> (avlen choose length) but we do not // currently have the average number of items. These thresholds yield // 2700, 6400, 12500, ... and thus will almost always be met until the // number of frequent itemsets is about to break down to 0. if ( candidates . size ( ) > length * length * length * 100 && first instanceof SparseItemset ) { // Assume that all itemsets are sparse itemsets! @ SuppressWarnings ( "unchecked" ) List < SparseItemset > sparsecand = ( List < SparseItemset > ) candidates ; return frequentItemsetsSparse ( sparsecand , relation , needed , ids , survivors , length ) ; } for ( DBIDIter iditer = ids . iter ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { BitVector bv = relation . get ( iditer ) ; // TODO: exploit that the candidate set it sorted? int lives = 0 ; for ( Itemset candidate : candidates ) { if ( candidate . containedIn ( bv ) ) { candidate . increaseSupport ( ) ; ++ lives ; } } if ( lives > length ) { survivors . add ( iditer ) ; } } // Retain only those with minimum support: List < Itemset > frequent = new ArrayList <> ( candidates . size ( ) ) ; for ( Iterator < ? extends Itemset > iter = candidates . iterator ( ) ; iter . hasNext ( ) ; ) { final Itemset candidate = iter . next ( ) ; if ( candidate . getSupport ( ) >= needed ) { frequent . add ( candidate ) ; } } return frequent ; }
|
Returns the frequent BitSets out of the given BitSets with respect to the given database .
| 456
| 20
|
156,698
|
protected List < SparseItemset > frequentItemsetsSparse ( List < SparseItemset > candidates , Relation < BitVector > relation , int needed , DBIDs ids , ArrayModifiableDBIDs survivors , int length ) { // Current search interval: int begin = 0 , end = candidates . size ( ) ; int [ ] scratchi = new int [ length ] , iters = new int [ length ] ; SparseItemset scratch = new SparseItemset ( scratchi ) ; for ( DBIDIter iditer = ids . iter ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { BitVector bv = relation . get ( iditer ) ; if ( ! initializeSearchItemset ( bv , scratchi , iters ) ) { continue ; } int lives = 0 ; while ( begin < end ) { begin = binarySearch ( candidates , scratch , begin , end ) ; if ( begin > 0 ) { candidates . get ( begin ) . increaseSupport ( ) ; ++ lives ; } else { begin = ( - begin ) - 1 ; } if ( begin >= end || ! nextSearchItemset ( bv , scratchi , iters ) ) { break ; } } for ( Itemset candidate : candidates ) { if ( candidate . containedIn ( bv ) ) { candidate . increaseSupport ( ) ; ++ lives ; } } if ( lives > length ) { survivors . add ( iditer ) ; } } // Retain only those with minimum support: List < SparseItemset > frequent = new ArrayList <> ( candidates . size ( ) ) ; for ( Iterator < SparseItemset > iter = candidates . iterator ( ) ; iter . hasNext ( ) ; ) { final SparseItemset candidate = iter . next ( ) ; if ( candidate . getSupport ( ) >= needed ) { frequent . add ( candidate ) ; } } return frequent ; }
|
Returns the frequent BitSets out of the given BitSets with respect to the given database . Optimized implementation for SparseItemset .
| 404
| 29
|
156,699
|
private boolean initializeSearchItemset ( BitVector bv , int [ ] scratchi , int [ ] iters ) { for ( int i = 0 ; i < scratchi . length ; i ++ ) { iters [ i ] = ( i == 0 ) ? bv . iter ( ) : bv . iterAdvance ( iters [ i - 1 ] ) ; if ( iters [ i ] < 0 ) { return false ; } scratchi [ i ] = bv . iterDim ( iters [ i ] ) ; } return true ; }
|
Initialize the scratch itemset .
| 117
| 7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.