List of usage examples for java.util TreeSet add
public boolean add(E e)
From source file:net.semanticmetadata.lire.filter.LsaFilter.java
/** * @param results/* w w w.j a v a 2s . c o m*/ * @param query * @return the filtered results or null if error occurs. */ public ImageSearchHits filter(ImageSearchHits results, Document query) { // create a double[items][histogram] tempFeature = null; LinkedList<double[]> features = new LinkedList<double[]>(); try { tempFeature = (LireFeature) featureClass.newInstance(); } catch (Exception e) { logger.severe("Could not create feature " + featureClass.getName() + " (" + e.getMessage() + ")."); return null; } // get all features from the result set, take care of those that do not have the respective field. for (int i = 0; i < results.length(); i++) { Document d = results.doc(i); if (d.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(d.getField(fieldName).binaryValue().bytes, d.getField(fieldName).binaryValue().offset, d.getField(fieldName).binaryValue().length); features.add(tempFeature.getDoubleHistogram()); } } // now go for the query if (query.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(query.getField(fieldName).binaryValue().bytes, query.getField(fieldName).binaryValue().offset, query.getField(fieldName).binaryValue().length); } else { logger.severe("Query document is missing the given feature " + featureClass.getName() + "."); return null; } double[][] matrixData = new double[features.size() + 1][tempFeature.getDoubleHistogram().length]; System.arraycopy(tempFeature.getDoubleHistogram(), 0, matrixData[0], 0, tempFeature.getDoubleHistogram().length); int count = 1; for (Iterator<double[]> iterator = features.iterator(); iterator.hasNext();) { double[] next = iterator.next(); System.arraycopy(next, 0, matrixData[count], 0, next.length); count++; } for (int i = 0; i < matrixData.length; i++) { double[] doubles = matrixData[i]; for (int j = 0; j < doubles.length; j++) { if (Double.isNaN(doubles[j])) System.err.println("Value is NaN"); ; } } // create a matrix object and do the magic Array2DRowRealMatrix m = new Array2DRowRealMatrix(matrixData); long ms = System.currentTimeMillis(); SingularValueDecomposition svd = new SingularValueDecomposition(m); ms = System.currentTimeMillis() - ms; double[] singularValues = svd.getSingularValues(); RealMatrix s = svd.getS(); // if no number of dimensions is given reduce to a tenth. if (numberOfDimensions < 1) numberOfDimensions = singularValues.length / 10; for (int i = numberOfDimensions; i < singularValues.length; i++) { s.setEntry(i, i, 0); } RealMatrix mNew = svd.getU().multiply(s).multiply(svd.getVT()); double[][] data = mNew.getData(); // create the new result set TreeSet<SimpleResult> result = new TreeSet<SimpleResult>(); double maxDistance = 0; double[] queryData = data[0]; for (int i = 1; i < data.length; i++) { double[] doubles = data[i]; double distance = MetricsUtils.distL1(doubles, queryData); result.add(new SimpleResult((float) distance, results.doc(i - 1), i - 1)); maxDistance = Math.max(maxDistance, distance); } ImageSearchHits hits; hits = new SimpleImageSearchHits(result, (float) maxDistance); return hits; }
From source file:com.cyanogenmod.eleven.ui.fragments.PlaylistDetailFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPopupMenuHelper = new SongPopupMenuHelper(getActivity(), getFragmentManager()) { @Override//from w w w. j a v a2 s . c o m public Song getSong(int position) { if (position == 0) { return null; } return mAdapter.getItem(position); } @Override protected void updateMenuIds(PopupMenuType type, TreeSet<Integer> set) { super.updateMenuIds(type, set); set.add(FragmentMenuItems.REMOVE_FROM_PLAYLIST); set.remove(FragmentMenuItems.DELETE); } @Override protected long getSourceId() { return mPlaylistId; } @Override protected Config.IdType getSourceType() { return Config.IdType.Playlist; } @Override protected void removeFromPlaylist() { mAdapter.remove(mSong); mAdapter.buildCache(); mAdapter.notifyDataSetChanged(); MusicUtils.removeFromPlaylist(getActivity(), mSong.mSongId, mPlaylistId); getLoaderManager().restartLoader(LOADER, null, PlaylistDetailFragment.this); } }; mPlaylistId = getArguments().getLong(Config.ID); lookupName(); }
From source file:de.sub.goobi.export.download.ExportPdf.java
@Override public boolean startExport(Process myProcess, URI inZielVerzeichnis) throws ReadException, IOException, PreferencesException, TypeNotAllowedForParentException, WriteException { /*/*from w w w.jav a 2 s . co m*/ * Read Document */ Fileformat gdzfile = serviceManager.getProcessService().readMetadataFile(myProcess); URI zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis); this.myPrefs = serviceManager.getRulesetService().getPreferences(myProcess.getRuleset()); /* * first of all write mets-file in images-Folder of process */ URI metsTempFile = fileService.createResource(myProcess.getTitle() + ".xml"); writeMetsFile(myProcess, metsTempFile, gdzfile, true); Helper.setMeldung(null, myProcess.getTitle() + ": ", "mets file created"); Helper.setMeldung(null, myProcess.getTitle() + ": ", "start pdf generation now"); if (logger.isDebugEnabled()) { logger.debug("METS file created: " + metsTempFile); } FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest(); String fullpath = req.getRequestURL().toString(); String servletpath = context.getExternalContext().getRequestServletPath(); String myBasisUrl = fullpath.substring(0, fullpath.indexOf(servletpath)); if (!ConfigCore.getBooleanParameter("pdfAsDownload")) { /* * use contentserver api for creation of pdf-file */ CreatePdfFromServletThread pdf = new CreatePdfFromServletThread(); pdf.setMetsURL(metsTempFile.toURL()); pdf.setTargetFolder(zielVerzeichnis); pdf.setInternalServletPath(myBasisUrl); if (logger.isDebugEnabled()) { logger.debug("Taget directory: " + zielVerzeichnis); logger.debug("Using ContentServer2 base URL: " + myBasisUrl); } pdf.initialize(myProcess); pdf.start(); } else { GetMethod method = null; try { /* * define path for mets and pdfs */ URL kitodoContentServerUrl = null; String contentServerUrl = ConfigCore.getParameter("kitodoContentServerUrl"); Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000); /* * using mets file */ if (new MetadatenVerifizierung().validate(myProcess) && metsTempFile.toURL() != null) { /* * if no contentserverurl defined use internal * goobiContentServerServlet */ if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/gcs/gcs?action=pdf&metsFile="; } kitodoContentServerUrl = new URL(contentServerUrl + metsTempFile.toURL() + AND_TARGET_FILE_NAME_IS + myProcess.getTitle() + PDF_EXTENSION); /* * mets data does not exist or is invalid */ } else { if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/cs/cs?action=pdf&images="; } FilenameFilter filter = new FileNameMatchesFilter("\\d*\\.tif"); URI imagesDir = serviceManager.getProcessService().getImagesTifDirectory(true, myProcess); ArrayList<URI> meta = fileService.getSubUris(filter, imagesDir); int capacity = contentServerUrl.length() + (meta.size() - 1) + AND_TARGET_FILE_NAME_IS.length() + myProcess.getTitle().length() + PDF_EXTENSION.length(); TreeSet<String> filenames = new TreeSet<>(new MetadatenHelper(null, null)); for (URI data : meta) { String file = data.toURL().toString(); filenames.add(file); capacity += file.length(); } StringBuilder url = new StringBuilder(capacity); url.append(contentServerUrl); boolean subsequent = false; for (String f : filenames) { if (subsequent) { url.append('$'); } else { subsequent = true; } url.append(f); } url.append(AND_TARGET_FILE_NAME_IS); url.append(myProcess.getTitle()); url.append(PDF_EXTENSION); kitodoContentServerUrl = new URL(url.toString()); } /* * get pdf from servlet and forward response to file */ method = new GetMethod(kitodoContentServerUrl.toString()); method.getParams().setParameter("http.socket.timeout", contentServerTimeOut); if (!context.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); String fileName = myProcess.getTitle() + PDF_EXTENSION; ServletContext servletContext = (ServletContext) context.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); response.sendRedirect(kitodoContentServerUrl.toString()); context.responseComplete(); } if (metsTempFile.toURL() != null) { File tempMets = new File(metsTempFile.toURL().toString()); tempMets.delete(); } } catch (Exception e) { /* * report Error to User as Error-Log */ String text = "error while pdf creation: " + e.getMessage(); URI uri = zielVerzeichnis.resolve(myProcess.getTitle() + ".PDF-ERROR.log"); try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fileService.write(uri)))) { output.write(text); } catch (IOException e1) { logger.error(e1); } return false; } finally { if (method != null) { method.releaseConnection(); } } } return true; }
From source file:org.bedework.eventreg.web.UserAgendaController.java
@Override public ModelAndView doRequest() throws Throwable { final TreeSet<Registration> regs = new TreeSet<>(); for (final Registration reg : sessMan.getRegistrationsByUser(sessMan.getCurrentUser())) { final Event ev = sessMan.retrieveEvent(reg); if ((ev == null) || // TODO Event deleted - should delete registration? (ev.getMaxTickets() < 0)) { // XXX Warn? - not registrable any more continue; }/*from w w w . j a va2 s . c o m*/ reg.setEvent(ev); regs.add(reg); } return objModel("agenda", "regs", regs); }
From source file:net.spfbl.core.Peer.java
public static TreeSet<Peer> dropAll() { TreeSet<Peer> peerSet = new TreeSet<Peer>(); for (Peer peer : getSet()) { if (peer.drop()) { peerSet.add(peer); }/*from w w w . j a v a2 s . co m*/ } return peerSet; }
From source file:net.semanticmetadata.lire.filters.LsaFilter.java
/** * @param results/*from w w w . j a va 2 s .co m*/ * @param query * @return the filtered results or null if error occurs. */ public ImageSearchHits filter(ImageSearchHits results, IndexReader reader, Document query) { // create a double[items][histogram] tempFeature = null; LinkedList<double[]> features = new LinkedList<double[]>(); try { tempFeature = (LireFeature) featureClass.newInstance(); } catch (Exception e) { logger.severe("Could not create feature " + featureClass.getName() + " (" + e.getMessage() + ")."); return null; } // get all features from the result set, take care of those that do not have the respective field. for (int i = 0; i < results.length(); i++) { Document d = null; try { d = reader.document(results.documentID(i)); } catch (IOException e) { e.printStackTrace(); } if (d.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(d.getField(fieldName).binaryValue().bytes, d.getField(fieldName).binaryValue().offset, d.getField(fieldName).binaryValue().length); features.add(tempFeature.getFeatureVector()); } } // now go for the query if (query.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(query.getField(fieldName).binaryValue().bytes, query.getField(fieldName).binaryValue().offset, query.getField(fieldName).binaryValue().length); } else { logger.severe("Query document is missing the given feature " + featureClass.getName() + "."); return null; } double[][] matrixData = new double[features.size() + 1][tempFeature.getFeatureVector().length]; System.arraycopy(tempFeature.getFeatureVector(), 0, matrixData[0], 0, tempFeature.getFeatureVector().length); int count = 1; for (Iterator<double[]> iterator = features.iterator(); iterator.hasNext();) { double[] next = iterator.next(); System.arraycopy(next, 0, matrixData[count], 0, next.length); count++; } for (int i = 0; i < matrixData.length; i++) { double[] doubles = matrixData[i]; for (int j = 0; j < doubles.length; j++) { if (Double.isNaN(doubles[j])) System.err.println("Value is NaN"); ; } } // create a matrix object and do the magic Array2DRowRealMatrix m = new Array2DRowRealMatrix(matrixData); long ms = System.currentTimeMillis(); SingularValueDecomposition svd = new SingularValueDecomposition(m); ms = System.currentTimeMillis() - ms; double[] singularValues = svd.getSingularValues(); RealMatrix s = svd.getS(); // if no number of dimensions is given reduce to a tenth. if (numberOfDimensions < 1) numberOfDimensions = singularValues.length / 10; for (int i = numberOfDimensions; i < singularValues.length; i++) { s.setEntry(i, i, 0); } RealMatrix mNew = svd.getU().multiply(s).multiply(svd.getVT()); double[][] data = mNew.getData(); // create the new result set TreeSet<SimpleResult> result = new TreeSet<SimpleResult>(); double maxDistance = 0; double[] queryData = data[0]; for (int i = 1; i < data.length; i++) { double[] doubles = data[i]; double distance = MetricsUtils.distL1(doubles, queryData); result.add(new SimpleResult((float) distance, results.documentID(i - 1))); maxDistance = Math.max(maxDistance, distance); } ImageSearchHits hits; hits = new SimpleImageSearchHits(result, (float) maxDistance); return hits; }
From source file:com.github.rholder.spring.transaction.TransactionBindingSupportTest.java
@Test public void testResourceHelperTreeSet() throws Exception { // run this in a transaction transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { TreeSet<String> treeSet = TransactionalResourceHelper.getTreeSet("abc"); Assert.assertNotNull("Map not created", treeSet); treeSet.add("ONE"); TreeSet<String> treeSetCheck = TransactionalResourceHelper.getTreeSet("abc"); Assert.assertTrue("Same map not retrieved", treeSet == treeSetCheck); return null; }//from w ww . j a v a2 s .com }); }
From source file:org.cleverbus.admin.web.msg.MessageController.java
/** * Creates a set of message dates, to search logs for these dates. * This set contains just the dates of the following timestamps: * <ul>//from w w w . ja va2 s . co m * <li>source system timestamp</li> * <li>received timestamp</li> * <li>start processing timestamp</li> * <li>last update timestamp</li> * </ul> * It's a Set, so that only distinct dates will be included. * It's a SortedSet, so that the dates are in their natural order. * The elements are LocalDate (without time), * so that the dates will be in the correct order * and the set will correctly not include duplicates. * * @param msg the message to find dates for * @return a set of dates */ private SortedSet<LocalDate> getMsgDates(Message msg) { TreeSet<LocalDate> logDates = new TreeSet<LocalDate>(); Date[] msgDates = new Date[] { msg.getMsgTimestamp(), msg.getReceiveTimestamp(), msg.getStartProcessTimestamp(), msg.getLastUpdateTimestamp() }; for (Date msgDate : msgDates) { if (msgDate != null) { logDates.add(new LocalDate(msgDate)); } } return logDates; }
From source file:com.enitalk.configs.DateCache.java
@Bean(name = "skipCache") public LoadingCache<String, ConcurrentSkipListSet<DateTime>> datesMap() { CacheBuilder<Object, Object> ccc = CacheBuilder.newBuilder(); ccc.expireAfterWrite(2, TimeUnit.MINUTES); LoadingCache<String, ConcurrentSkipListSet<DateTime>> cache = ccc .build(new CacheLoader<String, ConcurrentSkipListSet<DateTime>>() { @Override/*from w w w . j a va 2s . com*/ public ConcurrentSkipListSet<DateTime> load(String key) throws Exception { try { HashMap teachers = mongo.findOne(Query.query(Criteria.where("i").is(key)), HashMap.class, "teachers"); ObjectNode teacherJson = jackson.convertValue(teachers, ObjectNode.class); String timeZone = teacherJson.at("/calendar/timeZone").asText(); NavigableSet<DateTime> set = days(teacherJson.path("schedule"), timeZone, teacherJson); DateTimeZone dzz = DateTimeZone.forID(timeZone); DateTimeFormatter df = ISODateTimeFormat.dateTimeNoMillis().withZone(dzz); byte[] events = calendar.busyEvents(jackson.createObjectNode().put("id", key)); JsonNode evs = jackson.readTree(events); Iterator<JsonNode> its = evs.iterator(); TreeSet<DateTime> dates = new TreeSet<>(); while (its.hasNext()) { String date = its.next().asText(); DateTime av = df.parseDateTime(date).toDateTime(DateTimeZone.UTC); dates.add(av); } set.removeAll(dates); logger.info("Dates for i {} {}", key, set); return new ConcurrentSkipListSet<>(set); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } return null; } }); return cache; }
From source file:net.spfbl.core.Peer.java
public static TreeSet<Peer> getMirrorSet() { TreeSet<Peer> peerSet = new TreeSet<Peer>(); for (Peer peer : getSet()) { if (peer.getSendStatus() == Send.MIRROR) { peerSet.add(peer); }//from www .j a v a2 s . com } return peerSet; }