List of usage examples for java.lang Integer compare
public static int compare(int x, int y)
From source file:org.apache.hyracks.maven.license.LicenseMojo.java
private void addDependencyToLicenseMap(MavenProject depProject, List<Pair<String, String>> depLicenses, String depLocation) {/*from w w w. j a v a 2 s . c o m*/ final String depGav = toGav(depProject); getLog().debug("adding " + depGav + ", location: " + depLocation); final MutableBoolean usedMetric = new MutableBoolean(false); if (depLicenses.size() > 1) { Collections.sort(depLicenses, (o1, o2) -> { final int metric1 = getLicenseMetric(o1.getLeft()); final int metric2 = getLicenseMetric(o2.getLeft()); usedMetric.setValue(usedMetric.booleanValue() || metric1 != LicenseSpec.UNDEFINED_LICENSE_METRIC || metric2 != LicenseSpec.UNDEFINED_LICENSE_METRIC); return Integer.compare(metric1, metric2); }); if (usedMetric.booleanValue()) { getLog().info("Multiple licenses for " + depGav + ": " + depLicenses + "; taking lowest metric: " + depLicenses.get(0)); } else { getLog().warn("Multiple licenses for " + depGav + ": " + depLicenses + "; taking first listed: " + depLicenses.get(0)); } } else if (depLicenses.isEmpty()) { getLog().info("no license defined in model for " + depGav); depLicenses.add(new ImmutablePair<>("MISSING_LICENSE", null)); } Pair<String, String> key = depLicenses.get(0); String licenseUrl = key.getLeft(); final String displayName = key.getRight(); if (!urlToLicenseMap.containsKey(licenseUrl)) { // assuming we've not already mapped it, annotate the URL with artifact info, if not an actual URL try { getLog().debug("- URL: " + new URL(licenseUrl)); // life is good } catch (MalformedURLException e) { // we encounter this a lot. Log a warning, and use an annotated key final String fakeLicenseUrl = depGav.replaceAll(":", "--") + "_" + licenseUrl; getLog().info( "- URL for " + depGav + " is malformed: " + licenseUrl + "; using: " + fakeLicenseUrl); licenseUrl = fakeLicenseUrl; } } addProject(new Project(depProject, depLocation, depProject.getArtifact().getFile()), new LicenseSpec(licenseUrl, displayName), true); }
From source file:org.apache.kylin.query.util.ConvertToComputedColumn.java
static ImmutableSortedMap<String, String> getMapSortedByValue(Map<String, String> computedColumns) { if (computedColumns == null || computedColumns.isEmpty()) { return null; }//from w w w . j a v a2 s. c o m Ordering<String> ordering = Ordering.from(new Comparator<String>() { @Override public int compare(String o1, String o2) { return Integer.compare(o1.replaceAll("\\s*", "").length(), o2.replaceAll("\\s*", "").length()); } }).reverse().nullsLast().onResultOf(Functions.forMap(computedColumns, null)).compound(Ordering.natural()); return ImmutableSortedMap.copyOf(computedColumns, ordering); }
From source file:net.dv8tion.jda.core.entities.impl.MessageImpl.java
@Override public synchronized String getStrippedContent() { if (strippedContent == null) { String tmp = getContent(); //all the formatting keys to keep track of String[] keys = new String[] { "*", "_", "`", "~~" }; //find all tokens (formatting strings described above) TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start)); for (String key : keys) { Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp); while (matcher.find()) { tokens.add(new FormatToken(key, matcher.start())); }// w ww . j a v a 2 s. co m } //iterate over all tokens, find all matching pairs, and add them to the list toRemove Stack<FormatToken> stack = new Stack<>(); List<FormatToken> toRemove = new ArrayList<>(); boolean inBlock = false; for (FormatToken token : tokens) { if (stack.empty() || !stack.peek().format.equals(token.format) || stack.peek().start + token.format.length() == token.start) { //we are at opening tag if (!inBlock) { //we are outside of block -> handle normally if (token.format.equals("`")) { //block start... invalidate all previous tags stack.clear(); inBlock = true; } stack.push(token); } else if (token.format.equals("`")) { //we are inside of a block -> handle only block tag stack.push(token); } } else if (!stack.empty()) { //we found a matching close-tag toRemove.add(stack.pop()); toRemove.add(token); if (token.format.equals("`") && stack.empty()) { //close tag closed the block inBlock = false; } } } //sort tags to remove by their start-index and iteratively build the remaining string Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start)); StringBuilder out = new StringBuilder(); int currIndex = 0; for (FormatToken formatToken : toRemove) { if (currIndex < formatToken.start) { out.append(tmp.substring(currIndex, formatToken.start)); } currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < tmp.length()) { out.append(tmp.substring(currIndex)); } //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~"); } return strippedContent; }
From source file:com.publictransitanalytics.scoregenerator.datalayer.directories.GTFSReadingStopTimesDirectory.java
private void parseStopTimesFile(final ImmutableSetMultimap<String, FrequencyRecord> frequencyRecordMap, final Reader stopTimesReader) throws FileNotFoundException, IOException, InterruptedException { final CSVParser parser = new CSVParser(stopTimesReader, CSVFormat.DEFAULT.withHeader()); final SortedSetMultimap<String, RawTripStop> rawTripMap = TreeMultimap.create(Comparator.naturalOrder(), (stop1, stop2) -> Integer.compare(stop1.getSequence(), stop2.getSequence())); final Iterator<CSVRecord> stopTimesIter = parser.iterator(); while (stopTimesIter.hasNext()) { final CSVRecord record = stopTimesIter.next(); final String rawTripId = record.get("trip_id"); final int stopSequence = Integer.valueOf(record.get("stop_sequence")); final String stopId = record.get("stop_id"); final String arrivalTimeString = record.get("arrival_time"); final TransitTime arrivalTime = (arrivalTimeString == null) ? null : TransitTime.parse(arrivalTimeString); final String departureTimeString = record.get("departure_time"); final TransitTime departureTime = (departureTimeString == null) ? null : TransitTime.parse(arrivalTimeString); if (frequencyRecordMap.containsKey(rawTripId)) { final RawTripStop rawTripStop = new RawTripStop(arrivalTime, departureTime, stopId, rawTripId, stopSequence);//from ww w. j a v a 2s .c o m rawTripMap.put(rawTripId, rawTripStop); } else { final TripId tripId = new TripId(rawTripId); final TripStop tripStop = new TripStop(arrivalTime, stopId, tripId, stopSequence); try { final TripIdKey tripIdKey = new TripIdKey(rawTripId); tripsStore.put(tripIdKey, tripId); tripSequenceStore.put(new TripSequenceKey(tripIdKey, arrivalTime, stopSequence), tripStop); stopTimesStore.put(StopTimeKey.getWriteKey(stopId, arrivalTime), tripStop); } catch (final BitvantageStoreException e) { throw new ScoreGeneratorFatalException(e); } } } for (final String rawTripId : rawTripMap.keySet()) { final ImmutableSet<FrequencyRecord> frequencyRecords = frequencyRecordMap.get(rawTripId); for (final FrequencyRecord frequencyRecord : frequencyRecords) { TransitTime recurringTime = frequencyRecord.getStartTime(); while (recurringTime.isBefore(frequencyRecord.getEndTime())) { final TransitTime baseArrivalTime = rawTripMap.get(rawTripId).first().getArrivalTime(); final TripId tripId = new TripId(rawTripId, recurringTime.toString()); for (final RawTripStop rawTripStop : rawTripMap.get(rawTripId)) { final TransitTime arrivalTime = recurringTime .plus(TransitTime.durationBetween(baseArrivalTime, rawTripStop.getArrivalTime())); final int stopSequence = rawTripStop.getSequence(); final String stopId = rawTripStop.getStopId(); final TripStop tripStop = new TripStop(arrivalTime, stopId, tripId, stopSequence); final TripIdKey tripIdKey = new TripIdKey(tripId.getRawTripId(), tripId.getQualifier()); try { tripsStore.put(tripIdKey, tripId); tripSequenceStore.put(new TripSequenceKey(tripIdKey, arrivalTime, stopSequence), tripStop); stopTimesStore.put(StopTimeKey.getWriteKey(stopId, arrivalTime), tripStop); } catch (final BitvantageStoreException e) { throw new ScoreGeneratorFatalException(e); } } recurringTime = recurringTime.plus(frequencyRecord.getInterval()); } } } }
From source file:oct.analysis.application.comp.EZWorker.java
@Override protected EZEdgeCoord doInBackground() throws Exception { int foveaCenterXPosition = analysisManager.getFoveaCenterXPosition(); /*//from www.j ava 2 s . c o m first get a sharpened version of the OCT and use that to obtain the segmentation of the Bruch's membrane. Use a Loess interpolation algorithm to smooth out imperfetions in the segmentation line. */ UnivariateInterpolator interpolator = new LoessInterpolator(0.1, 0); ArrayList<Point> rawBrmPoints = new ArrayList<>(analysisManager .getSegmentation(new SharpenOperation(15, 0.5F)).getSegment(Segmentation.BrM_SEGMENT)); double[][] brmSeg = Util.getXYArraysFromPoints(rawBrmPoints); UnivariateFunction brmInterp = interpolator.interpolate(brmSeg[0], brmSeg[1]); BufferedImage sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); setProgress(10); /* Starting from the identified location of the fovea search northward in the image until the most northern pixels northward (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix is has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the seperation between bands or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching northward in the image until it can find an open region of all blak pixels. Once this is found it will find the contour of the edge between the black and white pixels along the width of the image. */ int searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)) + 1; do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || !isContrastPoint(foveaCenterXPosition, searchY, sharpOCT)); LinkedList<Point> contour = new LinkedList<>(); Point startPoint = new Point(foveaCenterXPosition, searchY); //find contour by searching for white pixel boundary to te right of the fovea contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving north to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); } setProgress(20); //open balck space found, complete contour to left of fovea contour.add( findContourLeft(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT)); analysisManager.getImgPanel().setDrawPoint(new Point(foveaCenterXPosition, searchY)); setProgress(30); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the largest Y value (furthest from the top of the image) at each X value. This eliminates overhangs from the contour line. */ Map<Double, List<Point>> grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedEZContour = grouped.values().stream().map((List<Point> points) -> { int maxY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, maxY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(35); /* Starting from the identified location of the fovea search southward in the image until the most southern pixels (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the bottom of the Bruch's membrane or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching southward in the image until it can find an open region of all black pixels. Once this is found it will find the contour of the edge between the black and white pixels, along the width of the image, of the bottom of the Bruch's membrane. */ // sharpOCT = getSharpenedOctImage(5D, 1.0F); searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); contour = new LinkedList<>(); startPoint = new Point(foveaCenterXPosition, searchY); /* Find contour by searching for white pixel boundary to te right of the fovea. Sometimes the crap below the Bruchs membrane causes too much interferance for the algorithm to work properly so we must tweak some of the parameters of the sharpening performed on the image until the algorithm succedes or we can no longer tweak parameters. In the case of the later event we can use the raw segmented Bruchs membrane as a substitute to keep the method from failing. */ contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); double filtValue = 8.5D; boolean tweakFailed = false; while (contour.contains(null)) { contour = new LinkedList<>(); filtValue -= 0.5D; System.out.println("Reducing sigma to " + filtValue); if (filtValue <= 0D) { tweakFailed = true; break; } sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } if (tweakFailed) { contour = new LinkedList<>(rawBrmPoints); } else { //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving south to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } setProgress(45); //open balck space found, complete contour to left of fovea contour.add(findContourLeft(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT)); } setProgress(55); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the smallest Y value (closest to the top of the image) at each X value. This eliminates overhangs from the contour line. */ grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedBruchsMembraneContour = grouped.values().stream().map((List<Point> points) -> { int minY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, minY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(70); /* use a Loess interpolator again to smooth the new contours of the EZ and Bruch's Membrane */ double[][] refinedContourPoints = Util.getXYArraysFromPoints(refinedEZContour); UnivariateFunction interpEZContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); refinedContourPoints = Util.getXYArraysFromPoints(refinedBruchsMembraneContour); UnivariateFunction interpBruchsContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); /* find the average difference in the distance in the Y between the 10 pixels at each end of the Bruch's Membrane contour and the contour created along the top of the EZ. */ //since the lines are sorted on X position it is easy to align the lines //based on the tails of each line int minX = refinedEZContour.get(0).x; int maxX; //the interpolator can shorten the range of the X values from the original supplied //so we need to test where the end of the range occurs since it isn't directly accessible for (maxX = refinedEZContour.get(refinedEZContour.size() - 1).x; maxX > minX; maxX--) { try { double tmp = interpEZContour.value(maxX) - interpBruchsContour.value(maxX); //if this break is reached we have found the max value the interpolators will allow break; } catch (OutOfRangeException oe) { //do nothing but let loop continue } } double avgDif = Stream .concat(IntStream.range(minX + 30, minX + 50).boxed(), IntStream.range(maxX - 49, maxX - 28).boxed()) .mapToDouble(x -> interpBruchsContour.value(x) - interpEZContour.value(x)).average().getAsDouble(); int height = sharpOCT.getHeight();//make to use in lambda expression List<LinePoint> ezLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpEZContour.value(x) - avgDif)) .collect(Collectors.toList()); List<LinePoint> bmLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpBruchsContour.value(x))) .collect(Collectors.toList()); List<LinePoint> bmUnfiltLine = refinedBruchsMembraneContour.stream() .map((Point p) -> new LinePoint(p.x, height - p.getY())).collect(Collectors.toList()); Util.graphPoints(ezLine, bmLine, bmUnfiltLine); analysisManager.getImgPanel().setDrawnLines( IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpEZContour.value(x))) .collect(Collectors.toList()), IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpBruchsContour.value(x))) .collect(Collectors.toList())); /* Find the difference between the two contours (Bruch's membrane and the EZ + Bruch's membrane) and use this to determine where the edge of the EZ is */ List<LinePoint> diffLine = findDiffWithAdjustment(interpBruchsContour, 0D, interpEZContour, avgDif, minX, maxX); setProgress(90); // List<LinePoint> peaks = Util.findPeaksAndVallies(diffLine); // Util.graphPoints(diffLine, peaks); /* Find the first zero crossings of the difference line on both sides of the fovea. If a zero crossing can't be found then search for the first crossing of a value of 1, then 2, then 3, etc. until an X coordinate of a crossing is found on each side of the fovea. */ OptionalInt ezLeftEdge; double crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezLeftEdge = diffLine.stream().filter(lp -> lp.getY() <= filtThresh && lp.getX() < foveaCenterXPosition) .mapToInt(LinePoint::getX).max(); crossingThreshold += 0.25D; } while (!ezLeftEdge.isPresent()); OptionalInt ezRightEdge; crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezRightEdge = diffLine.stream() .filter(lp -> lp.getY() <= filtThresh && lp.getX() > foveaCenterXPosition) .mapToInt(LinePoint::getX).min(); crossingThreshold += 0.25D; } while (!ezRightEdge.isPresent()); //return findings return new EZEdgeCoord(ezLeftEdge.getAsInt(), ezRightEdge.getAsInt()); }
From source file:org.mitre.mpf.interop.JsonDetectionOutputObject.java
public int compareTo(JsonDetectionOutputObject other) { int result = 0; if (other == null) { return 1; } else if ((result = Integer.compare(offsetFrame, other.offsetFrame)) != 0 || (result = Integer.compare(offsetTime, other.offsetTime)) != 0 || (result = Integer.compare(x, other.x)) != 0 || (result = Integer.compare(y, other.y)) != 0 || (result = Integer.compare(width, other.width)) != 0 || (result = Integer.compare(height, other.height)) != 0 || (result = compareMap(detectionProperties, other.detectionProperties)) != 0) { return result; } else {//from w w w . j a va 2s . c o m return 0; } }
From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ProcessSpecifications.java
static ProcessSpecifications createFromRules(List<EvaluatedPolicyRule> rules, PrismContext prismContext) throws ObjectNotFoundException { // Step 1: plain list of approval actions -> map: process-spec -> list of related actions/rules ("collected") LinkedHashMap<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>> collectedSpecifications = new LinkedHashMap<>(); for (EvaluatedPolicyRule rule : rules) { for (ApprovalPolicyActionType approvalAction : rule.getEnabledActions(ApprovalPolicyActionType.class)) { WfProcessSpecificationType spec = approvalAction.getProcessSpecification(); collectedSpecifications.computeIfAbsent(spec, s -> new ArrayList<>()) .add(new ImmutablePair<>(approvalAction, rule)); }/*from www . j a va2 s. com*/ } // Step 2: resolve references for (WfProcessSpecificationType spec : new HashSet<>(collectedSpecifications.keySet())) { // cloned to avoid concurrent modification exception if (spec != null && spec.getRef() != null) { List<Map.Entry<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>>> matching = collectedSpecifications .entrySet().stream() .filter(e -> e.getKey() != null && spec.getRef().equals(e.getKey().getName())) .collect(Collectors.toList()); if (matching.isEmpty()) { throw new IllegalStateException("Process specification named '" + spec.getRef() + "' referenced from an approval action couldn't be found"); } else if (matching.size() > 1) { throw new IllegalStateException("More than one process specification named '" + spec.getRef() + "' referenced from an approval action: " + matching); } else { // move all actions/rules to the referenced process specification List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> referencedSpecActions = matching .get(0).getValue(); referencedSpecActions.addAll(collectedSpecifications.get(spec)); collectedSpecifications.remove(spec); } } } Map<String, Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> actionsMap = null; // Step 3: include other actions for (Map.Entry<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>> processSpecificationEntry : collectedSpecifications .entrySet()) { WfProcessSpecificationType spec = processSpecificationEntry.getKey(); if (spec == null || spec.getIncludeAction().isEmpty() && spec.getIncludeActionIfPresent().isEmpty()) { continue; } if (actionsMap == null) { actionsMap = createActionsMap(collectedSpecifications.values()); } for (String actionToInclude : spec.getIncludeAction()) { processActionToInclude(actionToInclude, actionsMap, processSpecificationEntry, true); } for (String actionToInclude : spec.getIncludeActionIfPresent()) { processActionToInclude(actionToInclude, actionsMap, processSpecificationEntry, false); } } // Step 4: sorts process specifications and wraps into ProcessSpecification objects ProcessSpecifications rv = new ProcessSpecifications(prismContext); collectedSpecifications.entrySet().stream().sorted((ps1, ps2) -> { WfProcessSpecificationType key1 = ps1.getKey(); WfProcessSpecificationType key2 = ps2.getKey(); if (key1 == null) { return key2 == null ? 0 : 1; // non-empty (key2) records first } else if (key2 == null) { return -1; // non-empty (key1) record first } int order1 = defaultIfNull(key1.getOrder(), Integer.MAX_VALUE); int order2 = defaultIfNull(key2.getOrder(), Integer.MAX_VALUE); return Integer.compare(order1, order2); }).forEach(e -> rv.specifications.add(rv.new ProcessSpecification(e))); return rv; }
From source file:com.google.android.apps.forscience.whistlepunk.metadata.TriggerListFragment.java
@Override public void onResume() { super.onResume(); getDataController().getSensorLayouts(mExperimentId, new LoggingConsumer<List<GoosciSensorLayout.SensorLayout>>(TAG, "get layout") { @Override// w w w.j a va 2 s . c o m public void success(List<GoosciSensorLayout.SensorLayout> value) { for (GoosciSensorLayout.SensorLayout layout : value) { if (TextUtils.equals(layout.sensorId, mSensorId)) { mSensorLayout = layout; } } } }); getDataController().getSensorTriggersForSensor(mSensorId, new LoggingConsumer<List<SensorTrigger>>(TAG, "get triggers for sensor") { @Override public void success(List<SensorTrigger> triggers) { Comparator<SensorTrigger> cp; if (mTriggerOrder != null) { // If this is not the first load, use the saved order to define a new // order, but insert new triggers at the top. cp = new Comparator<SensorTrigger>() { @Override public int compare(SensorTrigger lhs, SensorTrigger rhs) { int lhsIndex = mTriggerOrder.indexOf(lhs.getTriggerId()); int rhsIndex = mTriggerOrder.indexOf(rhs.getTriggerId()); if (lhsIndex == rhsIndex && lhsIndex == -1) { // If they are both not found, they are both new. return Long.compare(rhs.getLastUsed(), lhs.getLastUsed()); } return Integer.compare(lhsIndex, rhsIndex); } }; } else { // Only do this sort on the first load. cp = new Comparator<SensorTrigger>() { @Override public int compare(SensorTrigger lhs, SensorTrigger rhs) { boolean lhsIsActive = isTriggerActive(lhs); boolean rhsIsActive = isTriggerActive(rhs); if (lhsIsActive && !rhsIsActive) { return -1; } if (!lhsIsActive && rhsIsActive) { return 1; } return Long.compare(rhs.getLastUsed(), lhs.getLastUsed()); } }; } // Sort sensor triggers Collections.sort(triggers, cp); mTriggerAdapter.setSensorTriggers(triggers); } }); WhistlePunkApplication.getUsageTracker(getActivity()).trackScreenView(TrackerConstants.SCREEN_TRIGGER_LIST); }
From source file:org.nuxeo.ecm.platform.forms.layout.export.WidgetTypeResource.java
protected boolean isStriclyBeforeVersion(String ref, String version) { if (version == null || version.trim().length() == 0) { return true; }//from w ww . j a va 2 s. co m String[] components1 = ref.split("\\."); String[] components2 = version.split("\\."); int length = Math.min(components1.length, components2.length); for (int i = 0; i < length; i++) { int result = Integer.compare(Integer.valueOf(components1[i]), Integer.valueOf(components2[i])); if (result != 0) { return result < 0; } } return components1.length < components2.length; }
From source file:org.search.niem.uml.merge.NamespaceMerger.java
@Override protected void copyContainment(final EReference eReference, final EObject eObject, final EObject copyEObject) { if (UMLPackage.Literals.CLASSIFIER.isInstance(eObject) && eObject.eIsSet(eReference) && eReference.isMany() && !((Collection<?>) eObject.eGet(eReference)).isEmpty()) { @SuppressWarnings("unchecked") final EList<EObject> source = (EList<EObject>) eObject.eGet(eReference); @SuppressWarnings("unchecked") final EList<EObject> target = (EList<EObject>) copyEObject.eGet(getTarget(eReference)); target.addAll(copyAll(source));// w ww . jav a 2 s.c o m final Namespace original = (Namespace) eObject; ECollections.sort(target, new Comparator<EObject>() { @Override public int compare(final EObject left, final EObject right) { return Integer.compare(indexOf(source, original.getOwnedMember(getName(left)), 0), indexOf(source, original.getOwnedMember(getName(right)), 0)); } }); } else { super.copyContainment(eReference, eObject, copyEObject); } }