code
stringlengths
73
34.1k
label
stringclasses
1 value
public static ZContext shadow(ZContext ctx) { ZContext context = new ZContext(ctx.context, false, ctx.ioThreads); context.linger = ctx.linger; context.sndhwm = ctx.sndhwm; context.rcvhwm = ctx.rcvhwm; context.pipehwm = ctx.pipehwm; return context; }
java
public Socket fork(ZThread.IAttachedRunnable runnable, Object... args) { return ZThread.fork(this, runnable, args); }
java
public static ByteBuffer putUInt64(ByteBuffer buf, long value) { buf.put((byte) ((value >>> 56) & 0xff)); buf.put((byte) ((value >>> 48) & 0xff)); buf.put((byte) ((value >>> 40) & 0xff)); buf.put((byte) ((value >>> 32) & 0xff)); buf.put((byte) ((value >>> 24) & 0xff)); ...
java
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) { Socket pipe = ctx.createSocket(SocketType.PAIR); if (pipe != null) { pipe.bind(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); } else { return null; } ...
java
private void startConnecting() { // Open the connecting socket. try { boolean rc = open(); // Connect may succeed in synchronous manner. if (rc) { handle = ioObject.addFd(fd); connectEvent(); } // Connect...
java
private void addReconnectTimer() { int rcIvl = getNewReconnectIvl(); ioObject.addTimer(rcIvl, RECONNECT_TIMER_ID); // resolve address again to take into account other addresses // besides the failing one (e.g. multiple dns entries). try { addr.resolve(options.ipv...
java
private int getNewReconnectIvl() { // The new interval is the current interval + random value. int interval = currentReconnectIvl + (Utils.randomInt() % options.reconnectIvl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's ...
java
private boolean open() throws IOException { assert (fd == null); // Resolve the address if (addr == null) { throw new IOException("Null address"); } addr.resolve(options.ipv6); Address.IZAddress resolved = addr.resolved(); if (resolved == null)...
java
private SocketChannel connect() { try { // Async connect has finished. Check whether an error occurred boolean finished = fd.finishConnect(); assert (finished); return fd; } catch (IOException e) { return null; } }
java
protected void close() { assert (fd != null); try { fd.close(); socket.eventClosed(addr.toString(), fd); } catch (IOException e) { socket.eventCloseFailed(addr.toString(), ZError.exccode(e)); } fd = null; }
java
@Deprecated public boolean setInterval(Timer timer, long interval) { assert (timer.parent == this); return timer.setInterval(interval); }
java
public long timeout() { final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); if (timer.alive) { // Live timer, lets return the timeout i...
java
public int execute() { int executed = 0; final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); // Dead timer, lets remove it and continue if (!timer....
java
public static ZProxy newProxy(ZContext ctx, String name, Proxy sockets, String motdelafin, Object... args) { return new ZProxy(ctx, name, sockets, new ZmqPump(), motdelafin, args); }
java
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); } ...
java
public String exit() { agent.send(EXIT); exit.awaitSilent(); agent.close(); return EXITED; }
java
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(); ...
java
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(); retu...
java
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)); }
java
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(pub...
java
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) { ...
java
public ZAuth configureCurve(String location) { Objects.requireNonNull(location, "Location has to be supplied"); return send(Mechanism.CURVE.name(), location); }
java
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); }
java
public static int send(SocketBase s, String str, int flags) { byte[] data = str.getBytes(CHARSET); return send(s, data, data.length, flags); }
java
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 overfl...
java
public static String getMessageMetadata(Msg msg, String property) { String data = null; Metadata metadata = msg.getMetadata(); if (metadata != null) { data = metadata.get(property); } return data; }
java
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, ba...
java
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; }
java
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(); re...
java
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(...
java
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); }
java
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; }
java
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...
java
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 = fal...
java
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 = fals...
java
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; } ...
java
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; }
java
public void rollback() { // Remove incomplete message from the outbound pipe. Msg msg; if (outpipe != null) { while ((msg = outpipe.unwrite()) != null) { assert (msg.hasMore()); } } }
java
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); } }
java
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; ...
java
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...
java
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 ne...
java
protected boolean rollback() { if (currentOut != null) { currentOut.rollback(); currentOut = null; moreOut = false; } return true; }
java
@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 == ...
java
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; ...
java
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; }
java
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) { ...
java
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...
java
@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()); ...
java
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); }
java
public boolean rm(Msg msg, Pipe pipe) { assert (msg != null); assert (pipe != null); return rmHelper(msg, 1, msg.size() - 1, pipe); }
java
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 (...
java
private void close() { assert (fd != null); try { fd.close(); socket.eventClosed(endpoint, fd); } catch (IOException e) { socket.eventCloseFailed(endpoint, ZError.exccode(e)); } fd = null; }
java
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)...
java
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....
java
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...
java
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--; } ...
java
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) { Coll...
java
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) { ...
java
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) { ...
java
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...
java
public final boolean register(final SelectableChannel channel, final EventsHandler handler) { return register(channel, handler, IN | OUT | ERR); }
java
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); } retu...
java
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, ti...
java
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); }
java
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()...
java
public boolean readable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, READABLE); if (it == null) { return false; } return it.isReadable(); }
java
public boolean writable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, WRITABLE); if (it == null) { return false; } return it.isWritable(); }
java
public boolean error(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, ERR); if (it == null) { return false; } return it.isError(); }
java
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 ...
java
protected Collection<? extends ItemHolder> items() { for (CompositePollItem item : all) { item.handler(globalHandler); } return all; }
java
protected Iterable<ItemHolder> items(final Object socketOrChannel) { final CompositePollItem aggregate = items.get(socketOrChannel); if (aggregate == null) { return Collections.emptySet(); } return aggregate.holders; }
java
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(); ...
java
public String getShortString() { String value = Wire.getShortString(needle, needle.position()); forward(value.length() + 1); return value; }
java
public String getLongString() { String value = Wire.getLongString(needle, needle.position()); forward(value.length() + 4); return value; }
java
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 : e...
java
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()...
java
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....
java
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 ...
java
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; }
java
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 (SP...
java
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 (...
java
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 executi...
java
public ANRWatchDog setANRListener(ANRListener listener) { if (listener == null) { _anrListener = DEFAULT_ANR_LISTENER; } else { _anrListener = listener; } return this; }
java
public ANRWatchDog setANRInterceptor(ANRInterceptor interceptor) { if (interceptor == null) { _anrInterceptor = DEFAULT_ANR_INTERCEPTOR; } else { _anrInterceptor = interceptor; } return this; }
java
public ANRWatchDog setInterruptionListener(InterruptionListener listener) { if (listener == null) { _interruptionListener = DEFAULT_INTERRUPTION_LISTENER; } else { _interruptionListener = listener; } return this; }
java
private static Type processTypeForDescendantLookup(Type type) { if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getRawType(); } else { return type; } }
java
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() { r...
java
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(mo...
java
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; }
java
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; Lis...
java
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; }
java
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...
java
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.0...
java
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);...
java
public static String guessFormat(String name) { String ext = FileUtil.getFilenameExtension(name); for(String format : FORMATS) { if(format.equalsIgnoreCase(ext)) { return ext; } } return null; }
java
@SuppressWarnings("unchecked") public static <F> FeatureVectorAdapter<F> featureVectorAdapter(FeatureVector<F> prototype) { return (FeatureVectorAdapter<F>) FEATUREVECTORADAPTER; }
java
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 (...
java
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 = ...
java
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.mak...
java