_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q8500
HistogramStatistics.Mode
train
public static int Mode( int[] values ){ int mode = 0, curMax = 0; for ( int i = 0, length = values.length; i < length; i++ ) { if ( values[i] > curMax ) { curMax = values[i]; mode = i; } } return mode; }
java
{ "resource": "" }
q8501
HistogramStatistics.StdDev
train
public static double StdDev( int[] values, double mean ){ double stddev = 0; double diff; int hits; int total = 0; // for all values for ( int i = 0, n = values.length; i < n; i++ ) { hits = values[i]; diff = (double) i - mean; // accumulate std.dev. stddev += diff * diff * hits; // accumalate total total += hits; } return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) ); }
java
{ "resource": "" }
q8502
DiscreteCosineTransform.Forward
train
public static void Forward(double[] data) { double[] result = new double[data.length]; double sum; double scale = Math.sqrt(2.0 / data.length); for (int f = 0; f < data.length; f++) { sum = 0; for (int t = 0; t < data.length; t++) { double cos = Math.cos(((2.0 * t + 1.0) * f * Math.PI) / (2.0 * data.length)); sum += data[t] * cos * alpha(f); } result[f] = scale * sum; } for (int i = 0; i < data.length; i++) { data[i] = result[i]; } }
java
{ "resource": "" }
q8503
DiscreteCosineTransform.Forward
train
public static void Forward(double[][] data) { int rows = data.length; int cols = data[0].length; double[] row = new double[cols]; double[] col = new double[rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < row.length; j++) row[j] = data[i][j]; Forward(row); for (int j = 0; j < row.length; j++) data[i][j] = row[j]; } for (int j = 0; j < cols; j++) { for (int i = 0; i < col.length; i++) col[i] = data[i][j]; Forward(col); for (int i = 0; i < col.length; i++) data[i][j] = col[i]; } }
java
{ "resource": "" }
q8504
DiscreteCosineTransform.Backward
train
public static void Backward(double[] data) { double[] result = new double[data.length]; double sum; double scale = Math.sqrt(2.0 / data.length); for (int t = 0; t < data.length; t++) { sum = 0; for (int j = 0; j < data.length; j++) { double cos = Math.cos(((2 * t + 1) * j * Math.PI) / (2 * data.length)); sum += alpha(j) * data[j] * cos; } result[t] = scale * sum; } for (int i = 0; i < data.length; i++) { data[i] = result[i]; } }
java
{ "resource": "" }
q8505
LevelsLinear.setInRGB
train
public void setInRGB(IntRange inRGB) { this.inRed = inRGB; this.inGreen = inRGB; this.inBlue = inRGB; CalculateMap(inRGB, outRed, mapRed); CalculateMap(inRGB, outGreen, mapGreen); CalculateMap(inRGB, outBlue, mapBlue); }
java
{ "resource": "" }
q8506
LevelsLinear.setOutRGB
train
public void setOutRGB(IntRange outRGB) { this.outRed = outRGB; this.outGreen = outRGB; this.outBlue = outRGB; CalculateMap(inRed, outRGB, mapRed); CalculateMap(inGreen, outRGB, mapGreen); CalculateMap(inBlue, outRGB, mapBlue); }
java
{ "resource": "" }
q8507
LevelsLinear.CalculateMap
train
private void CalculateMap(IntRange inRange, IntRange outRange, int[] map) { double k = 0, b = 0; if (inRange.getMax() != inRange.getMin()) { k = (double) (outRange.getMax() - outRange.getMin()) / (double) (inRange.getMax() - inRange.getMin()); b = (double) (outRange.getMin()) - k * inRange.getMin(); } for (int i = 0; i < 256; i++) { int v = (int) i; if (v >= inRange.getMax()) v = outRange.getMax(); else if (v <= inRange.getMin()) v = outRange.getMin(); else v = (int) (k * v + b); map[i] = v; } }
java
{ "resource": "" }
q8508
ImageStatistics.Maximum
train
public static int Maximum(ImageSource fastBitmap, int startX, int startY, int width, int height) { int max = 0; if (fastBitmap.isGrayscale()) { for (int i = startX; i < height; i++) { for (int j = startY; j < width; j++) { int gray = fastBitmap.getRGB(j, i); if (gray > max) { max = gray; } } } } else { for (int i = startX; i < height; i++) { for (int j = startY; j < width; j++) { int gray = fastBitmap.getG(j, i); if (gray > max) { max = gray; } } } } return max; }
java
{ "resource": "" }
q8509
ImageStatistics.Minimum
train
public static int Minimum(ImageSource fastBitmap, int startX, int startY, int width, int height) { int min = 255; if (fastBitmap.isGrayscale()) { for (int i = startX; i < height; i++) { for (int j = startY; j < width; j++) { int gray = fastBitmap.getRGB(j, i); if (gray < min) { min = gray; } } } } else { for (int i = startX; i < height; i++) { for (int j = startY; j < width; j++) { int gray = fastBitmap.getG(j, i); if (gray < min) { min = gray; } } } } return min; }
java
{ "resource": "" }
q8510
Distance.Bhattacharyya
train
public static double Bhattacharyya(double[] histogram1, double[] histogram2) { int bins = histogram1.length; // histogram bins double b = 0; // Bhattacharyya's coefficient for (int i = 0; i < bins; i++) b += Math.sqrt(histogram1[i]) * Math.sqrt(histogram2[i]); // Bhattacharyya distance between the two distributions return Math.sqrt(1.0 - b); }
java
{ "resource": "" }
q8511
Distance.ChiSquare
train
public static double ChiSquare(double[] histogram1, double[] histogram2) { double r = 0; for (int i = 0; i < histogram1.length; i++) { double t = histogram1[i] + histogram2[i]; if (t != 0) r += Math.pow(histogram1[i] - histogram2[i], 2) / t; } return 0.5 * r; }
java
{ "resource": "" }
q8512
Distance.Correlation
train
public static double Correlation(double[] p, double[] q) { double x = 0; double y = 0; for (int i = 0; i < p.length; i++) { x += -p[i]; y += -q[i]; } x /= p.length; y /= q.length; double num = 0; double den1 = 0; double den2 = 0; for (int i = 0; i < p.length; i++) { num += (p[i] + x) * (q[i] + y); den1 += Math.abs(Math.pow(p[i] + x, 2)); den2 += Math.abs(Math.pow(q[i] + x, 2)); } return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2))); }
java
{ "resource": "" }
q8513
Distance.Hamming
train
public static int Hamming(String first, String second) { if (first.length() != second.length()) throw new IllegalArgumentException("The size of string must be the same."); int diff = 0; for (int i = 0; i < first.length(); i++) if (first.charAt(i) != second.charAt(i)) diff++; return diff; }
java
{ "resource": "" }
q8514
Distance.JaccardDistance
train
public static double JaccardDistance(double[] p, double[] q) { double distance = 0; int intersection = 0, union = 0; for (int x = 0; x < p.length; x++) { if ((p[x] != 0) || (q[x] != 0)) { if (p[x] == q[x]) { intersection++; } union++; } } if (union != 0) distance = 1.0 - ((double) intersection / (double) union); else distance = 0; return distance; }
java
{ "resource": "" }
q8515
Distance.JensenShannonDivergence
train
public static double JensenShannonDivergence(double[] p, double[] q) { double[] m = new double[p.length]; for (int i = 0; i < m.length; i++) { m[i] = (p[i] + q[i]) / 2; } return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2; }
java
{ "resource": "" }
q8516
Distance.KumarJohnsonDivergence
train
public static double KumarJohnsonDivergence(double[] p, double[] q) { double r = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { r += Math.pow(p[i] * p[i] - q[i] * q[i], 2) / 2 * Math.pow(p[i] * q[i], 1.5); } } return r; }
java
{ "resource": "" }
q8517
Distance.KullbackLeiblerDivergence
train
public static double KullbackLeiblerDivergence(double[] p, double[] q) { boolean intersection = false; double k = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { intersection = true; k += p[i] * Math.log(p[i] / q[i]); } } if (intersection) return k; else return Double.POSITIVE_INFINITY; }
java
{ "resource": "" }
q8518
Distance.SquaredEuclidean
train
public static double SquaredEuclidean(double[] x, double[] y) { double d = 0.0, u; for (int i = 0; i < x.length; i++) { u = x[i] - y[i]; d += u * u; } return d; }
java
{ "resource": "" }
q8519
Distance.SymmetricChiSquareDivergence
train
public static double SymmetricChiSquareDivergence(double[] p, double[] q) { double r = 0; for (int i = 0; i < p.length; i++) { double den = p[i] * q[i]; if (den != 0) { double p1 = p[i] - q[i]; double p2 = p[i] + q[i]; r += (p1 * p1 * p2) / den; } } return r; }
java
{ "resource": "" }
q8520
Distance.SymmetricKullbackLeibler
train
public static double SymmetricKullbackLeibler(double[] p, double[] q) { double dist = 0; for (int i = 0; i < p.length; i++) { dist += (p[i] - q[i]) * (Math.log(p[i]) - Math.log(q[i])); } return dist; }
java
{ "resource": "" }
q8521
Distance.Taneja
train
public static double Taneja(double[] p, double[] q) { double r = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { double pq = p[i] + q[i]; r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i]))); } } return r; }
java
{ "resource": "" }
q8522
Distance.TopsoeDivergence
train
public static double TopsoeDivergence(double[] p, double[] q) { double r = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { double den = p[i] + q[i]; r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den); } } return r; }
java
{ "resource": "" }
q8523
Triangle.contains
train
public boolean contains(Vector3 p) { boolean ans = false; if(this.halfplane || p== null) return false; if (isCorner(p)) { return true; } PointLinePosition a12 = PointLineTest.pointLineTest(a,b,p); PointLinePosition a23 = PointLineTest.pointLineTest(b,c,p); PointLinePosition a31 = PointLineTest.pointLineTest(c,a,p); if ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) || (a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) || (a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) { ans = true; } return ans; }
java
{ "resource": "" }
q8524
Triangle.calcDet
train
public static float calcDet(Vector3 a ,Vector3 b, Vector3 c) { return (a.x*(b.y-c.y)) - (a.y*(b.x-c.x)) + (b.x*c.y-b.y*c.x); }
java
{ "resource": "" }
q8525
Triangle.sharedSegments
train
public int sharedSegments(Triangle t2) { int counter = 0; if(a.equals(t2.a)) { counter++; } if(a.equals(t2.b)) { counter++; } if(a.equals(t2.c)) { counter++; } if(b.equals(t2.a)) { counter++; } if(b.equals(t2.b)) { counter++; } if(b.equals(t2.c)) { counter++; } if(c.equals(t2.a)) { counter++; } if(c.equals(t2.b)) { counter++; } if(c.equals(t2.c)) { counter++; } return counter; }
java
{ "resource": "" }
q8526
BinaryErosion.apply
train
@Override public ImageSource apply(ImageSource source) { if (radius != 0) { if (source.isGrayscale()) { return applyGrayscale(source, radius); } else { return applyRGB(source, radius); } } else { if (source.isGrayscale()) { return applyGrayscale(source, kernel); } else { return applyRGB(source, kernel); } } }
java
{ "resource": "" }
q8527
ApiClient.handleResponse
train
public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } }
java
{ "resource": "" }
q8528
IIMFile.add
train
public void add(int ds, Object value) throws SerializationException, InvalidDataSetException { if (value == null) { return; } DataSetInfo dsi = dsiFactory.create(ds); byte[] data = dsi.getSerializer().serialize(value, activeSerializationContext); DataSet dataSet = new DefaultDataSet(dsi, data); dataSets.add(dataSet); }
java
{ "resource": "" }
q8529
IIMFile.addDateTimeHelper
train
public void addDateTimeHelper(int ds, Date date) throws SerializationException, InvalidDataSetException { if (date == null) { return; } DataSetInfo dsi = dsiFactory.create(ds); SimpleDateFormat df = new SimpleDateFormat(dsi.getSerializer().toString()); String value = df.format(date); byte[] data = dsi.getSerializer().serialize(value, activeSerializationContext); DataSet dataSet = new DefaultDataSet(dsi, data); add(dataSet); }
java
{ "resource": "" }
q8530
IIMFile.get
train
public Object get(int dataSet) throws SerializationException { Object result = null; for (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) { DataSet ds = i.next(); DataSetInfo info = ds.getInfo(); if (info.getDataSetNumber() == dataSet) { result = getData(ds); break; } } return result; }
java
{ "resource": "" }
q8531
IIMFile.getAll
train
public List<Object> getAll(int dataSet) throws SerializationException { List<Object> result = new ArrayList<Object>(); for (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) { DataSet ds = i.next(); DataSetInfo info = ds.getInfo(); if (info.getDataSetNumber() == dataSet) { result.add(getData(ds)); } } return result; }
java
{ "resource": "" }
q8532
IIMFile.readFrom
train
public void readFrom(IIMReader reader, int recover) throws IOException, InvalidDataSetException { final boolean doLog = log != null; for (;;) { try { DataSet ds = reader.read(); if (ds == null) { break; } if (doLog) { log.debug("Read data set " + ds); } DataSetInfo info = ds.getInfo(); Serializer s = info.getSerializer(); if (s != null) { if (info.getDataSetNumber() == IIM.DS(1, 90)) { setCharacterSet((String) s.deserialize(ds.getData(), activeSerializationContext)); } } dataSets.add(ds); if (stopAfter9_10 && info.getDataSetNumber() == IIM.DS(9, 10)) break; } catch (IIMFormatException e) { if (recoverFromIIMFormat && recover-- > 0) { boolean r = reader.recover(); if (doLog) { log.debug(r ? "Recoved from " + e : "Failed to recover from " + e); } if (!r) break; } else { throw e; } } catch (UnsupportedDataSetException e) { if (recoverFromUnsupportedDataSet && recover-- > 0) { boolean r = reader.recover(); if (doLog) { log.debug(r ? "Recoved from " + e : "Failed to recover from " + e); } if (!r) break; } else { throw e; } } catch (InvalidDataSetException e) { if (recoverFromInvalidDataSet && recover-- > 0) { boolean r = reader.recover(); if (doLog) { log.debug(r ? "Recoved from " + e : "Failed to recover from " + e); } if (!r) break; } else { throw e; } } catch (IOException e) { if (recover-- > 0 && !dataSets.isEmpty()) { if (doLog) { log.error("IOException while reading, however some data sets where recovered, " + e); } return; } else { throw e; } } } }
java
{ "resource": "" }
q8533
IIMFile.writeTo
train
public void writeTo(IIMWriter writer) throws IOException { final boolean doLog = log != null; for (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) { DataSet ds = i.next(); writer.write(ds); if (doLog) { log.debug("Wrote data set " + ds); } } }
java
{ "resource": "" }
q8534
IIMFile.validate
train
public Set<ConstraintViolation> validate(DataSetInfo info) { Set<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>(); try { if (info.isMandatory() && get(info.getDataSetNumber()) == null) { errors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING)); } if (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) { errors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED)); } } catch (SerializationException e) { errors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE)); } return errors; }
java
{ "resource": "" }
q8535
IIMFile.validate
train
public Set<ConstraintViolation> validate(int record) { Set<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>(); for (int ds = 0; ds < 250; ++ds) { try { DataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds)); errors.addAll(validate(dataSetInfo)); } catch (InvalidDataSetException ignored) { // DataSetFactory doesn't know about this ds, so will skip it } } return errors; }
java
{ "resource": "" }
q8536
IIMFile.validate
train
public Set<ConstraintViolation> validate() { Set<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>(); for (int record = 1; record <= 3; ++record) { errors.addAll(validate(record)); } return errors; }
java
{ "resource": "" }
q8537
PointComparator.compare
train
public int compare(Vector3 o1, Vector3 o2) { int ans = 0; if (o1 != null && o2 != null) { Vector3 d1 = o1; Vector3 d2 = o2; if (d1.x > d2.x) return 1; if (d1.x < d2.x) return -1; // x1 == x2 if (d1.y > d2.y) return 1; if (d1.y < d2.y) return -1; } else { if (o1 == null && o2 == null) return 0; if (o1 == null && o2 != null) return 1; if (o1 != null && o2 == null) return -1; } return ans; }
java
{ "resource": "" }
q8538
Random.nextDouble
train
public double nextDouble(double lo, double hi) { if (lo < 0) { if (nextInt(2) == 0) return -nextDouble(0, -lo); else return nextDouble(0, hi); } else { return (lo + (hi - lo) * nextDouble()); } }
java
{ "resource": "" }
q8539
TagsApi.getTagCategoriesWithHttpInfo
train
public ApiResponse<TagsEnvelope> getTagCategoriesWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = getTagCategoriesValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<TagsEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
{ "resource": "" }
q8540
RulesApi.getRule
train
public RuleEnvelope getRule(String ruleId) throws ApiException { ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId); return resp.getData(); }
java
{ "resource": "" }
q8541
FloodFillSearch.addNeighbor
train
protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) { if (!inBoundary(px, py, component)) { return; } if (!mask.isTouched(px, py)) { queue.add(new ColorPoint(px, py, color)); } }
java
{ "resource": "" }
q8542
Gaussian.Function1D
train
public double Function1D(double x) { return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma); }
java
{ "resource": "" }
q8543
Gaussian.Function2D
train
public double Function2D(double x, double y) { return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma); }
java
{ "resource": "" }
q8544
Gaussian.Kernel1D
train
public double[] Kernel1D(int size) { if (((size % 2) == 0) || (size < 3) || (size > 101)) { try { throw new Exception("Wrong size"); } catch (Exception e) { e.printStackTrace(); } } int r = size / 2; // kernel double[] kernel = new double[size]; // compute kernel for (int x = -r, i = 0; i < size; x++, i++) { kernel[i] = Function1D(x); } return kernel; }
java
{ "resource": "" }
q8545
Gaussian.Kernel2D
train
public double[][] Kernel2D(int size) { if (((size % 2) == 0) || (size < 3) || (size > 101)) { try { throw new Exception("Wrong size"); } catch (Exception e) { e.printStackTrace(); } } int r = size / 2; double[][] kernel = new double[size][size]; // compute kernel double sum = 0; for (int y = -r, i = 0; i < size; y++, i++) { for (int x = -r, j = 0; j < size; x++, j++) { kernel[i][j] = Function2D(x, y); sum += kernel[i][j]; } } for (int i = 0; i < kernel.length; i++) { for (int j = 0; j < kernel[0].length; j++) { kernel[i][j] /= sum; } } return kernel; }
java
{ "resource": "" }
q8546
ExtractBoundary.process
train
public ArrayList<IntPoint> process(ImageSource fastBitmap) { //FastBitmap l = new FastBitmap(fastBitmap); if (points == null) { apply(fastBitmap); } int width = fastBitmap.getWidth(); int height = fastBitmap.getHeight(); points = new ArrayList<IntPoint>(); if (fastBitmap.isGrayscale()) { for (int x = 0; x < height; x++) { for (int y = 0; y < width; y++) { if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x)); } } } else { for (int x = 0; x < height; x++) { for (int y = 0; y < width; y++) { // TODO Check for green and blue? if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x)); } } } return points; }
java
{ "resource": "" }
q8547
DiscreteHartleyTransform.Forward
train
public static void Forward(double[] data) { double[] result = new double[data.length]; for (int k = 0; k < result.length; k++) { double sum = 0; for (int n = 0; n < data.length; n++) { double theta = ((2.0 * Math.PI) / data.length) * k * n; sum += data[n] * cas(theta); } result[k] = (1.0 / Math.sqrt(data.length)) * sum; } for (int i = 0; i < result.length; i++) { data[i] = result[i]; } }
java
{ "resource": "" }
q8548
DiscreteHartleyTransform.Forward
train
public static void Forward(double[][] data) { double[][] result = new double[data.length][data[0].length]; for (int m = 0; m < data.length; m++) { for (int n = 0; n < data[0].length; n++) { double sum = 0; for (int i = 0; i < result.length; i++) { for (int k = 0; k < data.length; k++) { sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n)); } result[m][n] = (1.0 / data.length) * sum; } } } for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[0].length; j++) { data[i][j] = result[i][j]; } } }
java
{ "resource": "" }
q8549
UsersApi.createUserProperties
train
public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException { ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid); return resp.getData(); }
java
{ "resource": "" }
q8550
UsersApi.getUserProperties
train
public PropertiesEnvelope getUserProperties(String userId, String aid) throws ApiException { ApiResponse<PropertiesEnvelope> resp = getUserPropertiesWithHttpInfo(userId, aid); return resp.getData(); }
java
{ "resource": "" }
q8551
AbstractListenerStore.copyList
train
protected <T extends Listener> Collection<T> copyList(Class<T> listenerClass, Stream<Object> listeners, int sizeHint) { if (sizeHint == 0) { return Collections.emptyList(); } return listeners .map(listenerClass::cast) .collect(Collectors.toCollection(() -> new ArrayList<>(sizeHint))); }
java
{ "resource": "" }
q8552
DBScan.cluster
train
public List<Cluster> cluster(final Collection<Point2D> points) { final List<Cluster> clusters = new ArrayList<Cluster>(); final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>(); KDTree<Point2D> tree = new KDTree<Point2D>(2); // Populate the kdTree for (final Point2D point : points) { double[] key = {point.x, point.y}; tree.insert(key, point); } for (final Point2D point : points) { if (visited.get(point) != null) { continue; } final List<Point2D> neighbors = getNeighbors(point, tree); if (neighbors.size() >= minPoints) { // DBSCAN does not care about center points final Cluster cluster = new Cluster(clusters.size()); clusters.add(expandCluster(cluster, point, neighbors, tree, visited)); } else { visited.put(point, PointStatus.NOISE); } } for (Cluster cluster : clusters) { cluster.calculateCentroid(); } return clusters; }
java
{ "resource": "" }
q8553
DBScan.expandCluster
train
private Cluster expandCluster(final Cluster cluster, final Point2D point, final List<Point2D> neighbors, final KDTree<Point2D> points, final Map<Point2D, PointStatus> visited) { cluster.addPoint(point); visited.put(point, PointStatus.PART_OF_CLUSTER); List<Point2D> seeds = new ArrayList<Point2D>(neighbors); int index = 0; while (index < seeds.size()) { Point2D current = seeds.get(index); PointStatus pStatus = visited.get(current); // only check non-visited points if (pStatus == null) { final List<Point2D> currentNeighbors = getNeighbors(current, points); if (currentNeighbors.size() >= minPoints) { seeds = merge(seeds, currentNeighbors); } } if (pStatus != PointStatus.PART_OF_CLUSTER) { visited.put(current, PointStatus.PART_OF_CLUSTER); cluster.addPoint(current); } index++; } return cluster; }
java
{ "resource": "" }
q8554
DBScan.merge
train
private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) { final Set<Point2D> oneSet = new HashSet<Point2D>(one); for (Point2D item : two) { if (!oneSet.contains(item)) { one.add(item); } } return one; }
java
{ "resource": "" }
q8555
LetterSeparation.apply
train
public ImageSource apply(ImageSource input) { ImageSource originalImage = input; int width = originalImage.getWidth(); int height = originalImage.getHeight(); boolean[][] matrix = new boolean[width][height]; // black n white boolean matrix; true = blck, false = white // Copy ImageSource filteredImage = new MatrixSource(input); int[] histogram = OtsuBinarize.imageHistogram(originalImage); int totalNumberOfpixels = height * width; int threshold = OtsuBinarize.threshold(histogram, totalNumberOfpixels); int black = 0; int white = 255; int gray; int alpha; int newColor; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { gray = originalImage.getGray(i, j); if (gray > threshold) { matrix[i][j] = false; } else { matrix[i][j] = true; } } } int blackTreshold = letterThreshold(originalImage, matrix); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { gray = originalImage.getGray(i, j); alpha = originalImage.getA(i, j); if (gray > blackTreshold) { newColor = white; } else { newColor = black; } newColor = ColorHelper.getARGB(newColor, newColor, newColor, alpha); filteredImage.setRGB(i, j, newColor); } } return filteredImage; }
java
{ "resource": "" }
q8556
ArraysUtil.Argsort
train
public static int[] Argsort(final float[] array, final boolean ascending) { Integer[] indexes = new Integer[array.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i; } Arrays.sort(indexes, new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]); } }); return asArray(indexes); }
java
{ "resource": "" }
q8557
ArraysUtil.Concatenate
train
public static int[] Concatenate(int[] array, int[] array2) { int[] all = new int[array.length + array2.length]; int idx = 0; //First array for (int i = 0; i < array.length; i++) all[idx++] = array[i]; //Second array for (int i = 0; i < array2.length; i++) all[idx++] = array2[i]; return all; }
java
{ "resource": "" }
q8558
ArraysUtil.ConcatenateInt
train
public static int[] ConcatenateInt(List<int[]> arrays) { int size = 0; for (int i = 0; i < arrays.size(); i++) { size += arrays.get(i).length; } int[] all = new int[size]; int idx = 0; for (int i = 0; i < arrays.size(); i++) { int[] v = arrays.get(i); for (int j = 0; j < v.length; j++) { all[idx++] = v[i]; } } return all; }
java
{ "resource": "" }
q8559
ArraysUtil.asArray
train
public static <T extends Number> int[] asArray(final T... array) { int[] b = new int[array.length]; for (int i = 0; i < b.length; i++) { b[i] = array[i].intValue(); } return b; }
java
{ "resource": "" }
q8560
ArraysUtil.Shuffle
train
public static void Shuffle(double[] array, long seed) { Random random = new Random(); if (seed != 0) random.setSeed(seed); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); double temp = array[index]; array[index] = array[i]; array[i] = temp; } }
java
{ "resource": "" }
q8561
ArraysUtil.toFloat
train
public static float[] toFloat(int[] array) { float[] n = new float[array.length]; for (int i = 0; i < array.length; i++) { n[i] = (float) array[i]; } return n; }
java
{ "resource": "" }
q8562
ArraysUtil.toFloat
train
public static float[][] toFloat(int[][] array) { float[][] n = new float[array.length][array[0].length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { n[i][j] = (float) array[i][j]; } } return n; }
java
{ "resource": "" }
q8563
ArraysUtil.toInt
train
public static int[] toInt(double[] array) { int[] n = new int[array.length]; for (int i = 0; i < array.length; i++) { n[i] = (int) array[i]; } return n; }
java
{ "resource": "" }
q8564
ArraysUtil.toInt
train
public static int[][] toInt(double[][] array) { int[][] n = new int[array.length][array[0].length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { n[i][j] = (int) array[i][j]; } } return n; }
java
{ "resource": "" }
q8565
ArraysUtil.toDouble
train
public static double[] toDouble(int[] array) { double[] n = new double[array.length]; for (int i = 0; i < array.length; i++) { n[i] = (double) array[i]; } return n; }
java
{ "resource": "" }
q8566
ArraysUtil.toDouble
train
public static double[][] toDouble(int[][] array) { double[][] n = new double[array.length][array[0].length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { n[i][j] = (double) array[i][j]; } } return n; }
java
{ "resource": "" }
q8567
TokensApi.tokenInfoWithHttpInfo
train
public ApiResponse<TokenInfoSuccessResponse> tokenInfoWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = tokenInfoValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<TokenInfoSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
{ "resource": "" }
q8568
Normal.HighAccuracyFunction
train
public static double HighAccuracyFunction(double x) { if (x < -8 || x > 8) return 0; double sum = x; double term = 0; double nextTerm = x; double pwr = x * x; double i = 1; // Iterate until adding next terms doesn't produce // any change within the current numerical accuracy. while (sum != term) { term = sum; // Next term nextTerm *= pwr / (i += 2); sum += nextTerm; } return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI); }
java
{ "resource": "" }
q8569
Normal.HighAccuracyComplemented
train
public static double HighAccuracyComplemented(double x) { double[] R = { 1.25331413731550025, 0.421369229288054473, 0.236652382913560671, 0.162377660896867462, 0.123131963257932296, 0.0990285964717319214, 0.0827662865013691773, 0.0710695805388521071, 0.0622586659950261958 }; int j = (int) (0.5 * (Math.abs(x) + 1)); double a = R[j]; double z = 2 * j; double b = a * z - 1; double h = Math.abs(x) - z; double q = h * h; double pwr = 1; double sum = a + h * b; double term = a; for (int i = 2; sum != term; i += 2) { term = sum; a = (a + z * b) / (i); b = (b + z * a) / (i + 1); pwr *= q; sum = term + pwr * (a + h * b); } sum *= Math.exp(-0.5 * (x * x) - 0.5 * Constants.Log2PI); return (x >= 0) ? sum : (1.0 - sum); }
java
{ "resource": "" }
q8570
SubjectReference.toIPTC
train
public String toIPTC(SubjectReferenceSystem srs) { StringBuffer b = new StringBuffer(); b.append("IPTC:"); b.append(getNumber()); b.append(":"); if (getNumber().endsWith("000000")) { b.append(toIPTCHelper(srs.getName(this))); b.append("::"); } else if (getNumber().endsWith("000")) { b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + "000000")))); b.append(":"); b.append(toIPTCHelper(srs.getName(this))); b.append(":"); } else { b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + "000000")))); b.append(":"); b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + "000")))); b.append(":"); b.append(toIPTCHelper(srs.getName(this))); } return b.toString(); }
java
{ "resource": "" }
q8571
IIMDataSetInfoFactory.create
train
public DataSetInfo create(int dataSet) throws InvalidDataSetException { DataSetInfo info = dataSets.get(createKey(dataSet)); if (info == null) { int recordNumber = (dataSet >> 8) & 0xFF; int dataSetNumber = dataSet & 0xFF; throw new UnsupportedDataSetException(recordNumber + ":" + dataSetNumber); // info = super.create(dataSet); } return info; }
java
{ "resource": "" }
q8572
PerlinNoise.Function1D
train
public double Function1D(double x) { double frequency = initFrequency; double amplitude = initAmplitude; double sum = 0; // octaves for (int i = 0; i < octaves; i++) { sum += SmoothedNoise(x * frequency) * amplitude; frequency *= 2; amplitude *= persistence; } return sum; }
java
{ "resource": "" }
q8573
PerlinNoise.Function2D
train
public double Function2D(double x, double y) { double frequency = initFrequency; double amplitude = initAmplitude; double sum = 0; // octaves for (int i = 0; i < octaves; i++) { sum += SmoothedNoise(x * frequency, y * frequency) * amplitude; frequency *= 2; amplitude *= persistence; } return sum; }
java
{ "resource": "" }
q8574
PerlinNoise.Noise
train
private double Noise(int x, int y) { int n = x + y * 57; n = (n << 13) ^ n; return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0); }
java
{ "resource": "" }
q8575
PerlinNoise.CosineInterpolate
train
private double CosineInterpolate(double x1, double x2, double a) { double f = (1 - Math.cos(a * Math.PI)) * 0.5; return x1 * (1 - f) + x2 * f; }
java
{ "resource": "" }
q8576
FailureCollector.getFailedInvocations
train
public List<FailedEventInvocation> getFailedInvocations() { synchronized (this.mutex) { if (this.failedEvents == null) { return Collections.emptyList(); } return Collections.unmodifiableList(this.failedEvents); } }
java
{ "resource": "" }
q8577
SequentialEvent.getPrevented
train
public Set<Class<?>> getPrevented() { if (this.prevent == null) { return Collections.emptySet(); } return Collections.unmodifiableSet(this.prevent); }
java
{ "resource": "" }
q8578
Gabor.Function1D
train
public static double Function1D(double x, double mean, double amplitude, double position, double width, double phase, double frequency) { double envelope = mean + amplitude * Math.exp(-Math.pow((x - position), 2) / Math.pow((2 * width), 2)); double carry = Math.cos(2 * Math.PI * frequency * (x - position) + phase); return envelope * carry; }
java
{ "resource": "" }
q8579
Gabor.Function2D
train
public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) { double X = x * Math.cos(orientation) + y * Math.sin(orientation); double Y = -x * Math.sin(orientation) + y * Math.cos(orientation); double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance))); double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset); double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset); return new ComplexNumber(envelope * real, envelope * imaginary); }
java
{ "resource": "" }
q8580
LocalTaskExecutorService.getOldestTaskCreatedTime
train
public Long getOldestTaskCreatedTime(){ Timer.Context ctx = getOldestTaskTimeTimer.time(); try { long oldest = Long.MAX_VALUE; /* * I am asking this question first, because if I ask it after I could * miss the oldest time if the oldest is polled and worked on */ Long oldestQueueTime = this.taskQueue.getOldestQueueTime(); if(oldestQueueTime != null) oldest = oldestQueueTime; //there is a tiny race condition here... but we just want to make our best attempt long inProgressOldestTime = tasksInProgressTracker.getOldestTime(); if(inProgressOldestTime < oldest) oldest = inProgressOldestTime; return oldest; } finally { ctx.stop(); } }
java
{ "resource": "" }
q8581
LocalTaskExecutorService.shutdownNow
train
@SuppressWarnings({ "unchecked", "rawtypes" }) public List<HazeltaskTask<G>> shutdownNow() { return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow(); }
java
{ "resource": "" }
q8582
ExecutorMetrics.registerCollectionSizeGauge
train
public void registerCollectionSizeGauge( CollectionSizeGauge collectionSizeGauge) { String name = createMetricName(LocalTaskExecutorService.class, "queue-size"); metrics.register(name, collectionSizeGauge); }
java
{ "resource": "" }
q8583
ExecutorLoadBalancingConfig.useLoadBalancedEnumOrdinalPrioritizer
train
public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) { if(!groupClass.isEnum()) { throw new IllegalArgumentException("The group class "+groupClass+" is not an enum"); } groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>()); return this; }
java
{ "resource": "" }
q8584
ExecutorConfigs.basicGroupable
train
public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() { return new ExecutorConfig<GROUP>() .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>()); }
java
{ "resource": "" }
q8585
ShutdownOp.call
train
public Collection<HazeltaskTask<GROUP>> call() throws Exception { try { if(isShutdownNow) return this.getDistributedExecutorService().shutdownNowWithHazeltask(); else this.getDistributedExecutorService().shutdown(); } catch(IllegalStateException e) {} return Collections.emptyList(); }
java
{ "resource": "" }
q8586
MemberTasks.executeOptimistic
train
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) { return executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS); }
java
{ "resource": "" }
q8587
MemberTasks.executeOptimistic
train
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) { Collection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size()); Map<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members); for(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) { Future<T> future = futureEntry.getValue(); Member member = futureEntry.getKey(); try { if(maxWaitTime > 0) { result.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit))); } else { result.add(new MemberResponse<T>(member, future.get())); } //ignore exceptions... return what you can } catch (InterruptedException e) { Thread.currentThread().interrupt(); //restore interrupted status and return what we have return result; } catch (MemberLeftException e) { log.warn("Member {} left while trying to get a distributed callable result", member); } catch (ExecutionException e) { if(e.getCause() instanceof InterruptedException) { //restore interrupted state and return Thread.currentThread().interrupt(); return result; } else { log.warn("Unable to execute callable on "+member+". There was an error.", e); } } catch (TimeoutException e) { log.error("Unable to execute task on "+member+" within 10 seconds."); } catch (RuntimeException e) { log.error("Unable to execute task on "+member+". An unexpected error occurred.", e); } } return result; }
java
{ "resource": "" }
q8588
DistributedFutureTracker.createFuture
train
@SuppressWarnings("unchecked") public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) { DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId()); this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future); return future; }
java
{ "resource": "" }
q8589
DistributedFutureTracker.errorFuture
train
public void errorFuture(UUID taskId, Exception e) { DistributedFuture<GROUP, Serializable> future = remove(taskId); if(future != null) { future.setException(e); } }
java
{ "resource": "" }
q8590
BackoffTimer.schedule
train
public void schedule(BackoffTask task, long initialDelay, long fixedDelay) { synchronized (queue) { start(); queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay)); } }
java
{ "resource": "" }
q8591
HazelcastExecutorTopologyService.addPendingTaskAsync
train
public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) { return pendingTask.putAsync(task.getId(), task); }
java
{ "resource": "" }
q8592
XMLDSigCreator.applyXMLDSigAsFirstChild
train
public void applyXMLDSigAsFirstChild (@Nonnull final PrivateKey aPrivateKey, @Nonnull final X509Certificate aCertificate, @Nonnull final Document aDocument) throws Exception { ValueEnforcer.notNull (aPrivateKey, "privateKey"); ValueEnforcer.notNull (aCertificate, "certificate"); ValueEnforcer.notNull (aDocument, "document"); ValueEnforcer.notNull (aDocument.getDocumentElement (), "Document is missing a document element"); if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0) throw new IllegalArgumentException ("Document element has no children!"); // Check that the document does not contain another Signature element final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE); if (aNodeList.getLength () > 0) throw new IllegalArgumentException ("Document already contains an XMLDSig Signature element!"); // Create the XMLSignature, but don't sign it yet. final XMLSignature aXMLSignature = createXMLSignature (aCertificate); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. // -> The signature is always the first child element of the document // element for ebInterface final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey, aDocument.getDocumentElement (), aDocument.getDocumentElement ().getFirstChild ()); // The namespace prefix to be used for the signed XML aDOMSignContext.setDefaultNamespacePrefix (DEFAULT_NS_PREFIX); // Marshal, generate, and sign the enveloped signature. aXMLSignature.sign (aDOMSignContext); }
java
{ "resource": "" }
q8593
MyMapUtils.rankMapOnIntegerValue
train
public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) { Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap)); newMap.putAll(inputMap); Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap); return linkedMap; }
java
{ "resource": "" }
q8594
ZWaveController.handleIncomingMessage
train
private void handleIncomingMessage(SerialMessage incomingMessage) { logger.debug("Incoming message to process"); logger.debug(incomingMessage.toString()); switch (incomingMessage.getMessageType()) { case Request: handleIncomingRequestMessage(incomingMessage); break; case Response: handleIncomingResponseMessage(incomingMessage); break; default: logger.warn("Unsupported incomingMessageType: 0x%02X", incomingMessage.getMessageType()); } }
java
{ "resource": "" }
q8595
ZWaveController.handleIncomingRequestMessage
train
private void handleIncomingRequestMessage(SerialMessage incomingMessage) { logger.debug("Message type = REQUEST"); switch (incomingMessage.getMessageClass()) { case ApplicationCommandHandler: handleApplicationCommandRequest(incomingMessage); break; case SendData: handleSendDataRequest(incomingMessage); break; case ApplicationUpdate: handleApplicationUpdateRequest(incomingMessage); break; default: logger.warn(String.format("TODO: Implement processing of Request Message = %s (0x%02X)", incomingMessage.getMessageClass().getLabel(), incomingMessage.getMessageClass().getKey())); break; } }
java
{ "resource": "" }
q8596
ZWaveController.handleApplicationCommandRequest
train
private void handleApplicationCommandRequest(SerialMessage incomingMessage) { logger.trace("Handle Message Application Command Request"); int nodeId = incomingMessage.getMessagePayloadByte(1); logger.debug("Application Command Request from Node " + nodeId); ZWaveNode node = getNode(nodeId); if (node == null) { logger.warn("Node {} not initialized yet, ignoring message.", nodeId); return; } node.resetResendCount(); int commandClassCode = incomingMessage.getMessagePayloadByte(3); ZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode); if (commandClass == null) { logger.error(String.format("Unsupported command class 0x%02x", commandClassCode)); return; } logger.debug(String.format("Incoming command class %s (0x%02x)", commandClass.getLabel(), commandClass.getKey())); ZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass); // We got an unsupported command class, return. if (zwaveCommandClass == null) { logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode)); return; } logger.trace("Found Command Class {}, passing to handleApplicationCommandRequest", zwaveCommandClass.getCommandClass().getLabel()); zwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1); if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) { notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage)); transactionCompleted.release(); logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits()); } }
java
{ "resource": "" }
q8597
ZWaveController.handleSendDataRequest
train
private void handleSendDataRequest(SerialMessage incomingMessage) { logger.trace("Handle Message Send Data Request"); int callbackId = incomingMessage.getMessagePayloadByte(0); TransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1)); SerialMessage originalMessage = this.lastSentMessage; if (status == null) { logger.warn("Transmission state not found, ignoring."); return; } logger.debug("CallBack ID = {}", callbackId); logger.debug(String.format("Status = %s (0x%02x)", status.getLabel(), status.getKey())); if (originalMessage == null || originalMessage.getCallbackId() != callbackId) { logger.warn("Already processed another send data request for this callback Id, ignoring."); return; } switch (status) { case COMPLETE_OK: ZWaveNode node = this.getNode(originalMessage.getMessageNode()); node.resetResendCount(); // in case we received a ping response and the node is alive, we proceed with the next node stage for this node. if (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) { node.advanceNodeStage(); } if (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) { notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage)); transactionCompleted.release(); logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits()); } return; case COMPLETE_NO_ACK: case COMPLETE_FAIL: case COMPLETE_NOT_IDLE: case COMPLETE_NOROUTE: try { handleFailedSendDataRequest(originalMessage); } finally { transactionCompleted.release(); logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits()); } default: } }
java
{ "resource": "" }
q8598
ZWaveController.handleFailedSendDataRequest
train
private void handleFailedSendDataRequest(SerialMessage originalMessage) { ZWaveNode node = this.getNode(originalMessage.getMessageNode()); if (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD) return; if (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) { ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP); if (wakeUpCommandClass != null) { wakeUpCommandClass.setAwake(false); wakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue. return; } } else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low) return; node.incrementResendCount(); logger.error("Got an error while sending data to node {}. Resending message.", node.getNodeId()); this.sendData(originalMessage); }
java
{ "resource": "" }
q8599
ZWaveController.handleApplicationUpdateRequest
train
private void handleApplicationUpdateRequest(SerialMessage incomingMessage) { logger.trace("Handle Message Application Update Request"); int nodeId = incomingMessage.getMessagePayloadByte(1); logger.trace("Application Update Request from Node " + nodeId); UpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0)); switch (updateState) { case NODE_INFO_RECEIVED: logger.debug("Application update request, node information received."); int length = incomingMessage.getMessagePayloadByte(2); ZWaveNode node = getNode(nodeId); node.resetResendCount(); for (int i = 6; i < length + 3; i++) { int data = incomingMessage.getMessagePayloadByte(i); if(data == 0xef ) { // TODO: Implement control command classes break; } logger.debug(String.format("Adding command class 0x%02X to the list of supported command classes.", data)); ZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this); if (commandClass != null) node.addCommandClass(commandClass); } // advance node stage. node.advanceNodeStage(); if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) { notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage)); transactionCompleted.release(); logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits()); } break; case NODE_INFO_REQ_FAILED: logger.debug("Application update request, Node Info Request Failed, re-request node info."); SerialMessage requestInfoMessage = this.lastSentMessage; if (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) { logger.warn("Got application update request without node info request, ignoring."); return; } if (--requestInfoMessage.attempts >= 0) { logger.error("Got Node Info Request Failed while sending this serial message. Requeueing"); this.enqueue(requestInfoMessage); } else { logger.warn("Node Info Request Failed 3x. Discarding message: {}", lastSentMessage.toString()); } transactionCompleted.release(); break; default: logger.warn(String.format("TODO: Implement Application Update Request Handling of %s (0x%02X).", updateState.getLabel(), updateState.getKey())); } }
java
{ "resource": "" }