code
stringlengths
73
34.1k
label
stringclasses
1 value
public static List<File> listFiles(File dir, FileFilter filter, boolean recursive){ List<File> list = new ArrayList<File>(); listFilesInternal(list, dir, filter, recursive); return list; }
java
@SuppressWarnings("unchecked") public <T> T getAttribute(String name) { return (T) this.webSocketSession.getAttributes().get(name); }
java
public void registerDestructionCallback(String name, Runnable callback) { synchronized (getSessionMutex()) { if (isSessionCompleted()) { throw new IllegalStateException( "Session id=" + getWebSocketSessionId() + " already completed"); } setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name, callback...
java
public Object getSessionMutex() { Object mutex = getAttribute(SESSION_MUTEX_NAME); if (mutex == null) { mutex = this.webSocketSession.getAttributes(); } return mutex; }
java
public int peek(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { // non volatile read ( which is quicker ) final int readLocation = this.consumerReadLocation; blockForReadSpace(timeout, unit, readLocation); // purposely not volatile as the read...
java
public Object invoke(WampMessage message, Object... providedArgs) throws Exception { Object[] args = getMethodArgumentValues(message, providedArgs); if (this.logger.isTraceEnabled()) { this.logger.trace("Resolved arguments: " + Arrays.asList(args)); } Object returnValue = doInvoke(args); if (this.logger.is...
java
private Object[] getMethodArgumentValues(WampMessage message, Object... providedArgs) throws Exception { MethodParameter[] parameters = getMethodParameters(); Object[] args = new Object[parameters.length]; int argIndex = 0; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = paramet...
java
protected String getDetailedErrorMessage(String message) { StringBuilder sb = new StringBuilder(message).append("\n"); sb.append("HandlerMethod details: \n"); sb.append("Bean [").append(getBeanType().getName()).append("]\n"); sb.append("Method [").append(getBridgedMethod().toGenericString()).append("]\n"); re...
java
protected Object doInvoke(Object... args) throws Exception { ReflectionUtils.makeAccessible(getBridgedMethod()); try { return getBridgedMethod().invoke(getBean(), args); } catch (IllegalArgumentException ex) { assertTargetBean(getBridgedMethod(), getBean(), args); throw new IllegalStateException( ...
java
private File[] resolveConfigFiles(File base, Map<String, Object> override) { //system properties //-Dconfig=config.json -> override //Override if (override != null) { String configFilesString = (String) override.remove("config"); if (StringUtils.isNotBlank(configF...
java
public WebSocketTransportRegistration setDecoratorFactories( WebSocketHandlerDecoratorFactory... factories) { if (factories != null) { this.decoratorFactories.addAll(Arrays.asList(factories)); } return this; }
java
public boolean offer(float value, long timeout, TimeUnit unit) throws InterruptedException { // non volatile read ( which is quicker ) final int writeLocation = this.producerWriteLocation; // sets the nextWriteLocation my moving it on by 1, this may cause it it wrap back to the st...
java
public int size() { int read = readLocation; int write = writeLocation; if (write < read) write += capacity; return write - read; }
java
public static String[] removeEmpties(final String... values) { if (values == null || values.length == 0){ return new String[0]; } List<String> validValues = new ArrayList<String>(); for (String value : values){ if (value != null && value.length() > 0){ validValues.add(value); } } return validVa...
java
public static String[] getMatchingPaths(final String[] includes, final String[] excludes, final String baseDir) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(baseDir); if (includes != null && includes.length > 0){ scanner.setIncludes(includes); } if (excludes != null && exclude...
java
private FileFilter createConfigFilesFilter() { SiteConfig config = site.getConfig(); boolean useDefaultConfigFiles = config.useDefaultConfigFiles(); if (useDefaultConfigFiles) { log.debug("Using default config files."); return SiteConfigImpl.DEFAULT_CONFIG_FILES_FILTER; ...
java
public static Vector inverseTransform (double x, double y, double sx, double sy, double rotation, Vector result) { double sinnega = Math.sin(-rotation), cosnega = Math.cos(-rotation); double nx = (x * cosnega - y * sinnega); // unrotate double ny = (x *...
java
public void start() { setDefaultLogLevel(); /* * JLine doesn't run in Eclipse. To get around this, we allow * a property "jlineDisable" to be specified via VM arguments. * This causes it to use standard scanning of System.in and disables * auto complete functionality. */ if (Boolean.get...
java
protected FindCommandResult findAndCreateCommand(String[] args) throws CommandInitException { String commandName = args[0]; String[] remainingArguments = StringUtils.stripArgs(args, 1); // Check top level commands for app Class<? extends Command<? extends CLIContext>> commandClass = _commands.get(co...
java
private Map<String, Class<? extends Command<? extends CLIContext>>> loadCommands() throws CLIInitException{ Map<String, Class<? extends Command<? extends CLIContext>>> commands = new HashMap<String, Class<? extends Command<? extends CLIContext>>>(); Discoverer discoverer = new ClasspathDiscoverer(); CL...
java
public void setBounds (IRectangle r) { setBounds(r.x(), r.y(), r.width(), r.height()); }
java
public void add (int px, int py) { int x1 = Math.min(x, px); int x2 = Math.max(x + width, px); int y1 = Math.min(y, py); int y2 = Math.max(y + height, py); setBounds(x1, y1, x2 - x1, y2 - y1); }
java
public void add (IRectangle r) { int x1 = Math.min(x, r.x()); int x2 = Math.max(x + width, r.x() + r.width()); int y1 = Math.min(y, r.y()); int y2 = Math.max(y + height, r.y() + r.height()); setBounds(x1, y1, x2 - x1, y2 - y1); }
java
public Vector setAngle (double angle) { double l = length(); return set(l * Math.cos(angle), l * Math.sin(angle)); }
java
public boolean setListenerURL(String listenerURL) { String newURL = _substitutor.replace(listenerURL); boolean changed = false; if (!_urlValidator.isValid(newURL)) { error("The Response Listener URL specified is invalid. Continuing with previous value."); } else { if (!newURL.equalsIgnoreCas...
java
public void setResponseURL(String responseURL) { String newURL = _substitutor.replace(responseURL); if (!_urlValidator.isValid(newURL)) { error("The RespondTo URL specified is invalid. Continuing with previous value."); } else { this._responseURL = newURL; } }
java
public Box set (IVector3 minExtent, IVector3 maxExtent) { _minExtent.set(minExtent); _maxExtent.set(maxExtent); return this; }
java
public Box fromPoints (IVector3... points) { setToEmpty(); for (IVector3 point : points) { addLocal(point); } return this; }
java
public static int solveQuad (double[] eqn, double[] res) { double a = eqn[2]; double b = eqn[1]; double c = eqn[0]; int rc = 0; if (a == 0f) { if (b == 0f) { return -1; } res[rc++] = -c / b; } else { double d...
java
public static int solveCubic (double[] eqn, double[] res) { double d = eqn[3]; if (d == 0) { return solveQuad(eqn, res); } double a = eqn[2] / d; double b = eqn[1] / d; double c = eqn[0] / d; int rc = 0; double Q = (a * a - 3f * b) / 9f; ...
java
public static int intersectLine (double x1, double y1, double x2, double y2, double rx1, double ry1, double rx2, double ry2) { // LEFT/RIGHT/UP if ((rx2 < x1 && rx2 < x2) || (rx1 > x1 && rx1 > x2) || (ry1 > y1 && ry1 > y2)) { return 0; } ...
java
protected static void sortBound (double[] bound, int bc) { for (int i = 0; i < bc - 4; i += 4) { int k = i; for (int j = i + 4; j < bc; j += 4) { if (bound[k] > bound[j]) { k = j; } } if (k != i) { ...
java
protected static int crossBound (double[] bound, int bc, double py1, double py2) { // LEFT/RIGHT if (bc == 0) { return 0; } // Check Y coordinate int up = 0; int down = 0; for (int i = 2; i < bc; i += 4) { if (bound[i] < py1) { ...
java
public void setElement (int row, int col, float value) { switch (col) { case 0: switch (row) { case 0: m00 = value; return; case 1: m01 = value; return; case 2: m02 = value; return; } break; case 1: switch (row) ...
java
public Plane fromPoints (IVector3 p1, IVector3 p2, IVector3 p3) { // compute the normal by taking the cross product of the two vectors formed p2.subtract(p1, _v1); p3.subtract(p1, _v2); _v1.cross(_v2, _normal).normalizeLocal(); // use the first point to determine the constant ...
java
public Plane fromPointNormal (IVector3 pt, IVector3 normal) { return set(normal, -normal.dot(pt)); }
java
public static String[] stripArgs(String[] originalArgs, int stripCount) { if (originalArgs.length <= stripCount) { return new String[0]; } String[] stripped = new String[originalArgs.length - stripCount]; for (int i = 0; i < stripped.length; i++) { stripped[i] = originalArgs[i+stripCount]; } r...
java
public <U extends T> OngoingMatchingC0<T, U> when(MatchesExact<U> o) { List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.eq(o.t)); return new OngoingMatchingC0<>( this, new DecomposableMatchBuilder0<>(matchers, new IdentityFieldExtractor<U>()).build()); }
java
public <U extends T> OngoingMatchingC1<T, U, U> when(MatchesAny<U> o) { List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.any()); return new OngoingMatchingC1<>( this, new DecomposableMatchBuilder1<U, U>(matchers, 0, new IdentityFieldExtractor<>()).build()); }
java
public void doMatch() { boolean matchFound = false; for (ConsumablePattern<T> pattern : patterns) { if (pattern.matches(value)) { pattern.consume(value); matchFound = true; break; } } if (!matchFound) { throw new MatchException("No match found for " + value); ...
java
public FluentMatchingC<T> orElse() { patterns.add(ConsumablePattern.of(t -> true, t -> doNothing())); return this; }
java
public void subscribe() throws URISyntaxException, TransportConfigException { /* * if this instance of the transport (as there could be several - each with * a different topic) is in shutdown mode then don't subscribe. This is a * side effect of when you shutdown a sns transport and the listener get...
java
@SuppressWarnings("unchecked") public static <T> Matcher<T> eq(T value) { return (Matcher<T>) new Equals(value); }
java
public static URI getLocalBaseURI() { InetAddress localAddr; String addr; try { localAddr = InetAddress.getLocalHost(); addr = localAddr.getHostAddress(); } catch (UnknownHostException e) { LOGGER.warn("Issues finding ip address of locahost. Using string 'localhost' for listener addre...
java
private String calculateSHA256Hash(byte[] msg, int offset, int len) { // Calculate the SHA256 digest of the Hello message Digest digest = platform.getCrypto().createDigestSHA256(); digest.update(msg, offset, len); int digestLen = digest.getDigestLength(); // prepare space for hexadecimal representation, store...
java
public void handleIncomingMessage(byte[] data, int offset, int len) { synchronized(messageQueue) { messageQueue.add(new IncomingMessage(data, offset, len)); } synchronized(lock) { lock.notifyAll(); } }
java
public boolean isTrusted() { if (delayedCacheUpdate || farEndZID == null) { return false; } cache.selectEntry(farEndZID); return cache.getTrust(); }
java
private void runSession() { if (!started) { logString("Thread Starting"); completed = false; seqNum = getStartSeqNum(); rtpStack.setNextZrtpSequenceNumber(getStartSeqNum()); state = ZRTP_STATE_INACTIVE; initiator = false; hashMode = HashType.UNDEFINED; dhMode = KeyAgreementType.DH3K; sasMod...
java
public void setSdpHelloHash(String version, String helloHash) { if (!version.startsWith(VERSION_PREFIX)) { logWarning("Different version number: '" + version + "' Ours: '" + VERSION_PREFIX + "' (" + VERSION + ")"); } sdpHelloHashReceived = helloHash; }
java
public void untrust() { cache.updateEntry(cacheExpiryTime(), false, newRS, keepRS2, null); delayedCacheUpdate = true; }
java
private boolean verifyHelloMessage(byte[] helloMsg) { if (sdpHelloHashReceived != null) { String hash = calculateSHA256Hash(helloMsg, 0, helloMsg.length); boolean hashesMatched = hash.toUpperCase().equals( sdpHelloHashReceived.toUpperCase()); if (platform.getLogger().isEnabled()) { if (hashesMatched...
java
public IntersectionType intersectionType (Box box) { // exit quickly in cases where the bounding boxes don't overlap (equivalent to a separating // axis test using the axes of the box) if (!_bounds.intersects(box)) { return IntersectionType.NONE; } // consider each s...
java
public Box boundsUnderRotation (Matrix3 matrix, Box result) { result.setToEmpty(); for (Vector3 vertex : _vertices) { result.addLocal(matrix.transform(vertex, _vertex)); } return result; }
java
protected void updateDerivedState () { _planes[0].fromPoints(_vertices[0], _vertices[1], _vertices[2]); // near _planes[1].fromPoints(_vertices[5], _vertices[4], _vertices[7]); // far _planes[2].fromPoints(_vertices[1], _vertices[5], _vertices[6]); // left _planes[3].fromPoints(_vertices...
java
public void setArcType (int type) { if (type != OPEN && type != CHORD && type != PIE) { throw new IllegalArgumentException("Invalid Arc type: " + type); } this.type = type; }
java
public void setArc (IArc arc) { setArc(arc.x(), arc.y(), arc.width(), arc.height(), arc.angleStart(), arc.angleExtent(), arc.arcType()); }
java
public void setAngleStart (XY point) { double angle = Math.atan2(point.y() - centerY(), point.x() - centerX()); setAngleStart(normAngle(-Math.toDegrees(angle))); }
java
public static float distance (float x1, float y1, float x2, float y2) { return FloatMath.sqrt(distanceSq(x1, y1, x2, y2)); }
java
public void setRoundRect (float x, float y, float width, float height, float arcwidth, float archeight) { this.x = x; this.y = y; this.width = width; this.height = height; this.arcwidth = arcwidth; this.archeight = archeight; }
java
public void setRoundRect (IRoundRectangle rr) { setRoundRect(rr.x(), rr.y(), rr.width(), rr.height(), rr.arcWidth(), rr.arcHeight()); }
java
public static float pointLineDistSq (float px, float py, float x1, float y1, float x2, float y2) { x2 -= x1; y2 -= y1; px -= x1; py -= y1; float s = px * y2 - py * x2; return (s * s) / (x2 * x2 + y2 * y2); }
java
public static float pointLineDist (float px, float py, float x1, float y1, float x2, float y2) { return FloatMath.sqrt(pointLineDistSq(px, py, x1, y1, x2, y2)); }
java
public static float pointSegDistSq (float px, float py, float x1, float y1, float x2, float y2) { // A = (x2 - x1, y2 - y1) // P = (px - x1, py - y1) x2 -= x1; // A = (x2, y2) y2 -= y1; px -= x1; // P = (px, py) py -= y1; fl...
java
public static float pointSegDist (float px, float py, float x1, float y1, float x2, float y2) { return FloatMath.sqrt(pointSegDistSq(px, py, x1, y1, x2, y2)); }
java
public static ZrtpCacheEntry fromString(String key, String value) { String data = null; String number = null; int sep = value.indexOf(','); if (sep > 0) { data = value.substring(0, sep); number = value.substring(sep + 1); } else { data = value; number = ""; } byte[] buffer = new byt...
java
public void setLine (XY p1, XY p2) { setLine(p1.x(), p1.y(), p2.x(), p2.y()); }
java
public void setLine (float x1, float y1, float x2, float y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; }
java
public void addAccessPoint(String label, String ip, String port, String url, String dataType, String data) { AccessPoint ap = new AccessPoint(); ap.label = label; ap.ipAddress = ip; ap.port = port; ap.url = url; ap.dataType = dataType; ap.data = data; accessPoints.add(ap); }
java
public Matrix3 set (double[] values) { return set(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8]); }
java
public Matrix3 set ( double m00, double m10, double m20, double m01, double m11, double m21, double m02, double m12, double m22) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m2...
java
private String ipAddressFromURL(String url, String name) { String ipAddr = null; if (_urlValidator.isValid(url)) { WebTarget resolver = ClientBuilder.newClient().target(url); try { ipAddr = resolver.request().get(String.class); } catch (Exception e) { warn("URL Cannot Resolve ...
java
public RtpPacket protect(RtpPacket packet) { if (txSessEncKey == null) { log("protect() called out of session"); return null; } if (packet == null) { log("protect() called with null RTP packet"); return null; } int seqNum = packet.getSequenceNumber(); if (seqNum == 0) { // wrapped round r...
java
public int startNewSession() { if (txSessEncKey != null) return SESSION_ERROR_ALREADY_ACTIVE; if ((txMasterSalt == null) || (rxMasterSalt == null)) return SESSION_ERROR_MASTER_SALT_UDNEFINED; if ((txMasterKey == null) || (rxMasterKey == null)) return SESSION_ERROR_MASTER_SALT_UDNEFINED; if (!txSessionK...
java
public static boolean linesIntersect (double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { // A = (x2-x1, y2-y1) // B = (x3-x1, y3-y1) // C = (x4-x1, y4-y1) // D = (x4-x3, y4-y3) = C-B // E = (x1-x3, y...
java
public static boolean lineIntersectsRect (double x1, double y1, double x2, double y2, double rx, double ry, double rw, double rh) { double rr = rx + rw, rb = ry + rh; return (rx <= x1 && x1 <= rr && ry <= y1 && y1 <= rb) || (rx <= x2 && x2 <= rr ...
java
public Quaternion set (IQuaternion other) { return set(other.x(), other.y(), other.z(), other.w()); }
java
public Quaternion fromVectors (IVector3 from, IVector3 to) { float angle = from.angle(to); if (angle < MathUtil.EPSILON) { return set(IDENTITY); } if (angle <= FloatMath.PI - MathUtil.EPSILON) { return fromAngleAxis(angle, from.cross(to).normalizeLocal()); ...
java
public Quaternion fromAnglesXZ (float x, float z) { float hx = x * 0.5f, hz = z * 0.5f; float sx = FloatMath.sin(hx), cx = FloatMath.cos(hx); float sz = FloatMath.sin(hz), cz = FloatMath.cos(hz); return set(cz*sx, sz*sx, sz*cx, cz*cx); }
java
public Quaternion fromAnglesXY (float x, float y) { float hx = x * 0.5f, hy = y * 0.5f; float sx = FloatMath.sin(hx), cx = FloatMath.cos(hx); float sy = FloatMath.sin(hy), cy = FloatMath.cos(hy); return set(cy*sx, sy*cx, -sy*sx, cy*cx); }
java
public static float normalizeAnglePositive (float a) { while (a < 0f) { a += TWO_PI; } while (a >= TWO_PI) { a -= TWO_PI; } return a; }
java
public ProbeWrapper unmarshal(String payload) throws ProbeParseException { Probe xmlProbe = parseProbePayload(payload); ProbeWrapper probe = new ProbeWrapper(xmlProbe.getId()); probe.setClientId(xmlProbe.getClient()); probe.setDESVersion(xmlProbe.getDESVersion()); probe.setRespondToPayloadType(xmlP...
java
@Benchmark public void fizzbuzzConditional() { IntStream.range(0, 101).forEach( n -> { if (n % (3 * 5) == 0) { System.out.println("FizzBuzz"); } else if (n % 3 == 0) { System.out.println("Fizz"); } else if (n % 5 == 0) { System.out.println...
java
@Benchmark public void fizzBuzzPatternMatching() { IntStream.range(0, 101).forEach( n -> System.out.println( match(Tuple2.of(n % 3, n % 5)) .when(tuple2(eq(0), eq(0))).get(() -> "FizzBuzz") .when(tuple2(eq(0), any())).get(y -> "Fizz") .when(tuple...
java
public Quaternion set (double x, double y, double z, double w) { this.x = x; this.y = y; this.z = z; this.w = w; return this; }
java
public Quaternion fromAxes (IVector3 nx, IVector3 ny, IVector3 nz) { double nxx = nx.x(), nyy = ny.y(), nzz = nz.z(); double x2 = (1f + nxx - nyy - nzz)/4f; double y2 = (1f - nxx + nyy - nzz)/4f; double z2 = (1f - nxx - nyy + nzz)/4f; double w2 = (1f - x2 - y2 - z2); retu...
java
public static Point closestInteriorPoint (IRectangle r, IPoint p) { return closestInteriorPoint(r, p, new Point()); }
java
public boolean isRectangular () { return (_isPolygonal) && (_rulesSize <= 5) && (_coordsSize <= 8) && (_coords[1] == _coords[3]) && (_coords[7] == _coords[5]) && (_coords[0] == _coords[6]) && (_coords[2] == _coords[4]); }
java
public void add (Area area) { if (area == null || area.isEmpty()) { return; } else if (isEmpty()) { copy(area, this); return; } if (isPolygonal() && area.isPolygonal()) { addPolygon(area); } else { addCurvePolygon(area)...
java
public void intersect (Area area) { if (area == null) { return; } else if (isEmpty() || area.isEmpty()) { reset(); return; } if (isPolygonal() && area.isPolygonal()) { intersectPolygon(area); } else { intersectCurvePoly...
java
public void subtract (Area area) { if (area == null || isEmpty() || area.isEmpty()) { return; } if (isPolygonal() && area.isPolygonal()) { subtractPolygon(area); } else { subtractCurvePolygon(area); } if (areaBoundsSquare() < Geometry...
java
public void exclusiveOr (Area area) { Area a = clone(); a.intersect(area); add(area); subtract(a); }
java
private static double[] adjustSize (double[] array, int newSize) { if (newSize <= array.length) { return array; } double[] newArray = new double[2 * newSize]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; }
java
@GET @Path("/ipAddrInfo") public String getIPAddrInfo() throws UnknownHostException { Properties clientProps = getPropeSenderProps(); StringBuffer buf = new StringBuffer(); InetAddress localhost = null; NetworkInterface ni = null; try { localhost = InetAddress.getLocalHost(); LOGG...
java
@GET @Path("/launchProbe") @Produces("application/txt") public String launchProbe() throws IOException, UnsupportedPayloadType, ProbeSenderException, TransportException { Properties clientProps = getPropeSenderProps(); String multicastGroupAddr = clientProps.getProperty("multicastGroupAddr", DEFAULT_MUL...
java
@GET @Path("/responses") @Produces("application/json") public String getResponses() throws UnknownHostException { Properties clientProps = getPropeSenderProps(); String listenerIPAddress = clientProps.getProperty("listenerIPAddress"); String listenerPort = clientProps.getProperty("listenerPort"); ...
java
@GET @Path("/clearCache") @Produces("application/json") public String clearCache() throws UnknownHostException { Properties clientProps = getPropeSenderProps(); String listenerIPAddress = clientProps.getProperty("listenerIPAddress"); String listenerPort = clientProps.getProperty("listenerPort"); ...
java
public double distance (Vector3 point) { double distance = -Float.MAX_VALUE; for (Plane plane : _planes) { distance = Math.max(distance, plane.distance(point)); } return distance; }
java
public static Class<? extends Command<? extends CLIContext>> getCommandClass( CLIContext context, String commandName) { return context.getHostApplication().getCommands().get(commandName.toLowerCase()); }
java
public static <T> DecomposableMatchBuilder0<List<T>> nil() { List<Matcher<Object>> matchers = Lists.of(); return new DecomposableMatchBuilder0<List<T>>(matchers, new ListConsNilFieldExtractor<>()); }
java
public static void print(ConsoleLevel level, String message) { if (level.compareTo(_level) <= 0) { if (_printLogLevel) { level.getStream().println(level.name() + ": " + message); } else { level.getStream().println(message); } level.getStream().flush(); } }
java