List of usage examples for java.util ArrayList subList
public List<E> subList(int fromIndex, int toIndex)
From source file:org.eurekastreams.server.persistence.mappers.cache.testhelpers.SimpleMemoryCache.java
/** * {@inheritDoc}/*w w w. ja v a 2s . c o m*/ */ @SuppressWarnings("unchecked") public ArrayList<Long> getList(final String inKey, final int inMaximumEntries) { ArrayList toReturn = null; byte[] bytes = (byte[]) cache.get(inKey); if (bytes != null) { try { toReturn = getListFromBytes(bytes); } catch (IOException e) { // problem getting the key .. return a null so the client goes // to the database log.error("Unable to retrieve LIST key " + inKey + " from memcached. Exception " + e.getMessage()); return null; } } // check list size and trim if necessary if (toReturn != null && toReturn.size() > inMaximumEntries) { ArrayList<Long> trimmed = (ArrayList<Long>) toReturn.subList(0, inMaximumEntries - 1); toReturn = trimmed; try { this.set(inKey, getBytesFromList(trimmed)); } catch (IOException e) { log.error("Error getBytesFromList getList memcached list with passed in value for key " + inKey + ". Exception : " + e.toString()); } } return toReturn; }
From source file:com.retroteam.studio.retrostudio.MeasureEditor.java
/** * Calculate the number of notes to draw. * @return//from w w w . j av a 2s . c o m */ private List<List<Integer>> numNotesFromGuiSnap() { //the measure length int mlength = (int) ((((double) TS_BEATS / (double) TS_NOTES)) * 32); boolean useRange = true; int maxNotesToDraw; //decide if we can use the user's input guiSNAP if (guiSNAP > mlength || (mlength % 4) > 0) { //if not, then we will draw each individual note //this is for irregular time signatures maxNotesToDraw = mlength; useRange = false; } else { maxNotesToDraw = (int) ((((double) TS_BEATS / (double) TS_NOTES)) * guiSNAP); } ArrayList<Integer> therange = new ArrayList<>(mlength); List<List<Integer>> rangelist = new LinkedList<List<Integer>>(); //produce a list of the range of notes to draw //i.e., if 8, produce [0,1,2,3,4,5,6,7] for (int i = 0; i < mlength; i += 1) { therange.add(i); } if (useRange) { for (int i = 0; i < therange.size(); i += therange.size() / maxNotesToDraw) { rangelist.add(therange.subList(i, Math.min(i + therange.size() / maxNotesToDraw, therange.size()))); } } return rangelist; }
From source file:com.hygenics.parser.QualityAssurer.java
private void sendToDb(ArrayList<String> json, boolean split) { if (json.size() > 0) log.info("Records to Add: " + json.size()); if (split) {/*from w ww . j a v a2s . co m*/ ForkJoinPool f2 = new ForkJoinPool( (Runtime.getRuntime().availableProcessors() + ((int) Math.ceil(procnum * qnum)))); ArrayList<String> l; int size = (int) Math.ceil(json.size() / qnum); for (int conn = 0; conn < qnum; conn++) { l = new ArrayList<String>(); if (((conn + 1) * size) < json.size()) { l.addAll(json.subList((conn * size), ((conn + 1) * size))); } else { l.addAll(json.subList((conn * size), (json.size() - 1))); f2.execute(new SplitPost(template, l)); break; } f2.execute(new SplitPost(template, l)); } try { f2.awaitTermination(termtime, TimeUnit.MILLISECONDS); } catch (InterruptedException e1) { e1.printStackTrace(); } f2.shutdown(); int incrementor = 0; while (f2.isShutdown() == false && f2.getActiveThreadCount() > 0 && f2.isQuiescent() == false) { incrementor++; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } log.info("Shutting Down" + incrementor); } l = null; f2 = null; } else { for (String j : json) { boolean valid = false; try { Json.read(j); valid = true; } catch (Exception e) { log.info("ERROR: JSON NOT FORMATTED PROPERLY"); System.out.println(j); } try { this.template.postSingleJson(j); } catch (Exception e) { log.info("Failed to Post"); log.error(j); e.printStackTrace(); } } } }
From source file:de.fhg.iais.asc.ui.parts.TransformersPanel.java
/** * Providing transformers' selections// w ww. j a va 2 s .co m */ private void retrieveVersionsAndSetMaxVersion() { this.versionComboBox.removeAllItems(); // retrieve versions ArrayList<String> sel = new ArrayList<String>(); sel.add((String) this.sourceMetadataComboBox.getSelectedItem()); sel.add((String) this.domainComboBox.getSelectedItem()); sel.add((String) this.providermappingComboBox.getSelectedItem()); sel.add((String) this.collectionmappingComboBox.getSelectedItem()); int maxvalue = 0; for (String value : sel) { if (value == null || value.equals("--")) { break; } maxvalue++; } if (maxvalue == 0) { return; } SipMakerKey description = SipMakerKey.fromTrunk(sel.get(0), sel.subList(1, maxvalue)); String[] versions = this.sipMakerFactory.getVersions(description); // put the retrieved versions in the combobox for (String version : versions) { this.versionComboBox.addItem(version); } // select max version int max = -1; int indexToSelect = -1; for (int i = 0; i < this.versionComboBox.getModel().getSize(); i++) { try { Integer version = Integer.valueOf(this.versionComboBox.getModel().getElementAt(i).toString()); if (version > max) { max = version; indexToSelect = i; } } catch (NumberFormatException ex) { // ignore } // something found if (max > -1 && indexToSelect > -1) { this.versionComboBox.setSelectedIndex(indexToSelect); } } }
From source file:eu.trentorise.smartcampus.trentinofamiglia.custom.data.DTHelper.java
public static Collection<BaseDTObject> getMostPopular() throws DataException, StorageConfigurationException, ConnectionException, ProtocolException, SecurityException, TerritoryServiceException, AACException { ArrayList<BaseDTObject> list = new ArrayList<BaseDTObject>(); if (Utils.getObjectVersion(mContext, DTParamsHelper.getAppToken(), Constants.SYNC_DB_NAME) > 0) { Collection<PoiObjectForBean> pois = getInstance().storage.getObjects(PoiObjectForBean.class); for (PoiObjectForBean poiBean : pois) { list.add(poiBean.getObjectForBean()); }//from ww w. j a v a 2 s. c o m if (pois.size() > 20) { return list.subList(0, 20); } return list; } else { ObjectFilter filter = new ObjectFilter(); filter.setLimit(20); List<POIObject> pois = tService.getPOIs(filter, getAuthToken()); for (POIObject poiObject : pois) { list.add(poiObject); } return list; } }
From source file:id.ridon.keude.UpdateService.java
private void executeBatchWithStatus(String providerAuthority, ArrayList<ContentProviderOperation> operations, int currentCount, int totalUpdateCount) throws RemoteException, OperationApplicationException { int i = 0;//from www . j a va 2s . com while (i < operations.size()) { int count = Math.min(operations.size() - i, 100); ArrayList<ContentProviderOperation> o = new ArrayList<ContentProviderOperation>( operations.subList(i, i + count)); sendStatus(STATUS_INFO, getString(R.string.status_inserting, (int) ((double) (currentCount + i) / totalUpdateCount * 100))); getContentResolver().applyBatch(providerAuthority, o); i += 100; } }
From source file:ee.ioc.phon.android.speak.RecognizerIntentActivity.java
/** * <p>Returns the transcription results (matches) to the caller, * or sends them to the pending intent, or performs a web search.</p> * * <p>If a pending intent was specified then use it. This is the case with * applications that use the standard search bar (e.g. Google Maps and YouTube).</p> * * <p>Otherwise. If there was no caller (i.e. we cannot return the results), or * the caller asked us explicitly to perform "web search", then do that, possibly * disambiguating the results or redoing the recognition. * This is the case when K6nele was launched from its launcher icon (i.e. no caller), * or from a browser app.// w w w. jav a2s . c o m * (Note that trying to return the results to Google Chrome does not seem to work.)</p> * * <p>Otherwise. Just return the results to the caller.</p> * * <p>Note that we assume that the given list of matches contains at least one * element.</p> * * @param handler message handler * @param matches transcription results (one or more hypotheses) */ private void returnOrForwardMatches(final Handler handler, ArrayList<String> matches) { // Throw away matches that the user is not interested in int maxResults = mExtras.getInt(RecognizerIntent.EXTRA_MAX_RESULTS); if (maxResults > 0 && matches.size() > maxResults) { matches.subList(maxResults, matches.size()).clear(); } if (mExtraResultsPendingIntent == null) { if (getCallingActivity() == null || RecognizerIntent.ACTION_WEB_SEARCH.equals(getIntent().getAction()) || mExtras.getBoolean(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY)) { handleResultsByWebSearch(this, handler, matches); return; } else { setResultIntent(handler, matches); } } else { Bundle bundle = mExtras.getBundle(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE); if (bundle == null) { bundle = new Bundle(); } String match = matches.get(0); //mExtraResultsPendingIntentBundle.putString(SearchManager.QUERY, match); Intent intent = new Intent(); intent.putExtras(bundle); // This is for Google Maps, YouTube, ... intent.putExtra(SearchManager.QUERY, match); // This is for SwiftKey X, ... intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, matches); String message = ""; if (matches.size() == 1) { message = match; } else { message = matches.toString(); } // Display a toast with the transcription. handler.sendMessage( createMessage(MSG_TOAST, String.format(getString(R.string.toastForwardedMatches), message))); try { mExtraResultsPendingIntent.send(this, Activity.RESULT_OK, intent); } catch (CanceledException e) { handler.sendMessage(createMessage(MSG_TOAST, e.getMessage())); } } finish(); }
From source file:mp.teardrop.SongTimeline.java
int addCloudSongs(ArrayList<CloudSongMetadata> cloudSongs, int mode) { ArrayList<Song> timeline = mSongs; synchronized (this) { saveActiveSongs();//from w w w. j av a2 s . c om switch (mode) { case MODE_ENQUEUE: case MODE_ENQUEUE_POS_FIRST: case MODE_ENQUEUE_ID_FIRST: break; case MODE_PLAY_NEXT: timeline.subList(mCurrentPos + 1, timeline.size()).clear(); break; case MODE_PLAY: case MODE_PLAY_POS_FIRST: case MODE_PLAY_ID_FIRST: timeline.clear(); mCurrentPos = 0; break; default: throw new IllegalArgumentException("Invalid mode: " + mode); } /* int start = timeline.size(); Song jumpSong = null; */ for (CloudSongMetadata cloudSong : cloudSongs) { Song song = new Song(true, cloudSong.path, cloudSong.title, cloudSong.album, cloudSong.artist, 1); song.dropboxLinkCreated = new Date(); //it was created only seconds ago when the // user picked the songs in the library if (cloudSong.rgTrack != 0f) song.rgTrack = cloudSong.rgTrack; if (cloudSong.rgAlbum != 0f) song.rgAlbum = cloudSong.rgAlbum; song.dbPath = cloudSong.dbPath; timeline.add(song); } /* if (mShuffleMode != SHUFFLE_NONE) MediaUtils.shuffle(timeline.subList(start, timeline.size()), mShuffleMode == SHUFFLE_ALBUMS); */ broadcastChangedSongs(); } changed(); return cloudSongs.size(); }
From source file:org.sakaiproject.tool.assessment.ui.bean.evaluation.SubmissionStatusBean.java
protected void init() { defaultSearchString = ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages", "search_default_student_search_string"); if (searchString == null) { searchString = defaultSearchString; }/*from w ww. j av a 2 s .com*/ // Get allAgents only at the first time if (allAgents == null) { allAgents = getAllAgents(); } ArrayList matchingAgents; if (isFilteredSearch()) { matchingAgents = findMatchingAgents(searchString); } else { matchingAgents = allAgents; } scoreDataRows = matchingAgents.size(); ArrayList newAgents = new ArrayList(); if (maxDisplayedScoreRows == 0) { newAgents = matchingAgents; } else { int nextPageRow = Math.min(firstScoreRow + maxDisplayedScoreRows, scoreDataRows); newAgents = new ArrayList(matchingAgents.subList(firstScoreRow, nextPageRow)); log.debug("init(): subList " + firstScoreRow + ", " + nextPageRow); } agents = newAgents; }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.FLIMClasses.Classes.FindMaxpoint.java
public void acqMaxpointData() { ArrayList<Integer> signal = new ArrayList<Integer>(); ArrayList<Integer> delays = new ArrayList<Integer>(); // instrument interacting fn, currently dummy // REMEMBER TO APPLY THRESHOLD // plot maxpoint data findMaxpointData_ = createDummyMaxpointData(0); XYPlot plot = chart_.getXYPlot();//www . ja v a 2s . com plot.setDataset(0, findMaxpointData_); // assign maxpoint - easier when this is real data... ArrayList<XYDataItem> dummy = new ArrayList<XYDataItem>( ((XYSeriesCollection) findMaxpointData_).getSeries(0).getItems()); for (XYDataItem dummy1 : dummy) { delays.add((Integer) dummy1.getX().intValue()); signal.add((Integer) dummy1.getY().intValue()); } int[] res = findMaxIndex(signal); maxpointDelay_ = delays.get(res[0]); // estimate lifetime signal = new ArrayList<Integer>(signal.subList(res[0], signal.size())); delays = new ArrayList<Integer>(delays.subList(res[0], delays.size())); double sumt2 = 0; double sumt = 0; double sumtlnI = 0; double sumlnI = 0; for (int i = 0; i < signal.size(); i++) { sumt2 = sumt2 + delays.get(i) * delays.get(i); sumt = sumt + delays.get(i); sumlnI = (sumlnI + log((double) signal.get(i))); sumtlnI = sumtlnI + log((double) signal.get(i)) * delays.get(i); } lifetime_ = -(delays.size() * sumt2 - sumt * sumt) / (delays.size() * sumtlnI - sumt * sumlnI); }