List of usage examples for java.lang Long signum
public static int signum(long i)
From source file:org.dkpro.lab.storage.filesystem.FileSystemStorageService.java
@Override public List<TaskContextMetadata> getContexts(String aTaskType, Map<String, String> aConstraints) { List<TaskContextMetadata> contexts = new ArrayList<TaskContextMetadata>(); nextContext: for (TaskContextMetadata e : getContexts()) { // Ignore those that do not match the type if (!aTaskType.equals(e.getType())) { continue; }/*from www .j a v a 2 s .c o m*/ // Check the constraints if there are any if (aConstraints.size() > 0) { final Map<String, String> properties = retrieveBinary(e.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter()).getMap(); if (!matchConstraints(properties, aConstraints, true)) { continue nextContext; } } contexts.add(e); } Collections.sort(contexts, new Comparator<TaskContextMetadata>() { @Override public int compare(TaskContextMetadata aO1, TaskContextMetadata aO2) { return Long.signum(aO2.getEnd() - aO1.getEnd()); } }); return contexts; }
From source file:org.jenkinsci.plugins.jobgenerator.parameterizedtrigger.CounterGeneratorParameterFactory.java
@Override public List<AbstractBuildParameters> getParameters(AbstractBuild<?, ?> build, TaskListener listener) throws IOException, InterruptedException, AbstractBuildParameters.DontTriggerException { EnvVars envVars = build.getEnvironment(listener); long fromNum = Long.valueOf(envVars.expand(from)); long toNum = Long.valueOf(envVars.expand(to)); long stepNum = Long.valueOf(envVars.expand(step)); ArrayList<AbstractBuildParameters> params = Lists.newArrayList(); int upDown = Long.signum(toNum - fromNum); if (upDown == 0) { params.add(getParameterForCount(fromNum)); } else {/* w w w.ja v a 2s . c o m*/ if (stepNum == 0) { validationFail.failCheck(listener); } else if (upDown * stepNum < 0) { validationFail.failCheck(listener); } else { for (Long i = fromNum; upDown * i <= upDown * toNum; i += stepNum) { params.add(getParameterForCount(i)); } } } return params; }
From source file:org.noroomattheinn.visibletesla.TripController.java
private List<Trip> getSelectedTrips() { ArrayList<Trip> selection = new ArrayList<>(); for (String item : availableTripsView.getSelectionModel().getSelectedItems()) { Trip t = selectedTrips.get(item); if (t != null) selection.add(t);/*from w ww . ja v a 2 s.co m*/ } Collections.sort(selection, new Comparator<Trip>() { @Override public int compare(Trip o1, Trip o2) { return Long.signum(o1.firstWayPoint().getTime() - o2.firstWayPoint().getTime()); } }); return selection; }
From source file:org.codehaus.mojo.cassandra.Utils.java
/** * Returns {@code true} if the resource is not a file, does not exist or is older than the project file. * * @param project the project that the resource is dependent on. * @param resource the resource to query. * @return {@code true} if the resource is not a file, does not exist or is older than the project file. *///from w w w . jav a 2 s.c o m static boolean shouldGenerateResource(MavenProject project, File resource) { if (!resource.isFile()) { return true; } long resourceLM = resource.lastModified(); long projectLM = project.getFile().lastModified(); if (Long.signum(resourceLM) == Long.signum(projectLM)) { // the two dates are in the same epoch or else the universe is lasting a really long time. return resourceLM < projectLM; } // the universe has been around long enough that we should rewrite the resource. return true; }
From source file:it.gcatania.dropboxchallenges.packingYourDropbox.DropboxOptimizationTest.java
@Test public void testOptimization() throws IOException { random.setSeed(133l); // make test reproductible optimizationData.clear();/*from ww w . ja v a 2 s . c om*/ @SuppressWarnings("unchecked") List<Comparator<Rectangle>> comparators = Arrays.asList(new FakeComparator<Rectangle>(), // new RectangleSuperComparator(), // same as RectangleAreaComparator new RectangleMaxSideThenPerimeterComparator(), new RectangleAreaComparator(), new RectangleMaxSideComparator(), new RectangleSideRatioComparator(), new RectanglePerimeterComparator()); List<OverheadCalculator<?>> overheadCalculators = Arrays.<OverheadCalculator<?>>asList( new DropboxAreaOverheadCalculator(), // new AreaOverheadCalculator(), // not optimal // new DistanceFromOriginOverheadCalculator(), // not optimal new DropboxMagicOverheadCalculator() // not optimal // new FreeSpaceOverheadCalculator(), // same as DropBoxAreaOverheadCalculator // new DropBoxOverheadCalculator() // not optimal ); for (int i = 0; i < NUM_ITERATIONS; i++) { System.out.println("pass " + i); singlePass(comparators, overheadCalculators); } List<Map.Entry<Setup, Score>> entrySet = new ArrayList<Map.Entry<Setup, Score>>( optimizationData.entrySet()); Collections.sort(entrySet, new Comparator<Map.Entry<Setup, Score>>() { /** * compares two scores by their number of first places, then by their total area, then by their total free * space */ @Override public int compare(Map.Entry<Setup, Score> e1, Map.Entry<Setup, Score> e2) { Score score1 = e1.getValue(); Score score2 = e2.getValue(); int firstPlacesDiff = score2.firstPlaces - score1.firstPlaces; if (firstPlacesDiff == 0) { long totalAreaDiff = score1.totalArea - score2.totalArea; if (totalAreaDiff == 0) { return Long.signum(score1.totalFreeSpace - score2.totalFreeSpace); } return Long.signum(totalAreaDiff); } return firstPlacesDiff; } }); long minArea = Long.MAX_VALUE; long minFreeSpace = Long.MAX_VALUE; long minTime = Long.MAX_VALUE; long minAreaOverhead = Long.MAX_VALUE; for (Map.Entry<Setup, Score> e : entrySet) { Score score = e.getValue(); if (minArea > score.totalArea) { minArea = score.totalArea; } if (minFreeSpace > score.totalFreeSpace) { minFreeSpace = score.totalFreeSpace; } if (minAreaOverhead > score.totalAreaOverhead) { minAreaOverhead = score.totalAreaOverhead; } long time = score.watch.getTime(); if (minTime > time) { minTime = time; } } BufferedWriter w = new BufferedWriter(new FileWriter("target/results.csv", false)); w.write("Comparator;Calculator;FirstPlaces;FirstPlacesPerc;TotalArea;TotalAreaPerc;" + "FreeSpace;FreeSpacePerc;TimeMillis;TimeMillisPerc;AreaOverhead;AreaOverheadPerc;" + "winningPreAllocationsPerc;evenPreAllocationsPerc\n"); for (Map.Entry<Setup, Score> e : entrySet) { Setup setup = e.getKey(); Score score = e.getValue(); int firstPlacesPerc = 100 * score.firstPlaces / NUM_ITERATIONS; long totalAreaPerc = 100 * score.totalArea / minArea; long freeSpacePerc = 100 * score.totalFreeSpace / minFreeSpace; long timePerc = 100 * score.watch.getTime() / minTime; long areaOverheadPerc = minAreaOverhead > 0 ? 100 * score.totalAreaOverhead / minAreaOverhead : 0; int winningPreAllocationsPerc = score.winningPreAllocations * 100 / NUM_ITERATIONS; int evenPreAllocationsPerc = score.evenPreAllocations * 100 / NUM_ITERATIONS; w.write(new StringBuilder(setup.comparator.getClass().getSimpleName()).append(';') .append(setup.calculator.getClass().getSimpleName()).append(';').append(score.firstPlaces) .append(';').append(firstPlacesPerc).append(';').append(score.totalArea).append(';') .append(totalAreaPerc).append(';').append(score.totalFreeSpace).append(';') .append(freeSpacePerc).append(';').append(score.watch.getTime()).append(';').append(timePerc) .append(';').append(score.totalAreaOverhead).append(';').append(areaOverheadPerc).append(';') .append(winningPreAllocationsPerc).append(';').append(evenPreAllocationsPerc).append('\n') .toString()); } w.close(); }
From source file:org.trpr.platform.batch.impl.spring.admin.repository.MapStepExecutionDao.java
@Override public void addStepExecutions(JobExecution jobExecution) { Map<Long, StepExecution> executions = executionsByJobExecutionId.get(jobExecution.getId()); if (executions == null || executions.isEmpty()) { return;/*from ww w . jav a2 s . com*/ } List<StepExecution> result = new ArrayList<StepExecution>(executions.values()); Collections.sort(result, new Comparator<Entity>() { @Override public int compare(Entity o1, Entity o2) { return Long.signum(o2.getId() - o1.getId()); } }); List<StepExecution> copy = new ArrayList<StepExecution>(result.size()); for (StepExecution exec : result) { copy.add(copy(exec)); } jobExecution.addStepExecutions(copy); }
From source file:javaapplication2.Mundo.java
private Estado[][] generarGrillaDeEstados(int filaEstadoInicial, int columnaEstadoInicial, int filaEstadoFinal, int columnaEstadoFinal) { Estado[][] estadosCreados = new Estado[this.filas][this.columnas]; for (int i = 0; i < this.filas; i++) { for (int j = 0; j < this.columnas; j++) { estadosCreados[i][j] = new Estado(); estadosCreados[i][j].setFila(i); estadosCreados[i][j].setColumna(j); estadosCreados[i][j].setEsFinal(false); estadosCreados[i][j].setEsInicial(false); estadosCreados[i][j].setEsObstaculo(false); //ver si es el inicial o final //sino ver si le toca ser obstaculo if (((estadosCreados[i][j].getFila() == filaEstadoInicial) && (estadosCreados[i][j].getColumna() == columnaEstadoInicial)) || ((estadosCreados[i][j].getFila() == filaEstadoFinal) && (estadosCreados[i][j].getColumna() == columnaEstadoFinal))) { if ((estadosCreados[i][j].getFila() == filaEstadoInicial) && (estadosCreados[i][j].getColumna() == columnaEstadoInicial)) { estadosCreados[i][j].setEsInicial(true); }//from ww w . j a v a 2 s. c o m if ((estadosCreados[i][j].getFila() == filaEstadoFinal) && (estadosCreados[i][j].getColumna() == columnaEstadoFinal)) { estadosCreados[i][j].setEsFinal(true); } } else { //ver si se obstaculisa o no el estado double valorDistribucion = normal.inverseCumulativeProbability(random.nextDouble()); // normal.density(random.nextDouble()); long tileType = Long.signum(Math.abs(Math.round(valorDistribucion))); // System.out.println(tileType); if (tileType == 1) { estadosCreados[i][j].setEsObstaculo(true); } } } } return estadosCreados; }
From source file:it.unimi.dsi.sux4j.mph.TwoStepsGOV3Function.java
/** Creates a new two-step function for the given keys and values. * /* w w w. jav a2 s .c o m*/ * @param keys the keys in the domain of the function. * @param transform a transformation strategy for the keys. * @param values values to be assigned to each key, in the same order of the iterator returned by <code>keys</code>; if {@code null}, the * assigned value will the the ordinal number of each key. * @param tempDir a temporary directory for the store files, or {@code null} for the standard temporary directory. * @param chunkedHashStore a chunked hash store containing the keys associated with their rank, or {@code null}; the store * can be unchecked, but in this case <code>keys</code> and <code>transform</code> must be non-{@code null}. */ protected TwoStepsGOV3Function(final Iterable<? extends T> keys, final TransformationStrategy<? super T> transform, final LongBigList values, final File tempDir, ChunkedHashStore<T> chunkedHashStore) throws IOException { this.transform = transform; final ProgressLogger pl = new ProgressLogger(LOGGER); pl.displayLocalSpeed = true; pl.displayFreeMemory = true; final RandomGenerator random = new XorShift1024StarRandomGenerator(); pl.itemsName = "keys"; final boolean givenChunkedHashStore = chunkedHashStore != null; if (!givenChunkedHashStore) { if (keys == null) throw new IllegalArgumentException( "If you do not provide a chunked hash store, you must provide the keys"); chunkedHashStore = new ChunkedHashStore<T>(transform, pl); chunkedHashStore.reset(random.nextLong()); chunkedHashStore.addAll(keys.iterator()); } n = chunkedHashStore.size(); defRetValue = -1; // For the very few cases in which we can decide if (n == 0) { rankMean = escape = width = 0; firstFunction = secondFunction = null; remap = null; if (!givenChunkedHashStore) chunkedHashStore.close(); return; } // Compute distribution of values and maximum number of bits. int w = 0, size; long v; final Long2LongOpenHashMap counts = new Long2LongOpenHashMap(); counts.defaultReturnValue(-1); for (LongIterator i = values.iterator(); i.hasNext();) { v = i.nextLong(); counts.put(v, counts.get(v) + 1); size = Fast.length(v); if (size > w) w = size; } this.width = w; final int m = counts.size(); LOGGER.debug("Generating two-steps GOV3 function with " + w + " output bits..."); // Sort keys by reverse frequency final long[] keysArray = counts.keySet().toLongArray(new long[m]); LongArrays.quickSort(keysArray, 0, keysArray.length, new AbstractLongComparator() { private static final long serialVersionUID = 1L; public int compare(final long a, final long b) { return Long.signum(counts.get(b) - counts.get(a)); } }); long mean = 0; for (int i = 0; i < keysArray.length; i++) mean += i * counts.get(keysArray[i]); rankMean = (double) mean / n; // Analyze data and choose a threshold long post = n, bestCost = Long.MAX_VALUE; int pos = 0, best = -1; // Examine every possible choice for r. Note that r = 0 implies one function, so we do not need to test the case r == w. for (int r = 0; r < w && pos < m; r++) { /* This cost function is dependent on the implementation of GOV3Function. * Note that for r = 0 we are actually computing the cost of a single function (the first one). */ final long cost = (long) Math.min(GOV3Function.C * n * 1.126 + n * r, GOV3Function.C * n * r) + (long) Math.min(GOV3Function.C * post * 1.126 + post * w, GOV3Function.C * post * w) + pos * Long.SIZE; if (cost < bestCost) { best = r; bestCost = cost; } /* We add to pre and subtract from post the counts of keys from position (1<<r)-1 to position (1<<r+1)-1. */ for (int j = 0; j < (1 << r) && pos < m; j++) { final long c = counts.get(keysArray[pos++]); post -= c; } } if (ASSERTS) assert pos == m; counts.clear(); counts.trim(); // We must keep the remap array small. if (best >= Integer.SIZE) best = Integer.SIZE - 1; LOGGER.debug("Best threshold: " + best); escape = (1 << best) - 1; System.arraycopy(keysArray, 0, remap = new long[escape], 0, remap.length); final Long2LongOpenHashMap map = new Long2LongOpenHashMap(); map.defaultReturnValue(-1); for (int i = 0; i < escape; i++) map.put(remap[i], i); if (best != 0) { firstFunction = new GOV3Function.Builder<T>().keys(keys).transform(transform).store(chunkedHashStore) .values(new AbstractLongBigList() { public long getLong(long index) { long value = map.get(values.getLong(index)); return value == -1 ? escape : value; } public long size64() { return n; } }, best).indirect().build(); LOGGER.debug("Actual bit cost per key of first function: " + (double) firstFunction.numBits() / n); } else firstFunction = null; chunkedHashStore.filter(new Predicate() { public boolean evaluate(Object triple) { return firstFunction == null || firstFunction.getLongByTriple((long[]) triple) == escape; } }); secondFunction = new GOV3Function.Builder<T>().store(chunkedHashStore).values(values, w).indirect().build(); this.seed = chunkedHashStore.seed(); if (!givenChunkedHashStore) chunkedHashStore.close(); LOGGER.debug("Actual bit cost per key of second function: " + (double) secondFunction.numBits() / n); LOGGER.info("Actual bit cost per key: " + (double) numBits() / n); LOGGER.info("Completed."); }
From source file:it.unimi.dsi.sux4j.mph.TwoStepsMWHCFunction.java
/** Creates a new two-step function for the given keys and values. * //from w w w . ja va 2 s . c o m * @param keys the keys in the domain of the function. * @param transform a transformation strategy for the keys. * @param values values to be assigned to each key, in the same order of the iterator returned by <code>keys</code>; if {@code null}, the * assigned value will the the ordinal number of each key. * @param tempDir a temporary directory for the store files, or {@code null} for the standard temporary directory. * @param chunkedHashStore a chunked hash store containing the keys associated with their rank, or {@code null}; the store * can be unchecked, but in this case <code>keys</code> and <code>transform</code> must be non-{@code null}. */ protected TwoStepsMWHCFunction(final Iterable<? extends T> keys, final TransformationStrategy<? super T> transform, final LongBigList values, final File tempDir, ChunkedHashStore<T> chunkedHashStore) throws IOException { this.transform = transform; final ProgressLogger pl = new ProgressLogger(LOGGER); pl.displayLocalSpeed = true; pl.displayFreeMemory = true; final RandomGenerator random = new XorShift1024StarRandomGenerator(); pl.itemsName = "keys"; final boolean givenChunkedHashStore = chunkedHashStore != null; if (!givenChunkedHashStore) { if (keys == null) throw new IllegalArgumentException( "If you do not provide a chunked hash store, you must provide the keys"); chunkedHashStore = new ChunkedHashStore<T>(transform, pl); chunkedHashStore.reset(random.nextLong()); chunkedHashStore.addAll(keys.iterator()); } n = chunkedHashStore.size(); defRetValue = -1; // For the very few cases in which we can decide if (n == 0) { rankMean = escape = width = 0; firstFunction = secondFunction = null; remap = null; if (!givenChunkedHashStore) chunkedHashStore.close(); return; } // Compute distribution of values and maximum number of bits. int w = 0, size; long v; final Long2LongOpenHashMap counts = new Long2LongOpenHashMap(); counts.defaultReturnValue(-1); for (LongIterator i = values.iterator(); i.hasNext();) { v = i.nextLong(); counts.put(v, counts.get(v) + 1); size = Fast.length(v); if (size > w) w = size; } this.width = w; final int m = counts.size(); LOGGER.debug("Generating two-steps MWHC function with " + w + " output bits..."); // Sort keys by reverse frequency final long[] keysArray = counts.keySet().toLongArray(new long[m]); LongArrays.quickSort(keysArray, 0, keysArray.length, new AbstractLongComparator() { private static final long serialVersionUID = 1L; public int compare(final long a, final long b) { return Long.signum(counts.get(b) - counts.get(a)); } }); long mean = 0; for (int i = 0; i < keysArray.length; i++) mean += i * counts.get(keysArray[i]); rankMean = (double) mean / n; // Analyze data and choose a threshold long post = n, bestCost = Long.MAX_VALUE; int pos = 0, best = -1; // Examine every possible choice for r. Note that r = 0 implies one function, so we do not need to test the case r == w. for (int r = 0; r < w && pos < m; r++) { /* This cost function is dependent on the implementation of MWHCFunction. * Note that for r = 0 we are actually computing the cost of a single function (the first one). */ final long cost = (long) Math.min(HypergraphSorter.GAMMA * n * 1.126 + n * r, HypergraphSorter.GAMMA * n * r) + (long) Math.min(HypergraphSorter.GAMMA * post * 1.126 + post * w, HypergraphSorter.GAMMA * post * w) + pos * Long.SIZE; if (cost < bestCost) { best = r; bestCost = cost; } /* We add to pre and subtract from post the counts of keys from position (1<<r)-1 to position (1<<r+1)-1. */ for (int j = 0; j < (1 << r) && pos < m; j++) { final long c = counts.get(keysArray[pos++]); post -= c; } } if (ASSERTS) assert pos == m; counts.clear(); counts.trim(); // We must keep the remap array small. if (best >= Integer.SIZE) best = Integer.SIZE - 1; LOGGER.debug("Best threshold: " + best); escape = (1 << best) - 1; System.arraycopy(keysArray, 0, remap = new long[escape], 0, remap.length); final Long2LongOpenHashMap map = new Long2LongOpenHashMap(); map.defaultReturnValue(-1); for (int i = 0; i < escape; i++) map.put(remap[i], i); if (best != 0) { firstFunction = new MWHCFunction.Builder<T>().keys(keys).transform(transform).store(chunkedHashStore) .values(new AbstractLongBigList() { public long getLong(long index) { long value = map.get(values.getLong(index)); return value == -1 ? escape : value; } public long size64() { return n; } }, best).indirect().build(); LOGGER.debug("Actual bit cost per key of first function: " + (double) firstFunction.numBits() / n); } else firstFunction = null; chunkedHashStore.filter(new Predicate() { public boolean evaluate(Object triple) { return firstFunction == null || firstFunction.getLongByTriple((long[]) triple) == escape; } }); secondFunction = new MWHCFunction.Builder<T>().store(chunkedHashStore).values(values, w).indirect().build(); this.seed = chunkedHashStore.seed(); if (!givenChunkedHashStore) chunkedHashStore.close(); LOGGER.debug("Actual bit cost per key of second function: " + (double) secondFunction.numBits() / n); LOGGER.info("Actual bit cost per key: " + (double) numBits() / n); LOGGER.info("Completed."); }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.tree.NumberArithmetic.java
/** * Returns the sign of the number.//w w w .j av a 2 s. co m * * @param a the number * @return the sign of the number * @see Long#signum(long) * @see Math#signum(double) */ public static Number sign(Number a) { if (isFloatingPoint(a)) { return Math.signum(a.doubleValue()); } else { return Long.signum(a.longValue()); } }