List of usage examples for java.util ArrayList isEmpty
public boolean isEmpty()
From source file:com.yahoo.egads.models.adm.AdaptiveKernelDensityChangePointDetector.java
@Override public IntervalSequence detect(DataSequence observedSeries, DataSequence expectedSeries) throws Exception { if (observedSeries.size() != expectedSeries.size()) { throw new Exception("The observed time-series must have the same length as the expected time-series."); }//from w w w . jav a2s . c o m long unixTime = System.currentTimeMillis() / 1000L; IntervalSequence result = new IntervalSequence(); int n = observedSeries.size(); float[] residuals = new float[n]; // Computing the residuals for (int i = 0; i < n; ++i) { residuals[i] = observedSeries.get(i).value - expectedSeries.get(i).value; } // Detecting change points ArrayList<Integer> changePoints = detectChangePoints(residuals, this.preWindowSize, this.postWindowSize, this.confidence); // Preparing the output if (this.outputDest.equals("STD_OUT_ALL")) { int j = 0; for (int i = 0; i < n; ++i) { boolean isCP = false; if (!changePoints.isEmpty()) { isCP = (changePoints.get(j) == i); } if (isCP && j < (changePoints.size() - 1)) { j++; } logger.debug("TS:" + observedSeries.get(i).time + ",SC:" + String.join(":", arrayF2S(new Float[] { score[i] })) + ",LV:" + arrayF2S(new Float[] { level[i] }) + ",OV:" + observedSeries.get(i).value + ",EV:" + expectedSeries.get(i).value); result.add(new Interval(observedSeries.get(i).time, i, new Float[] { score[i] }, new Float[] { level[i] }, observedSeries.get(i).value, expectedSeries.get(i).value, (isCP))); } } else { for (int index : changePoints) { if (((unixTime - observedSeries.get(index).time) / 3600) < maxHrsAgo) { result.add(new Interval(observedSeries.get(index).time, index, new Float[] { score[index] }, new Float[] { level[index] }, observedSeries.get(index).value, expectedSeries.get(index).value)); } } } return result; }
From source file:com.hpe.application.automation.tools.pc.PcClient.java
public void waitForRunToPublishOnTrendReport(int runId, String trendReportId) throws PcException, IOException, InterruptedException { ArrayList<PcTrendedRun> trendReportMetaDataResultsList; boolean publishEnded = false; int counter = 0; do {/*from ww w .j ava 2 s . c o m*/ trendReportMetaDataResultsList = restProxy.getTrendReportMetaData(trendReportId); if (trendReportMetaDataResultsList.isEmpty()) break; for (PcTrendedRun result : trendReportMetaDataResultsList) { if (result.getRunID() != runId) continue; if (result.getState().equals(PcBuilder.TRENDED) || result.getState().equals(PcBuilder.ERROR)) { publishEnded = true; logger.println("Run: " + runId + " publishing status: " + result.getState()); break; } else { Thread.sleep(5000); counter++; if (counter >= 120) { String msg = "Error: Publishing didn't ended after 10 minutes, aborting..."; throw new PcException(msg); } } } } while (!publishEnded && counter < 120); }
From source file:net.pms.dlna.CueFolder.java
@Override protected void resolveOnce() { if (playlistfile.length() < 10000000) { CueSheet sheet;/* w w w .ja va 2 s . c om*/ try { sheet = CueParser.parse(playlistfile); } catch (IOException e) { logger.info("Error in parsing cue: " + e.getMessage()); return; } if (sheet != null) { List<FileData> files = sheet.getFileData(); // only the first one if (files.size() > 0) { FileData f = files.get(0); List<TrackData> tracks = f.getTrackData(); Player defaultPlayer = null; DLNAMediaInfo originalMedia = null; ArrayList<DLNAResource> addedResources = new ArrayList<DLNAResource>(); for (int i = 0; i < tracks.size(); i++) { TrackData track = tracks.get(i); if (i > 0) { double end = getTime(track.getIndices().get(0).getPosition()); if (addedResources.isEmpty()) { // seems the first file was invalid or non existent return; } DLNAResource prec = addedResources.get(i - 1); int count = 0; while (prec.isFolder() && i + count < addedResources.size()) { // not used anymore prec = addedResources.get(i + count); count++; } prec.getSplitRange().setEnd(end); prec.getMedia().setDuration(prec.getSplitRange().getDuration()); logger.debug("Track #" + i + " split range: " + prec.getSplitRange().getStartOrZero() + " - " + prec.getSplitRange().getDuration()); } Position start = track.getIndices().get(0).getPosition(); RealFile realFile = new RealFile(new File(playlistfile.getParentFile(), f.getFile())); addChild(realFile); addedResources.add(realFile); if (i > 0 && realFile.getMedia() == null) { realFile.setMedia(new DLNAMediaInfo()); realFile.getMedia().setMediaparsed(true); } realFile.resolve(); if (i == 0) { originalMedia = realFile.getMedia(); } realFile.getSplitRange().setStart(getTime(start)); realFile.setSplitTrack(i + 1); // assign a splitter engine if file is natively supported by the renderer if (realFile.getPlayer() == null) { if (defaultPlayer == null) { /* XXX why are we creating new player instances? aren't they supposed to be singletons? TODO don't hardwire the player here; leave it to the player factory to select the right player for the resource's format e.g: defaultPlayer = PlayerFactory.getPlayer(realFile); */ if (realFile.getFormat() == null) { logger.error( "No file format known for file \"{}\", assuming it is a video for now.", realFile.getName()); /* TODO (see above): r.resolveFormat(); // sets the format based on the filename defaultPlayer = PlayerFactory.getPlayer(realFile); */ defaultPlayer = new MEncoderVideo(configuration); } else { if (realFile.getFormat().isAudio()) { defaultPlayer = new FFmpegAudio(configuration); } else { defaultPlayer = new MEncoderVideo(configuration); } } } realFile.setPlayer(defaultPlayer); } if (realFile.getMedia() != null) { try { realFile.setMedia((DLNAMediaInfo) originalMedia.clone()); } catch (CloneNotSupportedException e) { logger.info("Error in cloning media info: " + e.getMessage()); } if (realFile.getMedia() != null && realFile.getMedia().getFirstAudioTrack() != null) { if (realFile.getFormat().isAudio()) { realFile.getMedia().getFirstAudioTrack().setSongname(track.getTitle()); } else { realFile.getMedia().getFirstAudioTrack().setSongname("Chapter #" + (i + 1)); } realFile.getMedia().getFirstAudioTrack().setTrack(i + 1); realFile.getMedia().setSize(-1); if (StringUtils.isNotBlank(sheet.getTitle())) { realFile.getMedia().getFirstAudioTrack().setAlbum(sheet.getTitle()); } if (StringUtils.isNotBlank(sheet.getPerformer())) { realFile.getMedia().getFirstAudioTrack().setArtist(sheet.getPerformer()); } if (StringUtils.isNotBlank(track.getPerformer())) { realFile.getMedia().getFirstAudioTrack().setArtist(track.getPerformer()); } } } } if (tracks.size() > 0 && addedResources.size() > 0) { DLNAResource lastTrack = addedResources.get(addedResources.size() - 1); Time lastTrackSplitRange = lastTrack.getSplitRange(); DLNAMediaInfo lastTrackMedia = lastTrack.getMedia(); if (lastTrackSplitRange != null && lastTrackMedia != null) { lastTrackSplitRange.setEnd(lastTrackMedia.getDurationInSeconds()); lastTrackMedia.setDuration(lastTrackSplitRange.getDuration()); logger.debug("Track #" + childrenNumber() + " split range: " + lastTrackSplitRange.getStartOrZero() + " - " + lastTrackSplitRange.getDuration()); } } PMS.get().storeFileInCache(playlistfile, Format.PLAYLIST); } } } }
From source file:coolmap.application.widget.impl.WidgetUserGroup.java
private void createNewGroup(ArrayList<VNode> nodes) { if (nodes.isEmpty()) { Messenger.showWarningMessage("Could not create new node group.\nNo nodes were selected.", "Selection error"); return;/*from ww w . j a v a 2 s . c o m*/ } String groupName = JOptionPane.showInputDialog(CoolMapMaster.getCMainFrame(), "Name for new node group."); if (groupName == null || groupName.length() == 0) { groupName = "Untitled"; } int counter = 0; String name = groupName; while (nodeGroups.containsKey(name)) { counter++; name = groupName + "_" + counter; } groupName = name; Color c = UI.randomColor(); ArrayList<VNode> groupNodes = new ArrayList<VNode>(); for (VNode node : nodes) { VNode copy = node.duplicate(); copy.setParentNode(null); //remove parent! copy.setViewColor(c); nodeGroups.put(groupName, copy); } if (!nodeColor.containsKey(groupName)) { nodeColor.put(groupName, c); } updateTable(); }
From source file:com.cloudera.impala.planner.PlannerTestBase.java
/** * Extracts and returns the expected error message from expectedPlan. * Returns null if expectedPlan is empty or its first element is not an error message. * The accepted format for error messages is 'not implemented: expected error message' * Returns the empty string if expectedPlan starts with 'not implemented' but no * expected error message was given./*from w w w.j a v a2 s . com*/ */ private String getExpectedErrorMessage(ArrayList<String> expectedPlan) { if (expectedPlan == null || expectedPlan.isEmpty()) return null; if (!expectedPlan.get(0).toLowerCase().startsWith("not implemented")) return null; // Find first ':' and extract string on right hand side as error message. int ix = expectedPlan.get(0).indexOf(":"); if (ix + 1 > 0) { return expectedPlan.get(0).substring(ix + 1).trim(); } else { return ""; } }
From source file:msgclient.MsgClient.java
public void getMessages() throws Exception { // Call the server to get recent mail ArrayList<EncryptedMessage> messages = mServerConnection.lookupMessages(); if (messages == null) { System.out.println("Invalid response from server"); return;//from ww w.j a va 2 s . co m } // Decrypt and process each message if (messages == null || messages.isEmpty()) { //System.out.println("No new messages."); } else { Iterator<EncryptedMessage> iterator = messages.iterator(); while (iterator.hasNext()) { EncryptedMessage nextMessage = iterator.next(); //System.out.println("Received an encrypted message"); // We need to get the sender's public key MsgKeyPair senderKey = mServerConnection.lookupKey(nextMessage.getSenderID()); if (senderKey != null) { String decryptedText = mEncryptor.decryptMessage(nextMessage.getMessageText(), nextMessage.getSenderID(), senderKey); if (decryptedText != null) { if (isReadReceipt(decryptedText) == false) { // Add the decrypted message to our pending messages list Message newMessage = new Message(nextMessage.getSenderID(), nextMessage.getReceiverID(), decryptedText, nextMessage.getSentTime(), nextMessage.getMessageID()); // Make sure we don't mess with the object thread locks, // since the mPendingMessages member can be accessed by // a different thread. synchronized (mPendingMessages) { mPendingMessages.add(newMessage); //System.out.println("Got a message!"); } sendReadReceipt(nextMessage.getSenderID(), nextMessage.getMessageID()); } } } else { //System.out.println("Could not get keys for " + nextMessage.getSenderID()); } } } }
From source file:com.nononsenseapps.notepad.sync.SyncAdapter.java
@SuppressWarnings("unchecked") @Override/* w w w .j a va 2 s. c o m*/ public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); // Only sync if it has been enabled by the user, and account is selected // Issue on reinstall where account approval is remembered by system if (settings.getBoolean(SyncPrefs.KEY_SYNC_ENABLE, false) && !settings.getString(SyncPrefs.KEY_ACCOUNT, "").isEmpty() && account.name.equals(settings.getString(SyncPrefs.KEY_ACCOUNT, ""))) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "onPerformSync"); Intent i = new Intent(SYNC_STARTED); mContext.sendBroadcast(i); // For later Intent doneIntent = new Intent(SYNC_FINISHED); doneIntent.putExtra(SYNC_RESULT, ERROR); // Initialize necessary stuff GoogleDBTalker dbTalker = new GoogleDBTalker(account.name, provider); GoogleAPITalker apiTalker = new GoogleAPITalker(); try { boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE, NOTIFY_AUTH_FAILURE); if (connected) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "We got an authToken atleast"); try { // FIrst of all, we need the latest updated time later. // So // save // that for now. // This is the latest time we synced String lastUpdate = dbTalker.getLastUpdated(account.name); //String lastUpdate = settings.getString(PREFS_LAST_SYNC_DATE, null); // Get the latest hash value we saw on the server String localEtag = settings.getString(PREFS_LAST_SYNC_ETAG, ""); // Prepare lists for items ArrayList<GoogleTaskList> listsToSaveToDB = new ArrayList<GoogleTaskList>(); HashMap<GoogleTaskList, ArrayList<GoogleTask>> tasksInListToSaveToDB = new HashMap<GoogleTaskList, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> tasksInListToUpload = new HashMap<Long, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> allTasksInList = new HashMap<Long, ArrayList<GoogleTask>>(); // gets all tasks in one query ArrayList<GoogleTask> allTasks = dbTalker.getAllTasks(allTasksInList, tasksInListToUpload); ArrayList<GoogleTaskList> listsToUpload = new ArrayList<GoogleTaskList>(); ArrayList<GoogleTaskList> allLocalLists = new ArrayList<GoogleTaskList>(); // gets all lists in one query dbTalker.getAllLists(allLocalLists, listsToUpload); // Get the current hash value on the server and all // remote // lists if upload is not true String serverEtag = apiTalker.getModifiedLists(localEtag, allLocalLists, listsToSaveToDB); // IF the tags match, then nothing has changed on // server. if (localEtag.equals(serverEtag)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags match, nothing to download"); } else { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags dont match, downloading new tasks"); // Download tasks which have been updated since last // time for (GoogleTaskList list : listsToSaveToDB) { if (list.id != null && !list.id.isEmpty()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Saving remote modified tasks for: " + list.id); tasksInListToSaveToDB.put(list, list.downloadModifiedTasks(apiTalker, allTasks, lastUpdate)); } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Getting stuff we want to upload"); // Get stuff we would like to upload to server // In case of lists, locally modified versions always // wins // in // conflict, so nothing more to do for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> moddedTasks = tasksInListToUpload.get(list.dbId); if (moddedTasks != null && !moddedTasks.isEmpty()) { // There are some tasks here which we want to // upload if (SYNC_DEBUG_PRINTS) Log.d(TAG, "List id " + list.dbId + ", Locally modified tasks found: " + moddedTasks.size()); // Now we need to handle possible conflicts in // the // tasks. But this has already been sorted when // we // downloaded them // For any task which exists in stuffToSaveToDB, // we // should not upload it // Iterate over a clone to avoid concurrency // problems since we will be modifying // the list during iteration for (GoogleTask moddedTask : (ArrayList<GoogleTask>) moddedTasks.clone()) { ArrayList<GoogleTask> tasksToBeSaved = tasksInListToSaveToDB.get(list); if (tasksToBeSaved != null && tasksToBeSaved.contains(moddedTask)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "This modified task was newer on server, removing from upload list: " + moddedTask.title); moddedTasks.remove(moddedTask); } // In the case that a task has been deleted // before it was synced the first time // We should definitely not sync it. Only // delete // it later if (moddedTask.deleted == 1 && (moddedTask.id == null || moddedTask.id.isEmpty())) { moddedTasks.remove(moddedTask); } } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading lists"); // First thing we want to do is upload stuff, because // some // values are updated then boolean uploadedStuff = false; // Start with lists for (GoogleTaskList list : listsToUpload) { GoogleTaskList result = apiTalker.uploadList(list); uploadedStuff = true; if (result != null) { // Make sure that local version is the same as // server's for (GoogleTaskList localList : allLocalLists) { if (result.equals(localList)) { localList.title = result.title; localList.id = result.id; result.dbId = localList.dbId; break; } } listsToSaveToDB.add(result); } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading tasks"); // Right, now upload tasks for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> tasksToUpload = tasksInListToUpload.get(list.dbId); if (tasksToUpload != null) { for (GoogleTask task : tasksToUpload) { GoogleTask result = apiTalker.uploadTask(task, list); uploadedStuff = true; // Task now has relevant fields set. Add to // DB-list if (tasksInListToSaveToDB.get(list) == null) tasksInListToSaveToDB.put(list, new ArrayList<GoogleTask>()); tasksInListToSaveToDB.get(list).add(result); } } } // Finally, get the updated etag from the server and // save. // Only worth doing if we actually uploaded anything // Also, only do this if we are doing a full sync String currentEtag = serverEtag; if (uploadedStuff) { currentEtag = apiTalker.getEtag(); //lastUpdate = dbTalker.getLastUpdated(account.name); } settings.edit().putString(PREFS_LAST_SYNC_ETAG, currentEtag) //.putString(PREFS_LAST_SYNC_DATE, lastUpdate) .commit(); // Now, set sorting values. for (GoogleTaskList list : tasksInListToSaveToDB.keySet()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values in: " + list.id); ArrayList<GoogleTask> tasks = tasksInListToSaveToDB.get(list); if (tasks != null) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values for #tasks: " + tasks.size()); ArrayList<GoogleTask> allListTasks = allTasksInList.get(list.dbId); list.setSortingValues(tasks, allListTasks); } } // Save to database in a single transaction if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Save stuff to DB"); dbTalker.SaveToDatabase(listsToSaveToDB, tasksInListToSaveToDB); // Commit it ContentProviderResult[] result = dbTalker.apply(); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Sync Complete!"); doneIntent.putExtra(SYNC_RESULT, SUCCESS); } catch (ClientProtocolException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "ClientProtocolException: " + e.getLocalizedMessage()); } catch (JSONException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "JSONException: " + e.getLocalizedMessage()); } catch (IOException e) { syncResult.stats.numIoExceptions++; if (SYNC_DEBUG_PRINTS) Log.d(TAG, "IOException: " + e.getLocalizedMessage()); } catch (RemoteException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "RemoteException: " + e.getLocalizedMessage()); } catch (OperationApplicationException e) { Log.d(TAG, "Joined operation failed: " + e.getLocalizedMessage()); } catch (ClassCastException e) { // GetListofLists will cast this if it returns a string. It should not return a string // but it did... Log.d(TAG, "ClassCastException: " + e.getLocalizedMessage()); } } else { // return real failure if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Could not get authToken. Reporting authException"); syncResult.stats.numAuthExceptions++; doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL); } } finally { // This must always be called or we will leak resources if (apiTalker != null) { apiTalker.closeClient(); } mContext.sendBroadcast(doneIntent); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "SyncResult: " + syncResult.toDebugString()); } } }
From source file:userInteface.Patient.ManageVitalSignsJPanel.java
private void populatePatientsTable(ArrayList<Person> personList) { DefaultTableModel model = (DefaultTableModel) viewPatientsJTable.getModel(); model.setRowCount(0);/*from w ww .ja v a 2 s. c om*/ if (personList.isEmpty()) { JOptionPane.showMessageDialog(this, "No Persons found. Please add Persons", "Error", JOptionPane.INFORMATION_MESSAGE); return; } for (Person person : personList) { Object[] row = new Object[3]; row[0] = person; row[1] = person.getAge(); if (person.getPatient() != null) { row[2] = person.getPatient().getPatientID(); } else { row[2] = "Patient Not Created"; } model.addRow(row); } }
From source file:com.datos.vfs.provider.AbstractFileSystem.java
/** * Removes a listener from a file in this file system. * @param file The FileObject to be monitored. * @param listener The FileListener/* w w w. j a v a 2s . c o m*/ */ @Override public void removeListener(final FileObject file, final FileListener listener) { synchronized (listenerMap) { final ArrayList<?> listeners = listenerMap.get(file.getName()); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { listenerMap.remove(file.getName()); } } } }
From source file:biblivre3.cataloging.authorities.AuthoritiesBO.java
public AuthoritySearchResultsDTO search(String searchTerms, int offset) { AuthoritySearchResultsDTO dto = new AuthoritySearchResultsDTO(); try {//from www . j a v a2s . c om dto.al = new ArrayList<AuthoritiesResultRow>(); ArrayList<AuthorityRecordDTO> authorities; String[] searchArray = null; if (searchTerms != null) { searchArray = TextUtils.removeDiacriticals(searchTerms).toLowerCase().split("\\s+"); } if (searchArray == null) { authorities = dao.list(offset, recordsPPage); } else { authorities = dao.search(searchArray, offset, recordsPPage); } if (!authorities.isEmpty()) { for (AuthorityRecordDTO authRecord : authorities) { Record fmRecord = MarcUtils.iso2709ToRecord(authRecord.getIso2709()); AuthoritiesResultRow rr = new AuthoritiesResultRow(); rr.setRecordSerial(String.valueOf(authRecord.getRecordId())); rr.setName(Indexer.listPrimaryAuthor(fmRecord)); rr.setCreated(authRecord.getCreated()); rr.setModified(authRecord.getModified()); dto.al.add(rr); } int total; if (searchTerms == null) { total = dao.countAll(); } else { total = dao.count(searchArray); } int nroPages = total / recordsPPage; int mod = total % recordsPPage; dto.recordsPerPage = recordsPPage; dto.totalRecords = total; dto.totalPages = mod == 0 ? nroPages : nroPages + 1; dto.currentPage = (offset / recordsPPage) + 1; return dto; } } catch (Exception e) { System.out.println("[AUTHBO.searchAuthorities(..)] Exception: " + e); } return null; }