List of usage examples for java.util ArrayList remove
public boolean remove(Object o)
From source file:com.farmerbb.notepad.fragment.NoteListFragment.java
private void listNotes() { // Get array of file names String[] listOfFiles = getActivity().getFilesDir().list(); ArrayList<String> listOfNotes = new ArrayList<>(); // Get number of files int numOfNotes = listOfFiles.length; // Remove any files from the list that aren't notes for (String listOfFile : listOfFiles) { if (NumberUtils.isCreatable(listOfFile)) listOfNotes.add(listOfFile); else//from www. j av a 2s.c o m numOfNotes--; } // Create arrays of note lists String[] listOfNotesByDate = new String[numOfNotes]; String[] listOfNotesByName = new String[numOfNotes]; NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes]; NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes]; ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes); for (int i = 0; i < numOfNotes; i++) { listOfNotesByDate[i] = listOfNotes.get(i); } // If sort-by is "by date", sort in reverse order if (sortBy.startsWith("date")) { Arrays.sort(listOfNotesByDate, Collections.reverseOrder()); if (sortBy.endsWith("reversed")) ArrayUtils.reverse(listOfNotesByDate); } // Get array of first lines of each note for (int i = 0; i < numOfNotes; i++) { try { String title = listener.loadNoteTitle(listOfNotesByDate[i]); String date = listener.loadNoteDate(listOfNotesByDate[i]); listOfTitlesByDate[i] = new NoteListItem(title, date); } catch (IOException e) { showToast(R.string.error_loading_list); } } // If sort-by is "by name", sort alphabetically if (sortBy.startsWith("name")) { // Copy titles array System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes); // Sort titles Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle); if (sortBy.endsWith("reversed")) ArrayUtils.reverse(listOfTitlesByName); // Initialize notes array for (int i = 0; i < numOfNotes; i++) listOfNotesByName[i] = "new"; // Copy filenames array with new sort order of titles and nullify date arrays for (int i = 0; i < numOfNotes; i++) { for (int j = 0; j < numOfNotes; j++) { if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote()) && listOfNotesByName[i].equals("new")) { listOfNotesByName[i] = listOfNotesByDate[j]; listOfNotesByDate[j] = ""; listOfTitlesByDate[j] = new NoteListItem("", ""); } } } // Populate ArrayList with notes, showing name as first line of the notes list.addAll(Arrays.asList(listOfTitlesByName)); } else if (sortBy.startsWith("date")) list.addAll(Arrays.asList(listOfTitlesByDate)); // Create the custom adapters to bind the array to the ListView final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list); final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list); // Display the ListView if (showDate) listView.setAdapter(dateAdapter); else listView.setAdapter(adapter); listView.setSelection(ScrollPositions.getInstance().getPosition()); // Finalize arrays to prepare for handling clicked items final String[] finalListByDate = listOfNotesByDate; final String[] finalListByName = listOfNotesByName; // Make ListView handle clicked items listView.setClickable(true); listView.setOnItemClickListener((arg0, arg1, position, arg3) -> { ScrollPositions.getInstance().setPosition(listView.getFirstVisiblePosition()); if (sortBy.startsWith("date")) { if (directEdit) listener.editNote(finalListByDate[position]); else listener.viewNote(finalListByDate[position]); } else if (sortBy.startsWith("name")) { if (directEdit) listener.editNote(finalListByName[position]); else listener.viewNote(finalListByName[position]); } }); // Make ListView handle contextual action bar final ArrayList<String> cab = listener.getCabArray(); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); listView.setMultiChoiceModeListener(new MultiChoiceModeListener() { @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // Respond to clicks on the actions in the CAB switch (item.getItemId()) { case R.id.action_select_all: cab.clear(); for (int i = 0; i < listView.getAdapter().getCount(); i++) { listView.setItemChecked(i, true); } return false; case R.id.action_export: if (cab.size() > 0) { mode.finish(); // Action picked, so close the CAB listener.exportNotes(); return true; } else { showToast(R.string.no_notes_to_export); return false; } case R.id.action_delete: if (cab.size() > 0) { mode.finish(); // Action picked, so close the CAB listener.deleteNotes(); return true; } else { showToast(R.string.no_notes_to_delete); return false; } default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { listener.hideFab(); // Inflate the menu for the CAB MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); // Clear any old values from cab array cab.clear(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { listener.showFab(); } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (position > -1) { // Add/remove filenames to cab array as they are checked/unchecked if (checked) { if (sortBy.startsWith("date")) cab.add(finalListByDate[position]); if (sortBy.startsWith("name")) cab.add(finalListByName[position]); } else { if (sortBy.startsWith("date")) cab.remove(finalListByDate[position]); if (sortBy.startsWith("name")) cab.remove(finalListByName[position]); } listView.setItemChecked(-1, false); } // Update the title in CAB mode.setTitle(cab.size() + " " + listener.getCabString(cab.size())); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } }); if (cab.size() > 0) { List<String> cabClone = new ArrayList<>(cab); cab.clear(); String[] array = null; if (sortBy.startsWith("date")) array = finalListByDate; if (sortBy.startsWith("name")) array = finalListByName; if (array != null) { for (String filename : cabClone) { for (int i = 0; i < array.length; i++) { if (filename.equals(array[i])) listView.setItemChecked(i, true); } } } } // If there are no saved notes, then display the empty view if (numOfNotes == 0) { TextView empty = getActivity().findViewById(R.id.empty); listView.setEmptyView(empty); } }
From source file:com.amalto.workbench.utils.XSDAnnotationsStructure.java
/**************************************************************************** * WRITE ACCESS//from w w w . j a va 2 s. c om * * @throws XtentisException ****************************************************************************/ public boolean setAccessRole(Collection<String> roles, boolean recursive, IStructuredContentProvider provider, String access) throws Exception { XSDSchema xsd = schema != null ? schema : declaration.getSchema(); String xsdString = Util.nodeToString(xsd.getDocument().getDocumentElement()); if (recursive) { ArrayList<Object> objList = new ArrayList<Object>(); XSDComponent component = declaration; if (declaration == null) { component = this.componet; } Object[] objs = Util.getAllObject(component, objList, provider); while (objs.length > 0) { Object[] objCpys = objs; for (Object obj : objCpys) { if (obj instanceof XSDElementDeclaration || obj instanceof XSDParticle) { boolean isImported = false; if (obj instanceof XSDParticle) { XSDParticle particle = (XSDParticle) obj; if (particle.getTerm() instanceof XSDElementDeclaration) { XSDElementDeclaration decl = (XSDElementDeclaration) particle.getTerm(); if (Util.IsAImporedElement(decl, xsdString)) { XSDTypeDefinition typeDef = decl.getTypeDefinition(); if (Util.IsAImporedElement(typeDef, xsdString)) { isImported = true; } } } } else if (obj instanceof XSDElementDeclaration) { XSDElementDeclaration decl = (XSDElementDeclaration) obj; if (Util.IsAImporedElement(decl, xsdString)) { isImported = true; } } if (!isImported) { XSDAnnotationsStructure annotion = new XSDAnnotationsStructure((XSDComponent) obj); // see 7993, if UUID/AUTO_INCREMENT ,should not add write access if (obj instanceof XSDParticle) { XSDParticle o = (XSDParticle) obj; // String name=Util.getFirstTextNode(o.getElement(), "@name"); String type = Util.getFirstTextNode(o.getElement(), "@type");//$NON-NLS-1$ if (EUUIDCustomType.AUTO_INCREMENT.equals(type) || EUUIDCustomType.UUID.equals(type)) { objList.remove(obj); objs = objList.toArray(); continue; } } annotion.removeAppInfos(access); // X_Write for (Iterator<String> iter = roles.iterator(); iter.hasNext();) { String role = iter.next(); annotion.addAppInfo(access, role); } } } objList.remove(obj); objs = objList.toArray(); } } return setAccessRole(roles, access); } else { if (Util.IsAImporedElement(declaration, xsdString)) { return false; } return setAccessRole(roles, access); } }
From source file:CB_Core.Api.GroundspeakAPI.java
/** * Gets the Logs for the given Cache/*from w w w . j av a 2s .c o m*/ * * @param Staging * Config.settings.StagingAPI.getValue() * @param accessToken * @param conectionTimeout * Config.settings.conection_timeout.getValue() * @param socketTimeout * Config.settings.socket_timeout.getValue() * @param cache * @return */ public static int GetGeocacheLogsByCache(Cache cache, ArrayList<LogEntry> logList, boolean all, cancelRunnable cancelRun) { String finders = CB_Core_Settings.Friends.getValue(); String[] finder = finders.split("\\|"); ArrayList<String> finderList = new ArrayList<String>(); for (String f : finder) { finderList.add(f); } if (cache == null) return -3; int chk = chkMembership(false); if (chk < 0) return chk; try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } int start = 1; int count = 30; String URL = CB_Core_Settings.StagingAPI.getValue() ? STAGING_GS_LIVE_URL : GS_LIVE_URL; while (!cancelRun.cancel() && (finderList.size() > 0 || all)) // Schleife, solange bis entweder keine Logs mehr geladen werden oder bis alle Logs aller Finder geladen sind. { try { String requestString = ""; requestString += "&AccessToken=" + GetAccessToken(); requestString += "&CacheCode=" + cache.getGcCode(); requestString += "&StartIndex=" + start; requestString += "&MaxPerPage=" + count; HttpGet httppost = new HttpGet(URL + "GetGeocacheLogsByCacheCode?format=json" + requestString); // set time outs HttpUtils.conectionTimeout = CB_Core_Settings.conection_timeout.getValue(); HttpUtils.socketTimeout = CB_Core_Settings.socket_timeout.getValue(); // Execute HTTP Post Request String result = HttpUtils.Execute(httppost, cancelRun); if (result.contains("The service is unavailable")) { return API_IS_UNAVAILABLE; } try // Parse JSON Result { JSONTokener tokener = new JSONTokener(result); JSONObject json = (JSONObject) tokener.nextValue(); JSONObject status = json.getJSONObject("Status"); if (status.getInt("StatusCode") == 0) { result = ""; JSONArray geocacheLogs = json.getJSONArray("Logs"); for (int ii = 0; ii < geocacheLogs.length(); ii++) { JSONObject jLogs = (JSONObject) geocacheLogs.get(ii); JSONObject jFinder = (JSONObject) jLogs.get("Finder"); JSONObject jLogType = (JSONObject) jLogs.get("LogType"); LogEntry log = new LogEntry(); log.CacheId = cache.Id; log.Comment = jLogs.getString("LogText"); log.Finder = jFinder.getString("UserName"); if (!finderList.contains(log.Finder)) { continue; } finderList.remove(log.Finder); log.Id = jLogs.getInt("ID"); log.Timestamp = new Date(); try { String dateCreated = jLogs.getString("VisitDate"); int date1 = dateCreated.indexOf("/Date("); int date2 = dateCreated.indexOf("-"); String date = (String) dateCreated.subSequence(date1 + 6, date2); log.Timestamp = new Date(Long.valueOf(date)); } catch (Exception exc) { logger.error("SearchForGeocaches_ParseLogDate", exc); } log.Type = LogTypes.GC2CB_LogType(jLogType.getInt("WptLogTypeId")); logList.add(log); } if ((geocacheLogs.length() < count) || (finderList.size() == 0)) { return 0; // alle Logs des Caches geladen oder alle gesuchten Finder gefunden } } else { result = "StatusCode = " + status.getInt("StatusCode") + "\n"; result += status.getString("StatusMessage") + "\n"; result += status.getString("ExceptionDetails"); LastAPIError = result; return (-1); } } catch (JSONException e) { e.printStackTrace(); } } catch (ConnectTimeoutException e) { logger.error("GetGeocacheLogsByCache ConnectTimeoutException", e); return CONNECTION_TIMEOUT; } catch (UnsupportedEncodingException e) { logger.error("GetGeocacheLogsByCache UnsupportedEncodingException", e); return ERROR; } catch (ClientProtocolException e) { logger.error("GetGeocacheLogsByCache ClientProtocolException", e); return ERROR; } catch (IOException e) { logger.error("GetGeocacheLogsByCache IOException", e); return ERROR; } // die nchsten Logs laden start += count; } return (-1); }
From source file:edu.eurac.commul.pepperModules.mmax2.MMAX22SaltMapper.java
private void completeSDomRel(SDominanceRelation sDomRel, SaltExtendedMarkable markable) { MarkableAttribute structAttribute = null; MarkableAttribute structSchemeAttribute = null; MarkableAttribute targetAttribute = null; MarkableAttribute targetSchemeAttribute = null; MarkableAttribute containerPointerAttribute = null; ArrayList<MarkableAttribute> markableAttributes = markable.getAttributes(); for (MarkableAttribute markableAttribute : markableAttributes) { if (markableAttribute.getName().equals("struct")) { structAttribute = markableAttribute; } else if (markableAttribute.getName().equals("struct_scheme")) { structSchemeAttribute = markableAttribute; } else if (markableAttribute.getName().equals("target")) { targetAttribute = markableAttribute; } else if (markableAttribute.getName().equals("target_scheme")) { targetSchemeAttribute = markableAttribute; } else if (markableAttribute.getName().equals("source_attr")) { containerPointerAttribute = markableAttribute; }/*from w w w . jav a 2 s. c o m*/ } if (structAttribute == null) throw new PepperModuleDataException(this, "'struct' attribute is missing on Saltextended markable '" + markable + "' representing an SDominationRelation"); markable.removeAttribute(structAttribute); SNode sStruct = null; SNode sStructuredTarget = null; if (structSchemeAttribute != null) {//struct markable is a SContainer SaltExtendedMarkable sStructMarkable = getMarkable(structAttribute.getValue(), structSchemeAttribute.getValue()); if (sStructMarkable == null) throw new PepperModuleDataException(this, "An unknown SContainer markable is referenced as the sStructured target of the pointer within markable '" + markable + "'"); SaltExtendedMarkable sstructContainedMarkable = this.claimSContainer.get(sStructMarkable); sStruct = getSNode(sstructContainedMarkable); if (containerPointerAttribute == null) throw new PepperModuleDataException(this, "'source_attr' attribute is missing on Saltextended markable '" + markable + "' representing an SDominanceRelation"); markableAttributes.remove(containerPointerAttribute); MarkableAttribute pointer = null; String sstructPointerAttribute = containerPointerAttribute.getValue(); for (MarkableAttribute sstructMarkableAttribute : sStructMarkable.getAttributes()) { if (sstructMarkableAttribute.getName().equals(sstructPointerAttribute)) { pointer = sstructMarkableAttribute; break; } } if (pointer == null) throw new PepperModuleDataException(this, "'" + sstructPointerAttribute + "' attribute is missing on SContainer markable '" + sStructMarkable + "'"); sStructMarkable.removeAttribute(pointer); MarkablePointerAttributeFactory pointerFactory = (MarkablePointerAttributeFactory) pointer.getFactory(); SaltExtendedMarkable targetMarkable = getMarkable(pointer.getValue(), pointerFactory.getTargetSchemeName()); if (targetMarkable == null) throw new PepperModuleDataException(this, " An unknown markable is referenced as the target of Saltextended markable '" + markable + "' representing an SDominanceRelation"); SaltExtendedMarkable targetContainedMarkable = this.claimSContainer.get(targetMarkable); sStructuredTarget = getSNode(targetContainedMarkable); if (sStructuredTarget == null) throw new PepperModuleDataException(this, "An unknown target node is referenced as the target for the SDominanceRelation represented by markable '" + markable + "'"); } else { SaltExtendedMarkable sStructMarkable = getMarkable(structAttribute.getValue(), SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSTRUCT); if (sStructMarkable == null) throw new PepperModuleDataException(this, "An unknown markable is referenced as the sStructured source of the pointer within markable '" + markable + "'"); if (targetAttribute == null) throw new PepperModuleDataException(this, "'target' attribute is missing on SContainer markable '" + markable + "'"); markable.removeAttribute(targetAttribute); if (targetSchemeAttribute == null) throw new PepperModuleDataException(this, "'target_scheme' attribute is missing on SContainer markable '" + markable + "'"); markable.removeAttribute(targetSchemeAttribute); SaltExtendedMarkable targetMarkable = getMarkable(targetAttribute.getValue(), targetSchemeAttribute.getValue()); if (targetMarkable == null) throw new PepperModuleDataException(this, " An unknown markable is referenced as the target of markable '" + markable + "' representing an SDominanceRelation"); sStructuredTarget = getSNode(targetMarkable); if (sStructuredTarget == null) throw new PepperModuleDataException(this, "An unknown target node is referenced as the target for the SDominanceRelation represented by markable '" + markable + "'"); } try { sDomRel.setSource((SStructure) sStruct); } catch (ClassCastException e) { throw new PepperModuleDataException(this, "The SNode referenced as source sstruct by SDominanceRelation markable '" + markable + "' is not anymore a SSTructure"); } try { sDomRel.setTarget((SStructuredNode) sStructuredTarget); } catch (ClassCastException e) { throw new PepperModuleDataException(this, "The SNode referenced as target by SDominanceRelation markable '" + markable + "' is not anymore a SStructuredNode"); } }
From source file:com.crushpaper.DbLogic.java
/** Helper method. Does all the real work for restoreMsWordListFormatForUser(). */ public boolean reallyRestoreMsWordListFormatForUser(String userId, InputStreamReader streamReader, boolean isAdmin, Errors errors) { if (userId == null) { Errors.add(errors, errorMessages.errorsUserIdIsNull()); return false; }//ww w . j a va 2s. c o m if (streamReader == null) { Errors.add(errors, errorMessages.errorsTheInputStreamReaderIsNull()); return false; } BufferedReader bf = new BufferedReader(streamReader); final User user = getUserById(userId); if (user == null) { return false; } boolean createdAnyChildren = false; try { final long now = System.currentTimeMillis(); Entry notebook = createEntryNoteBook(user, "Restored Notebook", now, null, null, false, false, false, isAdmin, false, errors); if (notebook == null) { return false; } Entry root = getEntryById(notebook.getRootId()); ArrayList<Entry> parents = new ArrayList<Entry>(); HashMap<String, Integer> bulletToDepth = new HashMap<String, Integer>(); String line = null; Integer previousDepth = 0; parents.add(root); while ((line = bf.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } String note = line; Integer depth = 1; if (line.length() > 1 && line.charAt(1) == '\t') { String bullet = line.substring(0, 1); note = line.substring(2); depth = bulletToDepth.get(bullet); if (depth == null) { depth = new Integer(bulletToDepth.size() + 1); bulletToDepth.put(bullet, depth); } for (int i = parents.size(); i > depth.intValue(); --i) { parents.remove(i - 1); } depth = new Integer(parents.size() + 1); } else { previousDepth = 0; while (parents.size() > 1) { parents.remove(parents.size() - 1); } } if (parents.isEmpty()) { return false; } Entry parent = parents.get(parents.size() - 1); Entry entry = createSimpleEntry(user, note, now, parent.getId(), TreeRelType.Parent, false, false, false, isAdmin, Constants.note, errors, null); if (entry == null) { return false; } if (previousDepth.intValue() != depth.intValue()) { parents.add(entry); } else { parents.set(parents.size() - 1, entry); } createdAnyChildren = true; } } catch (IOException e) { Errors.add(errors, errorMessages.errorProblemReadingInput()); } return createdAnyChildren; }
From source file:civilisation.individu.Humain.java
public ArrayList<Patch> AStar(Patch cible) { int[][] map = new int[getWorldWidth()][getWorldHeight()]; int minx = Math.min(cible.x, xcor()); int maxx = Math.max(cible.x, xcor()); int miny = Math.min(cible.y, ycor()); int maxy = Math.max(cible.y, ycor()); int addi = 0; int nb = 0;/* w ww .j a va 2s .c om*/ int min = 10000; for (int l = 0; l < Configuration.terrains.size(); l++) { if (Configuration.terrains.get(l).getInfranchissable() == false) { nb++; addi += Configuration.terrains.get(l).getPassabilite(); if (Configuration.terrains.get(l).getPassabilite() < min) { min = Configuration.terrains.get(l).getPassabilite(); } } } int defaut = min /*addi/nb*/; for (int i = minx - Configuration.VisionRadius * 6; i < maxx + Configuration.VisionRadius * 6; i++) { for (int j = miny - Configuration.VisionRadius * 4; j < maxy + Configuration.VisionRadius * 4; j++) { if (i > 0 && i < getWorldWidth() && j > 0 && j < getWorldHeight()) { map[i][j] = defaut; } } } for (int i = 0; i < Configuration.VisionRadius * 2; i++) { for (int j = 0; j < Configuration.VisionRadius * 2; j++) { // Color couleur = getPatchColorAt(i - getVisionRadius(), j - getVisionRadius()); if (xcor() + i - Configuration.VisionRadius < getWorldWidth() && ycor() + j - Configuration.VisionRadius < getWorldHeight() && xcor() + i - Configuration.VisionRadius > 0 && ycor() + j - Configuration.VisionRadius > 0) { int passabilite = Configuration.couleurs_terrains.get( getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius).getColor()) .getPassabilite(); if (smellAt("passage", i - Configuration.VisionRadius, j - Configuration.VisionRadius) > 0) { map[xcor() + i - Configuration.VisionRadius][ycor() + j - Configuration.VisionRadius] = (int) (passabilite - (passabilite / 2 * 1 / smellAt("passage", i - Configuration.VisionRadius, j - Configuration.VisionRadius))); } else { map[xcor() + i - Configuration.VisionRadius][ycor() + j - Configuration.VisionRadius] = passabilite; } if (getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius) .isMarkPresent("Route")) { map[xcor() + i - Configuration.VisionRadius][ycor() + j - Configuration.VisionRadius] /= 2; } if (Configuration.couleurs_terrains.get( getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius).getColor()) .getInfranchissable() == true) { map[xcor() + i - Configuration.VisionRadius][ycor() + j - Configuration.VisionRadius] = Integer.MAX_VALUE; } } } } /* for(int i = 0; i < map.length; i++) { System.out.print("["); for(int j = 0;j < map[i].length;j++) { if(map[i][j] != 1000) { System.out.print(map[i][j]); } } System.out.println("]"); }*/ ArrayList<Noeud> liste_noeud = new ArrayList<Noeud>(); ArrayList<Noeud> open_list = new ArrayList<Noeud>(); ArrayList<Noeud> close_list = new ArrayList<Noeud>(); Noeud noeud = new Noeud(getPatch().x, getPatch().y, 0, 0); noeud.setDistanceRacine(0); close_list.add(noeud); liste_noeud.add(noeud); int cpt = 1; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { int x = noeud.getPosX(); int y = noeud.getPosY(); if ((x + i < getWorldWidth() && x + i > 0) && (y + j < getWorldHeight() && y + j > 0) && (i != 0 || j != 0) && map[x + i][y + j] != Integer.MAX_VALUE) { Noeud noeu = new Noeud(x + i, y + j, 0, cpt); int distanceRacine = map[x + i][y + j]; noeu.setDistanceRacine(distanceRacine); open_list.add(noeu); liste_noeud.add(noeu); cpt++; } } } /*System.out.println("Open_list 1 : "); for(int i = 0; i < open_list.size();i++) { System.out.println("Noeud : "+open_list.get(i).getId()+" x : "+open_list.get(i).getPosX()+" y : "+open_list.get(i).getPosY()+ " distance : "+open_list.get(i).getDistanceRacine()); }*/ Noeud suivant = PlusProcheNoeud(open_list, cible); if (suivant != null) { /*if(suivant.getParent() != noeud.getId()) { for(int i = 0; i< close_list.size();i++) { if(close_list.get(i).getId() > suivant.getParent()) { close_list.remove(i); } } }*/ close_list.add(suivant); } //System.out.println("close_list 1 : " + close_list); noeud = suivant; while (noeud != null && (noeud.getPosX() != cible.x || noeud.getPosY() != cible.y)) { //System.out.println("Agent : "+getID()+" Noeud suivant : "+noeud.getId()+ " x : "+noeud.getPosX()+ " y : "+noeud.getPosY()+ " parent : "+noeud.getParent()+ " x cible : "+cible.x+" y cible : "+cible.y); open_list.remove(noeud); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { int x = noeud.getPosX(); int y = noeud.getPosY(); if ((x + i < getWorldWidth() && x + i > 0) && (y + j < getWorldHeight() && y + j > 0) && (i != 0 || j != 0) && map[x + i][y + j] != Integer.MAX_VALUE) { Noeud noeu = new Noeud(x + i, y + j, noeud.getId(), cpt); if (!doublons(open_list, noeu)) { int distanceRacine = map[x + i][y + j] + noeud.getDistanceRacine(); noeu.setDistanceRacine(distanceRacine); open_list.add(noeu); liste_noeud.add(noeu); cpt++; // System.out.println("Nouveau noeud "+noeu.getId()+" x : "+noeu.getPosX() + " y : "+noeu.getPosY()); } } } } suivant = PlusProcheNoeud(open_list, cible); if (suivant != null) { /*if(suivant.getParent() != noeud.getId()) { for(int i = 0; i< close_list.size();i++) { if(close_list.get(i).getId() > suivant.getParent()) { close_list.remove(i); } } }*/ close_list.add(suivant); } noeud = suivant; } ArrayList<Patch> liste = new ArrayList<Patch>(); /* for(int i = 0;i < close_list.size();i++) { int x = close_list.get(i).getPosX(); int y = close_list.get(i).getPosY(); if(map[x][y] >= Configuration.VitesseEstimeeParDefaut) { return liste; } else { liste.add(0,getPatchAt(x - position.x, y - position.y)); } }*/ Noeud nodesui = close_list.get(close_list.size() - 1); while (!(nodesui.getPosX() == getPatch().x && nodesui.getPosY() == getPatch().y)) { int x = nodesui.getPosX(); int y = nodesui.getPosY(); liste.add(0, getPatchAt(x - getPatch().x, y - getPatch().y)); nodesui = liste_noeud.get(nodesui.getParent()); } // System.out.println("Debut "); for (int i = 0; i < liste.size(); i++) { int x = liste.get(i).x; int y = liste.get(i).y; if (x > xcor() + Configuration.VisionRadius || x < xcor() - Configuration.VisionRadius || y > ycor() + Configuration.VisionRadius || y < ycor() - Configuration.VisionRadius) { if (i == 0) { //System.out.println("test"); setHeading(Math.random() * 360.); fd(1); } // System.out.println("Fin 1 "+"cible x : "+cible.x+" cible y :"+cible.y); return liste; } // System.out.println("Pos => x : "+x + " y : "+y); } // System.out.println("Pos => x : "+xcor() + " y : "+ycor()); // System.out.println("Fin 2 cible x : "+cible.x+" cible y :"+cible.y); return liste; }
From source file:gedi.riboseq.inference.orf.OrfFinder.java
private void tryToStitch(ArrayList<OrfWithCodons> orfs, SpliceGraph sg, String sequence) { if (orfs.size() <= 1) return;//from w ww .j ava 2 s.c o m Collections.sort(orfs, (a, b) -> a.getRegion().compareTo(b.getRegion())); for (int f = 0; f < orfs.size(); f++) { if (orfs.get(f).getEstimatedTotalActivity() / (orfs.get(f).getRegion().getTotalLength() / 3) >= minStitchCoverage) for (int t = f + 1; t < orfs.size(); t++) if (orfs.get(t).getEstimatedTotalActivity() / (orfs.get(t).getRegion().getTotalLength() / 3) >= minStitchCoverage && orfs.get(f).getRegion().getEnd() < orfs.get(t).getRegion().getStart()) { OrfWithCodons from = orfs.get(f); OrfWithCodons to = orfs.get(t); MutableMonad<ArrayGenomicRegion> inbetween = new MutableMonad<>( new ArrayGenomicRegion(from.getRegion().getEnd(), to.getRegion().getStart())); if (inbetween.Item.getTotalLength() % 3 != 0 || inbetween.Item.getTotalLength() / 3 >= maxStitchDistance || containsInframeStop( SequenceUtils.extractSequence(inbetween.Item.extendFront(3), sequence))) inbetween.Item = null; sg.forEachIntronStartingBetween(from.getRegion().getEnd(), maxStitchDistance, intron -> { ArrayGenomicRegion reg = new ArrayGenomicRegion(from.getRegion().getEnd(), intron.getStart(), intron.getEnd(), to.getRegion().getStart()); if (reg.getTotalLength() % 3 != 0 || reg.getTotalLength() >= maxStitchDistance || containsInframeStop( SequenceUtils.extractSequence(reg.extendFront(3), sequence))) { if (inbetween.Item == null || inbetween.Item.getTotalLength() > reg.getTotalLength()) inbetween.Item = reg; } }); if (inbetween.Item != null) { // yeah, I can stitch them! from.stitchWith(to, inbetween.Item); f--; orfs.remove(t); break; // continue with from and the check all possible to again! } } } }
From source file:mom.trd.opentheso.bdd.helper.TermHelper.java
/** * Cette fonction permet de rcuprer l'historique des termes synonymes d'un terme une date prcise * * @param ds/* w ww . j a v a2 s . co m*/ * @param idTerm * @param idThesaurus * @param idLang * @param date * @return Objet class Concept */ public ArrayList<NodeEM> getNonPreferredTermsHistoriqueFromDate(HikariDataSource ds, String idTerm, String idThesaurus, String idLang, Date date) { Connection conn; Statement stmt; ResultSet resultSet; ArrayList<NodeEM> nodeEMList = null; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "SELECT lexical_value, modified, source, status, hiden, action, username FROM non_preferred_term_historique, users" + " WHERE id_term = '" + idTerm + "'" + " and id_thesaurus = '" + idThesaurus + "'" + " and lang ='" + idLang + "'" + " and non_preferred_term_historique.id_user=users.id_user" + " and modified <= '" + date.toString() + "' order by modified, lexical_value ASC"; stmt.executeQuery(query); resultSet = stmt.getResultSet(); if (resultSet != null) { nodeEMList = new ArrayList<>(); while (resultSet.next()) { if (resultSet.getString("action").equals("DEL")) { for (NodeEM nem : nodeEMList) { if (nem.getLexical_value().equals(resultSet.getString("lexical_value")) && nem.getAction().equals("ADD") && nem.getStatus().equals(resultSet.getString("status"))) { nodeEMList.remove(nem); break; } } } else { NodeEM nodeEM = new NodeEM(); nodeEM.setLexical_value(resultSet.getString("lexical_value")); nodeEM.setModified(resultSet.getDate("modified")); nodeEM.setSource(resultSet.getString("source")); nodeEM.setStatus(resultSet.getString("status")); nodeEM.setHiden(resultSet.getBoolean("hiden")); nodeEM.setAction(resultSet.getString("action")); nodeEM.setIdUser(resultSet.getString("username")); nodeEM.setLang(idLang); nodeEMList.add(nodeEM); } } } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while getting NonPreferedTerm date historique of Term : " + idTerm, sqle); } return nodeEMList; }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
@SuppressWarnings("unchecked") public void testDescendingKeySet_iterator() { NavigableMap<K, V> map = createNavigableMap(); map.putAll(makeFullMap());//from ww w . j a va2 s . c o m resetFull(); ArrayList<K> keys = new ArrayList<K>(); for (Object key : getSampleKeys()) { keys.add((K) key); } // JDK < 7 does not handle null keys correctly. if (useNullKey() && TestUtils.isJvm() && TestUtils.getJdkVersion() < 7) { map.remove(null); keys.remove(null); } Comparator<? super K> cmp = ((TreeMap<K, V>) map).comparator(); Collections.sort(keys, Collections.reverseOrder(cmp)); Iterator<K> it = map.descendingKeySet().iterator(); for (K key : keys) { assertTrue(it.hasNext()); K rem = it.next(); it.remove(); assertEquals(key, rem); } try { it.next(); fail("should throw NoSuchElementException"); } catch (NoSuchElementException expected) { } _assertEmpty(map); }
From source file:com.adaptris.core.services.splitter.SimpleRegexpMessageSplitter.java
@Override protected ArrayList<String> split(String messagePayload) throws Exception { String batch = messagePayload; compiledSplitPattern = compile(compiledSplitPattern, splitPattern); Matcher splitMatcher = compiledSplitPattern.matcher(batch); Matcher compareMatcher = null; if (compareToPreviousMatch()) { compiledMatchPattern = compile(compiledMatchPattern, matchPattern); compareMatcher = compiledMatchPattern.matcher(batch); }//from w w w.j a v a 2 s . c o m ArrayList<String> splitMessages = new ArrayList(); int splitStart = 0; int splitEnd = 0; StringBuffer currentSplitMsg = new StringBuffer(); String currentMatch = null; if (compareToPreviousMatch()) { try { // do not check for a match first - we want to throw an exception if // no match found. compareMatcher.find(); // lgtm currentMatch = compareMatcher.group(1); } catch (Exception e) { throw new Exception("Could not match record comparator [" + e.getMessage() + "]", e); } } while (splitMatcher.find(splitEnd)) { splitEnd = splitMatcher.end(); String thisRecord = batch.substring(splitStart, splitEnd); if (compareToPreviousMatch()) { compareMatcher = compiledMatchPattern.matcher(thisRecord); // We may get an empty line, in which case the compare.start() and // compare.end() methods will throw an IllegalStateException String newMatch = ""; if (compareMatcher.find()) { newMatch = compareMatcher.group(1); } if (currentMatch.equals(newMatch)) { // lgtm // Still in the same message currentSplitMsg.append(thisRecord); } else { // The current thisRecord value is actually the start of the next // message, so we should store the last record and start again // with this one. splitMessages.add(currentSplitMsg.toString()); // ******** currentSplitMsg.setLength(0); currentSplitMsg.append(thisRecord); currentMatch = newMatch; } } else { splitMessages.add(thisRecord); } splitStart = splitEnd; } // last message - might be an empty String String thisRecord = batch.substring(splitStart); if (compareToPreviousMatch()) { compareMatcher = compiledMatchPattern.matcher(thisRecord); // We may get an empty line, in which case the compare.start() and // compare.end() methods will throw an IllegalStateException String newMatch = ""; if (compareMatcher.find()) { newMatch = compareMatcher.group(1); } if (currentMatch.equals(newMatch)) { // lgtm // Still in the same message currentSplitMsg.append(thisRecord); splitMessages.add(currentSplitMsg.toString()); } else { // The current thisRecord value is actually the start of the next // message, so we should store the last record and start again // with this one. splitMessages.add(currentSplitMsg.toString()); currentSplitMsg.setLength(0); // Must be a single line record - write it out (unless empty) if (thisRecord.trim().length() > 0) { splitMessages.add(thisRecord); } } } else { // Must be a single line record - write it out (unless empty) if (thisRecord.trim().length() > 0) { splitMessages.add(thisRecord); } } if (ignoreFirstSubMessage()) { splitMessages.remove(0); } return splitMessages; }