List of usage examples for java.util Collection removeAll
boolean removeAll(Collection<?> c);
From source file:org.drools.semantics.builder.model.inference.DelegateInferenceStrategy.java
private void reduceTransitiveInheritance(LinkedHashMap<String, Concept> sortedCache, Map<String, Collection<String>> supers) { Map<String, Collection<String>> taboos = new HashMap<String, Collection<String>>(); for (String con : sortedCache.keySet()) { Collection<String> ancestors = supers.get(con); Set<String> taboo = new HashSet<String>(); for (String anc : ancestors) { if (taboos.containsKey(anc)) { taboo.addAll(taboos.get(anc)); }//from w w w. j ava 2s .c o m } ancestors.removeAll(taboo); taboo.addAll(ancestors); taboos.put(con, taboo); } }
From source file:ubic.gemma.persistence.service.expression.bioAssayData.ProcessedExpressionDataVectorDaoImpl.java
/** * @param rawPreferredDataVectors//from ww w.j ava2 s. c o m */ private void removeDuplicateElements(Collection<RawExpressionDataVector> rawPreferredDataVectors) { /* * Remove rows that are duplicates for the same design element. This can happen for data sets that were merged. * We arbitrarily throw one out. */ int maxWarn = 10; int warned = 0; Set<CompositeSequence> seenDes = new HashSet<>(); Collection<RawExpressionDataVector> toRemove = new HashSet<>(); for (RawExpressionDataVector rdv : rawPreferredDataVectors) { CompositeSequence de = rdv.getDesignElement(); if (seenDes.contains(de)) { if (warned <= maxWarn) { log.info("Duplicate vector for: " + de); warned++; } if (warned == maxWarn) { log.info("Further warnings skipped"); } toRemove.add(rdv); } seenDes.add(de); } if (!toRemove.isEmpty()) { rawPreferredDataVectors.removeAll(toRemove); log.info("Removed " + toRemove.size() + " duplicate elements, " + rawPreferredDataVectors.size() + " remain"); } }
From source file:edu.jhuapl.openessence.controller.ReportController.java
private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss, List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull, String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations, final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails, boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) { Map<String, Object> result = new HashMap<String, Object>(); Map<String, ResolutionHandler> resolutionHandlers = null; result.put("success", false); try {// ww w. ja v a2 s. c o m GroupingDimension grpdim = dss.getGroupingDimension(group.getId()); resolutionHandlers = grpdim.getResolutionsMap(); String dateFieldName = group.getId(); Date startDate = null; Date endDate = null; if (grpdim != null && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) { for (Filter f : filters) { if (f instanceof OneArgOpFilter) { OneArgOpFilter of = (OneArgOpFilter) f; if (of.getFilterId().equalsIgnoreCase(grpdim.getId()) && (of.getSqlSnippet("").contains(">="))) { startDate = (Date) of.getArguments().get(0); } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId()) && (of.getSqlSnippet("").contains("<="))) { endDate = (Date) of.getArguments().get(0); } } } } //union accumulations to get all results List<Dimension> dimensions = new ArrayList<Dimension>( ControllerUtils.unionDimensions(accumulations, timeseriesDenominators)); int timeOffsetMillies = 0; String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false"); if (timezoneEnabledString.equalsIgnoreCase("true")) { timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings()) - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings()); } Calendar startDayCal = Calendar.getInstance(clientTimezone); startDayCal.setTime(startDate); startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies); //get data grouped by group dimension List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records, startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers); if (points.size() > 0) { DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone); DateFormat tmpDateFormat = (DateFormat) dateFormat.clone(); tmpDateFormat.setTimeZone(clientTimezone); // number format for level NumberFormat numFormat3 = NumberFormat.getNumberInstance(); numFormat3.setMinimumFractionDigits(0); numFormat3.setMaximumFractionDigits(3); // number format for expected count NumberFormat numFormat1 = NumberFormat.getNumberInstance(); numFormat1.setMinimumFractionDigits(0); numFormat1.setMaximumFractionDigits(1); Calendar cal = new GregorianCalendar(); cal.setTime(startDayCal.getTime()); //offset start date to match prepull offset if (timeResolution.equals("weekly")) { cal.add(Calendar.DATE, (7 * prepull)); } else if (timeResolution.equals("daily")) { cal.add(Calendar.DATE, prepull); } Date queryStartDate = cal.getTime(); //-- Handles Denominator Types -- // double[] divisors = new double[points.size()]; double multiplier = 1.0; boolean percentBased = false; String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss); boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass); //if there is a denominator we need to further manipulate the data if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) { // divisor is the sum of timeseriesDenominators divisors = totalSeriesValues(points, timeseriesDenominators); multiplier = 100.0; percentBased = true; yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss); } else { //the query is for total counts Arrays.fill(divisors, 1.0); } double[][] allCounts = new double[accumulations.size()][]; int[][] allColors = new int[accumulations.size()][]; String[][] allAltTexts = new String[accumulations.size()][]; String[] dates = new String[] { "" }; double[][] allExpecteds = new double[accumulations.size()][]; double[][] allLevels = new double[accumulations.size()][]; String[][] allLineSetURLs = new String[accumulations.size()][]; String[][] allSwitchInfo = new String[accumulations.size()][]; String[] lineSetLabels = new String[accumulations.size()]; boolean[] displayAlerts = new boolean[accumulations.size()]; //get all results Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions()); Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims); Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations()); //remove extra accumulations in the result set using string ids dimIds.removeAll(accIds); //for each accumulation we run detection and gather results int aIndex = 0; for (Dimension accumulation : accumulations) { String accumId = accumulation.getId(); // use display name if it has one, otherwise translate its ID String accumIdTranslated = accumulation.getDisplayName(); if (accumIdTranslated == null) { accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss); } TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper .createObject(detectorClass); TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject(); int[] colors; double[] counts; String[] altTexts; double[] expecteds; double[] levels; String[] switchInfo; String[] urls; //pull the counts from the accum array points double[] seriesDoubleArray = generateSeriesValues(points, accumId); //run divisor before detection for (int i = 0; i < seriesDoubleArray.length; i++) { double div = divisors[i]; if (div == 0) { seriesDoubleArray[i] = 0.0; } else { seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier; } } //run detection TDDO.setCounts(seriesDoubleArray); TDDO.setStartDate(startDate); TDDO.setTimeResolution(timeResolution); try { TDI.runDetector(TDDO); } catch (Exception e) { String errorMessage = "Failure to create Timeseries"; if (e.getMessage() != null) { errorMessage = errorMessage + ":<BR>" + e.getMessage(); } result.put("message", errorMessage); result.put("success", false); return result; } TDDO.cropStartup(prepull); counts = TDDO.getCounts(); int tddoLength = counts.length; if (!DAILY.equalsIgnoreCase(timeResolution)) { //toggle between start date and end date //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution)); TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution, displayIntervalEndDate)); } double[] tcolors = TDDO.getColors(); Date[] tdates = TDDO.getDates(); altTexts = TDDO.getAltTexts(); expecteds = TDDO.getExpecteds(); levels = TDDO.getLevels(); switchInfo = TDDO.getSwitchInfo(); colors = new int[tddoLength]; dates = new String[tddoLength]; urls = new String[tddoLength]; //add the accumId for the current series dimIds.add(accumId); StringBuilder jsCall = new StringBuilder(); jsCall.append("javascript:OE.report.datasource.showDetails({"); jsCall.append("dsId:'").append(dss.getClass().getName()).append("'"); //specify results jsCall.append(",results:[") .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']'); //specify accumId jsCall.append(",accumId:'").append(accumId).append("'"); addJavaScriptFilters(jsCall, filters, dateFieldName); //this builds urls and hover texts int startDay = getWeekStartDay(resolutionHandlers); Calendar c = Calendar.getInstance(clientTimezone); // Calendar curr = Calendar.getInstance(); for (int i = 0; i < tddoLength; i++) { colors[i] = (int) tcolors[i]; // For a time series data point, set time to be current server time // This will allow us to convert this data point date object to be request timezone date c.setTime(tdates[i]); c.add(Calendar.MILLISECOND, timeOffsetMillies); if (timeResolution.equals(WEEKLY)) { dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W" + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-" + PgSqlDateHelper.getYear(startDay, c); } else { dates[i] = tmpDateFormat.format(c.getTime()); } altTexts[i] = "(" + accumIdTranslated + ") " + // Accum "Date: " + dates[i] + // Date ", Level: " + numFormat3.format(levels[i]) + // Level ", Count: " + ((int) counts[i]) + // Count ", Expected: " + numFormat1.format(expecteds[i]); // Expected if (switchInfo != null) { altTexts[i] += ", Switch: " + switchInfo[i] + ", "; } // build the click through url StringBuilder tmp = new StringBuilder(jsCall.toString()); // add the date field with start and end dates from the data point if (!DAILY.equalsIgnoreCase(timeResolution)) { Calendar timeSet = Calendar.getInstance(clientTimezone); timeSet.setTime(tdates[i]); if (WEEKLY.equalsIgnoreCase(timeResolution)) { timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); timeSet.add(Calendar.DAY_OF_YEAR, 6); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); } else if (MONTHLY.equalsIgnoreCase(timeResolution)) { // Compute last day of month timeSet.set(Calendar.DAY_OF_MONTH, 1); timeSet.add(Calendar.MONTH, 1); timeSet.add(Calendar.DAY_OF_YEAR, -1); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); // set first day of month timeSet.set(Calendar.DAY_OF_MONTH, 1); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); } else if (YEARLY.equalsIgnoreCase(timeResolution)) { // Compute last day of month timeSet.set(Calendar.DATE, 31); timeSet.add(Calendar.MONTH, Calendar.DECEMBER); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); timeSet.set(Calendar.DATE, 1); timeSet.add(Calendar.MONTH, Calendar.JANUARY); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); } } else { // compute end date for individual data points based on the selected resolution // detailsPointEndDate = computeEndDate(tdates[i],timeResolution); // add the date field with start and end dates from the data point tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime()) .append("'"); tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime()) .append("'"); } tmp.append("});"); urls[i] = tmp.toString(); } allCounts[aIndex] = counts; allColors[aIndex] = colors; allAltTexts[aIndex] = altTexts; allExpecteds[aIndex] = expecteds; allLevels[aIndex] = levels; allLineSetURLs[aIndex] = urls; allSwitchInfo[aIndex] = switchInfo; lineSetLabels[aIndex] = accumIdTranslated; displayAlerts[aIndex] = isDetectionDetector; aIndex++; //remove the accumId for the next series dimIds.remove(accumId); } GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir); GraphController gc = getGraphController(null, hndl, userPrincipalName); //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012 // gc.setMaxLegendItems(accumulations.size()); graphData.setShowSingleAlertLegends(isDetectionDetector); graphData.setCounts(allCounts); graphData.setColors(allColors); graphData.setAltTexts(allAltTexts); graphData.setXLabels(dates); graphData.setExpecteds(allExpecteds); graphData.setLevels(allLevels); graphData.setLineSetURLs(allLineSetURLs); graphData.setLineSetLabels(lineSetLabels); graphData.setDisplayAlerts(displayAlerts); // graphData.setDisplaySeverityAlerts(displayAlerts); graphData.setPercentBased(percentBased); graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss)); graphData.setYAxisLabel(yAxisLabel); int maxLabels = graphData.getGraphWidth() / 30; graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length)); StringBuffer sb = new StringBuffer(); GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl); result.put("html", sb.toString()); //added to build method calls from javascript Map<String, Object> graphConfig = new HashMap<String, Object>(); graphConfig.put("address", graphTimeSeriesUrl); graphConfig.put("graphDataId", graph.getGraphDataId()); graphConfig.put("imageMapName", graph.getImageMapName()); graphConfig.put("graphTitle", graphData.getGraphTitle()); graphConfig.put("xAxisLabel", graphData.getXAxisLabel()); graphConfig.put("yAxisLabel", graphData.getYAxisLabel()); graphConfig.put("xLabels", graphData.getXLabels()); graphConfig.put("graphWidth", graphData.getGraphWidth()); graphConfig.put("graphHeight", graphData.getGraphHeight()); graphConfig.put("yAxisMin", graph.getYAxisMin()); graphConfig.put("yAxisMax", graph.getYAxisMax()); // fix invalid JSON coming from GraphController String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "") // remove trailing "}" .substring(0, graph.getDataSeriesJSON().length() - 2); // read malformed JSON ObjectMapper mapper = new ObjectMapper(); JsonFactory jsonFactory = mapper.getJsonFactory() .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson); // array of String -> Object maps TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() { }; // write JSON as Map so that it can be serialized properly back to JSON Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType); graphConfig.put("dataSeriesJSON", seriesMap); if (includeDetails) { int totalPoints = 0; List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> detail; for (int i = 0; i < allCounts.length; i++) { for (int j = 0; j < allCounts[i].length; j++) { totalPoints++; detail = new HashMap<String, Object>(); detail.put("Date", dates[j]); detail.put("Series", lineSetLabels[i]); detail.put("Level", allLevels[i][j]); detail.put("Count", allCounts[i][j]); if (!ArrayUtils.isEmpty(allExpecteds[i])) { detail.put("Expected", allExpecteds[i][j]); } if (!ArrayUtils.isEmpty(allSwitchInfo[i])) { detail.put("Switch", allSwitchInfo[i][j]); } detail.put("Color", allColors[i][j]); details.add(detail); } } result.put("detailsTotalRows", totalPoints); result.put("details", details); } result.put("graphConfiguration", graphConfig); result.put("success", true); } else { StringBuilder sb = new StringBuilder(); sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>"); sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>"); result.put("html", sb.toString()); result.put("success", true); } } catch (Exception e) { log.error("Failure to create Timeseries", e); } return result; }
From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java
public void replaceOrCreateXref(String database, String databaseMI, String primaryId, String version, String qualifier, String qualifierMI, Collection<Xref> refs) { if (database == null) { throw new IllegalArgumentException( "Impossible to replace or create cross references if the database is not set."); }//from www . j ava 2s.com if (primaryId == null) { throw new IllegalArgumentException( "Impossible to replace or create cross references if the primary id is not set."); } // modify if exists Collection<Xref> existingRefs = XrefUtils.collectAllXrefsHavingDatabaseAndQualifier(refs, databaseMI, database, qualifierMI, qualifier); Xref existingRef = !existingRefs.isEmpty() ? existingRefs.iterator().next() : null; // update if existing if (existingRef instanceof AbstractIntactXref) { AbstractIntactXref intactRef = (AbstractIntactXref) existingRef; intactRef.setVersion(version); intactRef.setId(primaryId); } // create if not exists else { refs.removeAll(existingRefs); refs.add(newXref(database, databaseMI, primaryId, version, qualifier, qualifierMI)); } setUnsavedChanges(true); }
From source file:org.openremote.modeler.cache.LocalFileCache.java
private String getRulesFileContent() { Collection<ControllerConfig> configs = controllerConfigService.listAllConfigs(); configs.removeAll(controllerConfigService.listAllexpiredConfigs()); configs.addAll(controllerConfigService.listAllMissingConfigs()); String result = ""; for (ControllerConfig controllerConfig : configs) { if (controllerConfig.getName().equals("rules.editor")) { result = controllerConfig.getValue(); }//from w w w . ja v a2 s. c om } return result; }
From source file:org.fenixedu.academic.domain.student.Registration.java
public static void checkIngression(IngressionType ingressionType, Person person, DegreeCurricularPlan degreeCurricularPlan) { if (ingressionType.isReIngression()) { if (person == null || person.getStudent() == null) { throw new DomainException("error.registration.preBolonhaSourceDegreeNotFound"); }/*from w w w.j a va 2 s .c om*/ if (degreeCurricularPlan.getEquivalencePlan() != null) { final Student student = person.getStudent(); final Degree sourceDegree = degreeCurricularPlan.getEquivalencePlan() .getSourceDegreeCurricularPlan().getDegree(); Registration sourceRegistration = person.getStudent().readRegistrationByDegree(sourceDegree); if (sourceRegistration == null) { final Collection<Registration> registrations = student .getRegistrationsMatchingDegreeType(DegreeType::isPreBolonhaDegree); registrations.removeAll(student.getRegistrationsFor(degreeCurricularPlan)); sourceRegistration = registrations.size() == 1 ? registrations.iterator().next() : null; } if (sourceRegistration == null) { throw new DomainException("error.registration.preBolonhaSourceDegreeNotFound"); } else if (!sourceRegistration.getActiveStateType().canReingress()) { throw new DomainException("error.registration.preBolonhaSourceRegistrationCannotReingress"); } } } }
From source file:org.openremote.modeler.cache.LocalFileCache.java
@SuppressWarnings("unchecked") private String getControllerXML(Collection<Screen> screens, long maxOid, ConfigurationFilesGenerationContext generationContext) { // PATCH R3181 BEGIN ---8<----- /*// w w w .j a v a 2 s. co m * Get all sensors and commands from database. */ List<Sensor> dbSensors = currentUserAccount.getAccount().getSensors(); List<Device> allDevices = currentUserAccount.getAccount().getDevices(); List<DeviceCommand> allDBDeviceCommands = new ArrayList<DeviceCommand>(); for (Device device : allDevices) { allDBDeviceCommands.addAll(deviceCommandService.loadByDevice(device.getOid())); } // PATCH R3181 END ---->8----- /* * store the max oid */ MaxId maxId = new MaxId(maxOid + 1); /* * initialize UI component box. */ UIComponentBox uiComponentBox = new UIComponentBox(); initUIComponentBox(screens, uiComponentBox); Map<String, Object> context = new HashMap<String, Object>(); ProtocolCommandContainer eventContainer = new ProtocolCommandContainer(protocolContainer); eventContainer.setAllDBDeviceCommands(allDBDeviceCommands); addDataBaseCommands(eventContainer, maxId); Collection<Sensor> sensors = getAllSensorWithoutDuplicate(screens, maxId, dbSensors); Collection<UISwitch> switchs = (Collection<UISwitch>) uiComponentBox.getUIComponentsByType(UISwitch.class); Collection<UIComponent> buttons = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(UIButton.class); Collection<UIComponent> gestures = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(Gesture.class); Collection<UIComponent> uiSliders = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(UISlider.class); Collection<UIComponent> uiImages = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(UIImage.class); Collection<UIComponent> uiLabels = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(UILabel.class); Collection<UIComponent> colorPickers = (Collection<UIComponent>) uiComponentBox .getUIComponentsByType(ColorPicker.class); Collection<ControllerConfig> configs = controllerConfigService.listAllConfigs(); configs.removeAll(controllerConfigService.listAllexpiredConfigs()); configs.addAll(controllerConfigService.listAllMissingConfigs()); // TODO : BEGIN HACK (TO BE REMOVED) // // - the following removes the rules.editor configuration section from the // controller.xml // <config> section. The rules should not be defined in terms of controller // configuration // in the designer but as artifacts, similar to images (and multiple rule // files should // be supported). for (ControllerConfig controllerConfig : configs) { if (controllerConfig.getName().equals("rules.editor")) { configs.remove(controllerConfig); break; // this fixes a concurrent modification error in this hack.. } } // TODO : END HACK ------------------- context.put("switchs", switchs); context.put("buttons", buttons); context.put("screens", screens); context.put("eventContainer", eventContainer); context.put("localFileCache", this); context.put("protocolContainer", protocolContainer); context.put("sensors", sensors); context.put("dbSensors", dbSensors); context.put("gestures", gestures); context.put("uiSliders", uiSliders); context.put("labels", uiLabels); context.put("images", uiImages); context.put("colorPickers", colorPickers); context.put("maxId", maxId); context.put("configs", configs); context.put("generationContext", generationContext); try { return mergeXMLTemplateIntoString(CONTROLLER_XML_TEMPLATE, context); } catch (Exception e) { throw new XmlExportException("Failed to read panel.xml", e); } }
From source file:com.FFLive.MySQLConnection.java
public void saveTransfers(int gw) { Main.log.log(6, "Saving GW Transfer Data...\n"); //int gw = Integer.parseInt(gameweek); String[] positions = { "GkID", "DefID1", "DefID2", "DefID3", "DefID4", "DefID5", "MidID1", "MidID2", "MidID3", "MidID4", "MidID5", "ForID1", "ForID2", "ForID3", "BenchID1", "BenchID2", "BenchID3", "BenchID4" }; try {//from w ww . ja va 2 s . c o m //Get All Teams and Convert to Map<Int, Collection> PreparedStatement getTeam = conn.prepareStatement("SELECT * FROM teamsGW?"); getTeam.setInt(1, gw); ResultSet allTeams = getTeam.executeQuery(); //Map<Integer,Collection<Integer>> allTeams = makeList(allTeamsResults); while (allTeams.next()) { if (allTeams.getInt("Transfers") != 0) { PreparedStatement getLastGWTeam = conn .prepareStatement("SELECT * FROM teamsGW? WHERE managerID = ?"); getLastGWTeam.setInt(1, gw - 1); getLastGWTeam.setInt(2, allTeams.getInt("managerID")); ResultSet lastGWTeam = getLastGWTeam.executeQuery(); while (lastGWTeam.next()) { //Make Required Collections to get all overlap data Collection<Integer> thisWeek = new ArrayList<Integer>(); Collection<Integer> transfersOut = new ArrayList<Integer>(); for (String temp : positions) { thisWeek.add(allTeams.getInt(temp)); } for (String temp : positions) { transfersOut.add(lastGWTeam.getInt(temp)); } Main.log.ln(8); Main.log.log(8, "Team List: " + thisWeek + "\n"); Main.log.log(8, "Team List Last Week: " + transfersOut + "\n"); //Copy One to preserve thisWeeks Data Collection<Integer> transfersIn = new ArrayList<Integer>(); transfersIn.addAll(thisWeek); //RemoveAll to get overall transfersIn.removeAll(transfersOut); transfersOut.removeAll(thisWeek); Main.log.ln(7); Main.log.log(7, "Transfers In: " + transfersIn + " - Transfers Out: " + transfersOut + "\n"); //Sanity Check, Can have more transfer points than real transfers but can have more real transfers that what the game says. if (transfersIn.size() > allTeams.getInt("Transfers")) { //TODO Can Transfer Issues Be Error Handled? Main.log.ln(3); Main.log.log(3, "Too Many Transfers for " + allTeams.getInt("managerID") + " in GW:" + gw + "\n"); Main.log.log(6, "Measured transfers: " + transfersIn.size() + " Real Value:" + allTeams.getInt("Transfers") + "\n"); Main.log.log(6, "Transfers In: " + transfersIn + " - Transfers Out: " + transfersOut + "\n"); } else { PreparedStatement writeTransfers = conn.prepareStatement( "UPDATE teamsGW? SET transferIN = ?, transferOut = ? WHERE managerID = ?"); writeTransfers.setInt(1, gw); writeTransfers.setString(2, listCollectionToString(transfersIn)); writeTransfers.setString(3, listCollectionToString(transfersOut)); writeTransfers.setInt(4, allTeams.getInt("managerID")); writeTransfers.execute(); //Clean Up writeTransfers.close(); } } lastGWTeam.close(); } } allTeams.close(); } catch (SQLException sql) { Main.log.ln(2); Main.log.log(2, "Error Processing Transfers.. " + sql + "\n"); Main.log.log(9, sql); } }
From source file:ubic.gemma.loader.expression.arrayDesign.ArrayDesignSequenceAlignmentServiceImpl.java
@Override public Collection<BlatResult> processArrayDesign(ArrayDesign ad, Taxon taxon, Collection<BlatResult> rawBlatResults) { log.info("Looking for old results to remove..."); ad = arrayDesignService.thaw(ad);/*from ww w . j av a 2 s . co m*/ arrayDesignService.deleteAlignmentData(ad); // Blat file processing can only be run on one taxon at a time taxon = validateTaxaForBlatFile(ad, taxon); Collection<BioSequence> sequencesToBlat = getSequences(ad); sequencesToBlat = bioSequenceService.thaw(sequencesToBlat); // if the blat results were loaded from a file, we have to replace the // querysequences with the actual ones // attached to the array design. We have to do this by name because the // sequence name is what the files contain. // Note that if there is ambiguity there will be problems! Map<String, BioSequence> seqMap = new HashMap<String, BioSequence>(); for (BioSequence bioSequence : sequencesToBlat) { seqMap.put(bioSequence.getName(), bioSequence); } ExternalDatabase searchedDatabase = Blat.getSearchedGenome(taxon); Collection<BlatResult> toSkip = new HashSet<BlatResult>(); for (BlatResult result : rawBlatResults) { /* * If the sequences don't have ids, replace them with the actual sequences associated with the array design. */ if (result.getQuerySequence().getId() == null) { String querySeqName = result.getQuerySequence().getName(); BioSequence actualSequence = seqMap.get(querySeqName); if (actualSequence == null) { log.debug("Array design does not contain a sequence with name " + querySeqName); toSkip.add(result); continue; } result.setQuerySequence(actualSequence); } else { result.getQuerySequence().setTaxon(taxon); } result.setSearchedDatabase(searchedDatabase); result.getTargetChromosome().setTaxon(taxon); result.getTargetChromosome().getSequence().setTaxon(taxon); } if (toSkip.size() > 0) { log.warn(toSkip.size() + " blat results were for sequences not on " + ad + "; they will be ignored."); rawBlatResults.removeAll(toSkip); } Map<BioSequence, Collection<BlatResult>> goldenPathAlignments = new HashMap<BioSequence, Collection<BlatResult>>(); getGoldenPathAlignments(sequencesToBlat, taxon, goldenPathAlignments); for (BioSequence sequence : goldenPathAlignments.keySet()) { rawBlatResults.addAll(goldenPathAlignments.get(sequence)); } Collection<BlatResult> results = persistBlatResults(rawBlatResults); arrayDesignReportService.generateArrayDesignReport(ad.getId()); return results; }
From source file:org.dllearner.algorithms.qtl.experiments.QTLEvaluation.java
private void filterOutGeneralTypes(Multimap<Var, Triple> var2Triples) { // keep the most specific types for each subject for (Var subject : var2Triples.keySet()) { Collection<Triple> triplePatterns = var2Triples.get(subject); Collection<Triple> triplesPatterns2Remove = new HashSet<>(); for (Triple tp : triplePatterns) { if (tp.getObject().isURI() && !triplesPatterns2Remove.contains(tp)) { // get all super classes for the triple object Set<Node> superClasses = getSuperClasses(tp.getObject()); // remove triple patterns that have one of the super classes as object for (Triple tp2 : triplePatterns) { if (tp2 != tp && superClasses.contains(tp2.getObject())) { triplesPatterns2Remove.add(tp2); }/*from ww w . jav a 2 s. c om*/ } } } // remove triple patterns triplePatterns.removeAll(triplesPatterns2Remove); } }