List of usage examples for org.apache.commons.lang.math LongRange LongRange
public LongRange(Number number1, Number number2)
Constructs a new LongRange with the specified minimum and maximum numbers (both inclusive).
The arguments may be passed in the order (min,max) or (max,min).
From source file:SparkKMer.java
public static void main(String[] args) throws Exception { //Setup// ww w .ja v a 2 s. co m SparkConf sparkConf = new SparkConf().setAppName("SparkKMer"); JavaSparkContext jsc = new JavaSparkContext(sparkConf); //Agrument parsing if (args.length < 2) { System.err.println("Usage: SparkKMer <accession> <kmer-length>"); System.exit(1); } final String acc = args[0]; final int KMER_LENGTH = Integer.parseInt(args[1]); //Check accession and split ReadCollection run = gov.nih.nlm.ncbi.ngs.NGS.openReadCollection(acc); long numreads = run.getReadCount(); //Slice the job int chunk = 20000; /** amount of reads per 1 map operation **/ int slices = (int) (numreads / chunk / 1); if (slices == 0) slices = 1; List<LongRange> sub = new ArrayList<LongRange>(); for (long first = 1; first <= numreads;) { long last = first + chunk - 1; if (last > numreads) last = numreads; sub.add(new LongRange(first, last)); first = last + 1; } System.err.println("Prepared ranges: \n" + sub); JavaRDD<LongRange> jobs = jsc.parallelize(sub, slices); //Map // JavaRDD<String> kmers = jobs.flatMap(new FlatMapFunction<LongRange, String>() { ReadCollection run = null; @Override public Iterable<String> call(LongRange s) { //Executes on task nodes List<String> ret = new ArrayList<String>(); try { long first = s.getMinimumLong(); long last = s.getMaximumLong(); if (run == null) { run = gov.nih.nlm.ncbi.ngs.NGS.openReadCollection(acc); } ReadIterator it = run.getReadRange(first, last - first + 1, Read.all); while (it.nextRead()) { //iterate through fragments while (it.nextFragment()) { String bases = it.getFragmentBases(); //iterate through kmers for (int i = 0; i < bases.length() - KMER_LENGTH; i++) { ret.add(bases.substring(i, i + KMER_LENGTH)); } } } } catch (ErrorMsg x) { System.err.println(x.toString()); x.printStackTrace(); } return ret; } }); //Initiate kmer counting; JavaPairRDD<String, Integer> kmer_ones = kmers.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s, 1); } }); //Reduce counts JavaPairRDD<String, Integer> counts = kmer_ones.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer i1, Integer i2) { return i1 + i2; } }); //Collect the output List<Tuple2<String, Integer>> output = counts.collect(); for (Tuple2<String, Integer> tuple : output) { System.out.println(tuple._1() + ": " + tuple._2()); } jsc.stop(); }
From source file:edu.kit.dama.mdm.content.search.impl.DateRangeTerm.java
public void setFromDate(Date fromDate) { setValue(new LongRange(fromDate.getTime(), getValue().getMaximumLong())); }
From source file:edu.kit.dama.mdm.content.search.impl.DateRangeTerm.java
public void setToDate(Date toDate) { setValue(new LongRange(getValue().getMinimumLong(), toDate.getTime())); }
From source file:cern.c2mon.client.core.jms.impl.RequestHandlerImplTest.java
/** * Tests that a request is split into bunches of 500 and results are gathered in the correct way. * @throws JMSException //from ww w . ja va 2s . co m */ @Test public void getManyTags() throws JMSException { Collection<ClientRequestResult> returnCollection = Arrays.asList(new TagConfigImpl(1), new TagConfigImpl(1)); EasyMock.expect(jmsProxy.sendRequest(EasyMock.isA(JsonRequest.class), EasyMock.eq("c2mon.client.request"), EasyMock.eq(10000), //10000 is timeout (ClientRequestReportListener) EasyMock.isNull())).andReturn(returnCollection).times(20); EasyMock.replay(jmsProxy); LongRange range = new LongRange(1, 10000); long[] arrayRange = range.toArray(); Collection<Long> ids = Arrays.asList(ArrayUtils.toObject(arrayRange)); Collection result = requestHandlerImpl.requestTags(ids); Assert.assertEquals(40, result.size()); //each request for 500 tags returns 2 objects (faked list back) EasyMock.verify(jmsProxy); }
From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java
@Override public void paintComponent(Graphics g) { super.paintComponent(g); if (mTimeFrame == null) { renderNoInfoView(g);/*www . j a v a 2s. c o m*/ } else { updateSize(); LongRange startRange = mTimeFrame.getStartRange(); LongRange arriveRange = mTimeFrame.getArriveRange(); HashMap<LongRange, TimeSpan> startRanges = mTimeFrame .startTimespansToRangesMap(AnyTribe.getSingleton()); HashMap<LongRange, TimeSpan> arriveRanges = mTimeFrame.arriveTimespansToRangesMap(null); long minValue = startRange.getMinimumLong(); long maxValue = arriveRange.getMaximumLong(); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(new TexturePaint(STROKED, new Rectangle(0, 0, 3, 3))); g2d.fillRect(0, 0, getWidth(), getHeight()); //draw frame around the entire range renderRange(new LongRange(startRange.getMinimumLong(), arriveRange.getMaximumLong()), startRange, arriveRange, false, false, g2d, null, popupInfo); g2d.setColor(Constants.DS_BACK); popupInfo.clear(); //fill start range renderRange(startRange, startRange, arriveRange, true, false, g2d, null, popupInfo); //fill arrive range renderRange(arriveRange, startRange, arriveRange, false, true, g2d, null, popupInfo); Paint p = g2d.getPaint(); Iterator<LongRange> rangeKeys = startRanges.keySet().iterator(); while (rangeKeys.hasNext()) { LongRange currentRange = rangeKeys.next(); TimeSpan spanForRange = startRanges.get(currentRange); if (spanForRange != null) { if (spanForRange.isValidAtEveryDay()) { g2d.setPaint(new TexturePaint(DAILY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3))); } else if (spanForRange.isValidAtExactTime()) { g2d.setPaint(new TexturePaint(EXACT_START_FRAME_FILL, new Rectangle(0, 0, 3, 3))); } else { g2d.setPaint(new TexturePaint(ONE_DAY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3))); } } renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo); } Composite c = g2d.getComposite(); rangeKeys = arriveRanges.keySet().iterator(); while (rangeKeys.hasNext()) { LongRange currentRange = rangeKeys.next(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); g2d.setPaint(new TexturePaint(ARRIVE_FRAME_FILL, new Rectangle(0, 0, 3, 3))); TimeSpan spanForRange = arriveRanges.get(currentRange); renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo); } g2d.setComposite(c); g2d.setPaint(p); renderDayMarkers(minValue, maxValue, g2d); renderPopup(popupInfo, g2d); } }
From source file:com.hipu.bdb.util.FileUtils.java
/** * Retrieve a number of lines from the file around the given * position, as when paging forward or backward through a file. * //from w ww .j a v a 2s.co m * @param file File to retrieve lines * @param position offset to anchor lines * @param signedDesiredLineCount lines requested; if negative, * want this number of lines ending with a line containing * the position; if positive, want this number of lines, * all starting at or after position. * @param lines List<String> to insert found lines * @param lineEstimate int estimate of line size, 0 means use default * of 128 * @return LongRange indicating the file offsets corresponding to * the beginning of the first line returned, and the point * after the end of the last line returned * @throws IOException */ @SuppressWarnings("unchecked") public static LongRange pagedLines(File file, long position, int signedDesiredLineCount, List<String> lines, int lineEstimate) throws IOException { // consider negative positions as from end of file; -1 = last byte if (position < 0) { position = file.length() + position; } // calculate a reasonably sized chunk likely to have all desired lines if (lineEstimate == 0) { lineEstimate = 128; } int desiredLineCount = Math.abs(signedDesiredLineCount); long startPosition; long fileEnd = file.length(); int bufferSize = (desiredLineCount + 5) * lineEstimate; if (signedDesiredLineCount > 0) { // reading forward; include previous char in case line-end startPosition = position - 1; } else { // reading backward startPosition = position - bufferSize + (2 * lineEstimate); } if (startPosition < 0) { startPosition = 0; } if (startPosition + bufferSize > fileEnd) { bufferSize = (int) (fileEnd - startPosition); } // read that reasonable chunk FileInputStream fis = new FileInputStream(file); fis.getChannel().position(startPosition); byte[] buf = new byte[bufferSize]; IOUtils.closeQuietly(fis); // find all line starts fully in buffer // (positions after a line-end, per line-end definition in // BufferedReader.readLine) LinkedList<Integer> lineStarts = new LinkedList<Integer>(); if (startPosition == 0) { lineStarts.add(0); } boolean atLineEnd = false; boolean eatLF = false; int i; for (i = 0; i < bufferSize; i++) { if ((char) buf[i] == '\n' && eatLF) { eatLF = false; continue; } if (atLineEnd) { atLineEnd = false; lineStarts.add(i); if (signedDesiredLineCount < 0 && startPosition + i > position) { // reached next line past position, read no more break; } } if ((char) buf[i] == '\r') { atLineEnd = true; eatLF = true; continue; } if ((char) buf[i] == '\n') { atLineEnd = true; } } if (startPosition + i == fileEnd) { // add phantom lineStart after end lineStarts.add(bufferSize); } int foundFullLines = lineStarts.size() - 1; // if found no lines if (foundFullLines < 1) { if (signedDesiredLineCount > 0) { if (startPosition + bufferSize == fileEnd) { // nothing more to read: return nothing return new LongRange(fileEnd, fileEnd); } else { // retry with larger lineEstimate return pagedLines(file, position, signedDesiredLineCount, lines, Math.max(bufferSize, lineEstimate)); } } else { // try again with much larger line estimate // TODO: fail gracefully before growing to multi-MB buffers return pagedLines(file, position, signedDesiredLineCount, lines, bufferSize); } } // trim unneeded lines while (signedDesiredLineCount > 0 && startPosition + lineStarts.getFirst() < position) { // discard lines starting before desired position lineStarts.removeFirst(); } while (lineStarts.size() > desiredLineCount + 1) { if (signedDesiredLineCount < 0 && (startPosition + lineStarts.get(1) <= position)) { // discard from front until reach line containing target position lineStarts.removeFirst(); } else { lineStarts.removeLast(); } } int firstLine = lineStarts.getFirst(); int partialLine = lineStarts.getLast(); LongRange range = new LongRange(startPosition + firstLine, startPosition + partialLine); List<String> foundLines = IOUtils .readLines(new ByteArrayInputStream(buf, firstLine, partialLine - firstLine)); if (foundFullLines < desiredLineCount && signedDesiredLineCount < 0 && startPosition > 0) { // if needed and reading backward, read more lines from earlier range = expandRange(range, pagedLines(file, range.getMinimumLong() - 1, signedDesiredLineCount + foundFullLines, lines, bufferSize / foundFullLines)); } lines.addAll(foundLines); if (signedDesiredLineCount < 0 && range.getMaximumLong() < position) { // did not get line containining start position range = expandRange(range, pagedLines(file, partialLine, 1, lines, bufferSize / foundFullLines)); } if (signedDesiredLineCount > 0 && foundFullLines < desiredLineCount && range.getMaximumLong() < fileEnd) { // need more forward lines range = expandRange(range, pagedLines(file, range.getMaximumLong(), desiredLineCount - foundFullLines, lines, bufferSize / foundFullLines)); } return range; }
From source file:com.hipu.bdb.util.FileUtils.java
public static LongRange expandRange(LongRange range1, LongRange range2) { return new LongRange(Math.min(range1.getMinimumLong(), range2.getMinimumLong()), Math.max(range1.getMaximumLong(), range2.getMaximumLong())); }
From source file:com.bst.tags.TableTag.java
/** * Reads parameters from the request and initialize all the needed table model attributes. * @throws ObjectLookupException for problems in evaluating the expression in the "name" attribute * @throws FactoryInstantiationException for problems in instantiating a RequestHelperFactory *///w ww. ja v a2s .c o m private void initParameters() throws ObjectLookupException, FactoryInstantiationException { if (rhf == null) { // first time initialization rhf = this.properties.getRequestHelperFactoryInstance(); } RequestHelper requestHelper = rhf.getRequestHelperInstance(this.pageContext); initHref(requestHelper); Integer pageNumberParameter = requestHelper .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_PAGE)); this.pageNumber = (pageNumberParameter == null) ? 1 : pageNumberParameter.intValue(); Integer sortColumnParameter = requestHelper .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_SORT)); int sortColumn = (sortColumnParameter == null) ? this.defaultSortedColumn : sortColumnParameter.intValue(); this.tableModel.setSortedColumnNumber(sortColumn); // default value boolean finalSortFull = this.properties.getSortFullList(); // user value for this single table if (this.sortFullTable != null) { finalSortFull = this.sortFullTable.booleanValue(); } this.tableModel.setSortFullTable(finalSortFull); SortOrderEnum paramOrder = SortOrderEnum .fromCode(requestHelper.getIntParameter(encodeParameter(TableTagParameters.PARAMETER_ORDER))); // if no order parameter is set use default if (paramOrder == null) { paramOrder = this.defaultSortOrder; } boolean order = SortOrderEnum.DESCENDING != paramOrder; this.tableModel.setSortOrderAscending(order); Integer exportTypeParameter = requestHelper .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_EXPORTTYPE)); this.currentMediaType = MediaTypeEnum.fromCode(exportTypeParameter); if (this.currentMediaType == null) { this.currentMediaType = MediaTypeEnum.HTML; } String fullName = getFullObjectName(); // only evaluate if needed, else use list attribute if (fullName != null) { this.list = evaluateExpression(fullName); } else if (this.list == null) { // needed to allow removing the collection of objects if not set directly this.list = this.listAttribute; } // do we really need to skip any row? boolean wishOptimizedIteration = (this.pagesize > 0 // we are paging || this.offset > 0 // or we are skipping some records using offset || this.length > 0 // or we are limiting the records using length ); // can we actually skip any row? if (wishOptimizedIteration && (this.list instanceof Collection) // we need to know the size && ((sortColumn == -1 // and we are not sorting || !finalSortFull // or we are sorting with the "page" behaviour ) && (this.currentMediaType == MediaTypeEnum.HTML // and we are not exporting || !this.properties.getExportFullList()) // or we are exporting a single page )) { int start = 0; int end = 0; if (this.offset > 0) { start = this.offset; } if (length > 0) { end = start + this.length; } if (this.pagesize > 0) { int fullSize = ((Collection) this.list).size(); start = (this.pageNumber - 1) * this.pagesize; // invalid page requested, go back to page one if (start > fullSize) { start = 0; } end = start + this.pagesize; } // rowNumber starts from 1 filteredRows = new LongRange(start + 1, end); } else { filteredRows = new LongRange(1, Long.MAX_VALUE); } this.tableIterator = IteratorUtils.getIterator(this.list); }
From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java
public void prepareForDefense(DefenseInformation[] pElements) { for (DefenseInformation elem : pElements) { fireAddTargetEvent(elem.getTarget(), elem.getNeededSupports()); mSettingsPanel.addTimeSpanExternally(new DefenseTimeSpan(elem.getTarget(), new LongRange(elem.getFirstAttack().getTime(), elem.getLastAttack().getTime()))); }//from w w w . j ava2s . co m }
From source file:net.sourceforge.subsonic.controller.StreamController.java
private LongRange parseAndConvertOffsetSeconds(String offsetSeconds, MediaFile file) { if (offsetSeconds == null) { return null; }/*from www . j a va 2s. com*/ try { Integer duration = file.getDurationSeconds(); Long fileSize = file.getFileSize(); if (duration == null || fileSize == null) { return null; } float offset = Float.parseFloat(offsetSeconds); // Convert from time offset to byte offset. long byteOffset = (long) (fileSize * (offset / duration)); return new LongRange(byteOffset, Long.MAX_VALUE); } catch (Exception x) { LOG.error("Failed to parse and convert time offset: " + offsetSeconds, x); return null; } }