List of usage examples for java.util List set
E set(int index, E element);
From source file:com.xumpy.timesheets.services.implementations.JobsSrvImpl.java
@Override @Transactional/*from www . jav a2 s .c om*/ public List<JobsInJobsGroup> selectMonthJobsInJobGroup(String month, Overview overview) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date startDate = df.parse("01/" + month); Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); Date endDate = c.getTime(); List<JobsInJobsGroup> periodeJobsInJobsGroup = selectPeriodeJobsInJobGroup(startDate, endDate); for (int i = 0; i < periodeJobsInJobsGroup.size(); i++) { JobsInJobsGroup jobsInJobsGroup = periodeJobsInJobsGroup.get(i); List<JobsCtrlPojo> jobsCtrlPojo = new ArrayList<JobsCtrlPojo>(); for (Jobs job : fillMonth(jobsInJobsGroup.getJobs())) { jobsCtrlPojo.add(new JobsCtrlPojo(job)); } jobsInJobsGroup.setJobs(jobsCtrlPojo); periodeJobsInJobsGroup.set(i, jobsInJobsGroup); } overview.setMonth(month); overview.setAllJobsInJobsGroup(periodeJobsInJobsGroup); return periodeJobsInJobsGroup; }
From source file:com.krawler.br.exp.Variable.java
private void setIndexedElement(Object cont, int index, Object val, boolean insert) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ProcessException { if (cont == null) { throw new ProcessException("container not found for variable: " + this); } else {/*from ww w . jav a 2s . c o m*/ if (indices != null && indices.containsKey(index)) { Iterator<Expression> itr = indices.get(index).iterator(); Object container = null; while (cont != null && itr.hasNext()) { container = cont; int idx = ((Number) itr.next().getValue()).intValue(); if (itr.hasNext()) { if (cont instanceof JSONArray) { cont = ((JSONArray) cont).opt(idx); } else if (cont instanceof java.util.List) { cont = ((java.util.List) cont).get(idx); } else if (cont.getClass().isArray()) { cont = Array.get(cont, idx); } else throw new ProcessException("Unsuported container type found in variable: " + this); } else { if (container == null) throw new ProcessException("container not found for variable: " + this); else if (container instanceof JSONArray) { try { JSONArray jArr = (JSONArray) container; int last = jArr.length(); if (insert) { jArr.put(val); } if (insert && last > idx) { jArr.put(last, jArr.get(last - 1)); last--; } jArr.put(idx, val); } catch (JSONException ex) { throw new ProcessException(ex); } } else if (container instanceof java.util.List) { java.util.List list = (java.util.List) container; if (idx == list.size()) { list.add(val); } else if (insert) { list.add(idx, val); } else { list.set(idx, val); } } else if (container.getClass().isArray()) { Array.set(container, idx, val); } break; } } } } }
From source file:com.ittm_solutions.ipacore.IpaApi.java
/** * Parses analysis results and returns it as List of * {@code IpaAnalysisResults}./*from ww w .j a v a 2s . co m*/ * * @param is * the input stream, usually the content of a http response * @return the results */ public static List<IpaAnalysisResults> parseExport(InputStream is) throws IpaApiException { // the different sections we are expecting final List<String> sections = Collections.unmodifiableList( Arrays.asList("Analysis Details", "Canonical Pathways", "Upstream Regulators", "Causal Networks", "Causal Networks", "Diseases and Bio Functions", "Tox Functions", "Regulator Effects", "Networks", "My Lists", "Tox Lists", "My Pathways", "Analysis Ready Molecules")); // these sections contain a table final List<String> tableSections = Collections .unmodifiableList(Arrays.asList("Canonical Pathways", "Upstream Regulators", "Diseases and Bio Functions", "Tox Functions", "Networks", "Analysis Ready Molecules")); // the columns which should be marked as numeric final List<String> numericColumns = Collections .unmodifiableList(Arrays.asList("-log(p-value)", "zScore", "Ratio", "Exp Log Ratio", "Exp Fold Change", "Activation z-score", "Bias Term", "Bias-corrected z-score", "p-value of overlap", "p-Value", "# Molecules", "Score", "Focus Molecules", "Exp p-value")); // the regular expression denoting the beginning of a new section final Pattern secRgx = Pattern.compile("^(" + StringUtils.join(sections, "|") + ") for (.*)->(.*)->(.*)"); List<IpaAnalysisResults> ipaResults = new ArrayList<IpaAnalysisResults>(); try { try (InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr)) { IpaAnalysisResults currentIpaResults = new IpaAnalysisResults(); currentIpaResults.setAnalysisName(""); String currentSection = ""; String currentAnalysisId = null; SimpleTable currentTable = new SimpleTable(); String currentLine; int sectionLine = 0; while ((currentLine = reader.readLine()) != null) { // FIXME if there is stored something like `<html` in the table // this will throw IpaErrorIndication err = containsStringIndicatingError(currentLine); if (err != null) { throw new IpaApiException(parseContentForError(reader, err).toString()); } // skip empty lines if (currentLine.isEmpty()) { continue; } String[] parts = currentLine.split("\t"); Matcher m = secRgx.matcher(parts[0]); if (m.find()) { String newSectionName = m.group(1); String newSectionWorkspace = m.group(2); String newSectionProjectName = m.group(3); String newSectionAnalysisName = m.group(4); // this is the beginning of a new section if (newSectionAnalysisName.length() == 0) { throw new IpaApiParserException("no analysis name"); } // store the old section if there is one if (currentTable.isInitialised()) { currentTable.setName(currentSection); // remove duplicated information from table (Analysis // Name is constant) if (currentTable.header().get(0).equals("Analysis") || currentTable.header().get(1).equals("Analysis")) { currentTable.deleteColumn("Analysis"); } currentIpaResults.getTables().put(currentTable.getName(), currentTable); } if (!newSectionAnalysisName.equals(currentIpaResults.getAnalysisName())) { // this is a new analysis, store the old one if (currentIpaResults.getAnalysisName().length() > 0) { if (currentAnalysisId == null || currentAnalysisId.length() == 0) { throw new IpaApiParserException("no analysis ID"); } currentIpaResults.setAnalysisId(currentAnalysisId); ipaResults.add(currentIpaResults); } currentAnalysisId = null; currentIpaResults = new IpaAnalysisResults(); currentIpaResults.setWorkspace(newSectionWorkspace); currentIpaResults.setProjectName(newSectionProjectName); currentIpaResults.setAnalysisName(newSectionAnalysisName); } sectionLine = 0; currentSection = newSectionName; currentTable = new SimpleTable(); if (!currentIpaResults.getWorkspace().equals(newSectionWorkspace) || !currentIpaResults.getProjectName().equals(newSectionProjectName) || !currentIpaResults.getAnalysisName().equals(newSectionAnalysisName)) { throw new IpaApiParserException("table metadata mismatch: " + "current(" + currentIpaResults.getWorkspace() + "," + currentIpaResults.getProjectName() + "," + currentIpaResults.getAnalysisName() + "), " + "new(" + newSectionWorkspace + "," + newSectionProjectName + "," + newSectionAnalysisName + ")"); } } else { sectionLine += 1; if (sectionLine == 1) { if (tableSections.contains(currentSection)) { // this is the header of a new table; remove // trailing empty column name List<String> header = new ArrayList<String>(); for (String p : parts) { header.add(p.trim()); } if (header.get(header.size() - 1).length() == 0) { header.remove(header.size() - 1); } currentTable.setHeader(header); List<SimpleColumnType> columnTypes = new ArrayList<SimpleColumnType>(); for (String c : header) { if (numericColumns.contains(c)) { columnTypes.add(SimpleColumnType.NUMERIC); } else { columnTypes.add(SimpleColumnType.STRING); } } currentTable.setColumnTypes(columnTypes); } } else { if (tableSections.contains(currentSection)) { if (currentTable.header().size() > parts.length) { throw new IpaApiParserException("could not parse table (expected " + currentTable.header().size() + " elements, got " + parts.length); } List<String> row = new ArrayList<String>(Arrays.asList(parts)); // beautify certain columns: delete trailing comma, add whitespace after comma for (int i = 0; i < currentTable.header().size(); ++i) { if (currentTable.header().get(i).equals("Molecules") || currentTable.header().get(i).equals("Molecules in Network") || currentTable.header().get(i).equals("Target molecules in dataset")) { row.set(i, row.get(i).replaceAll(",$", "")); row.set(i, row.get(i).replaceAll(",([^\\s])", ", $1")); } } currentTable.addRow(row); } else if (currentSection.equals("Analysis Details")) { if (parts.length == 2) { if (parts[0].equals("Analysis ID")) { currentAnalysisId = parts[1]; } } } } } } // store the last section if (currentTable.isInitialised()) { currentTable.setName(currentSection); // remove duplicated information from table (Analysis Name is // constant) if (currentTable.header().get(0).equals("Analysis") || currentTable.header().get(1).equals("Analysis")) { currentTable.deleteColumn("Analysis"); } currentIpaResults.getTables().put(currentTable.getName(), currentTable); } // store the last analysis if (currentIpaResults.getAnalysisName().length() > 0) { if (currentAnalysisId == null || currentAnalysisId.length() == 0) { throw new IpaApiParserException("no analysis ID"); } currentIpaResults.setAnalysisId(currentAnalysisId); ipaResults.add(currentIpaResults); } } } catch (IOException e) { throw new IpaApiException(e); } return ipaResults; }
From source file:com.seajas.search.codex.social.connection.InMemoryConnectionRepository.java
@Override public MultiValueMap<String, Connection<?>> findConnectionsToUsers( final MultiValueMap<String, String> providerUsers) { if (providerUsers == null || providerUsers.isEmpty()) { throw new IllegalArgumentException("Unable to execute find: no providerUsers provided"); }// w w w .j ava 2s. c o m Map<String, List<String>> providerUserIdsByProviderId = new HashMap<String, List<String>>(); for (Entry<String, List<String>> entry : providerUsers.entrySet()) { String providerId = entry.getKey(); providerUserIdsByProviderId.put(providerId, entry.getValue()); } List<ConnectionData> connectionDatas = new ArrayList<ConnectionData>(); for (Map.Entry<String, List<String>> entry : providerUserIdsByProviderId.entrySet()) { connectionDatas.addAll(getInMemoryProviderConnectionRepository(entry.getKey()) .findByProviderUserIdsOrderByProviderIdAndRank(entry.getValue())); } List<Connection<?>> resultList = createConnections(connectionDatas); MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>(); for (Connection<?> connection : resultList) { String providerId = connection.getKey().getProviderId(); List<String> userIds = providerUsers.get(providerId); List<Connection<?>> connections = connectionsForUsers.get(providerId); if (connections == null) { connections = new ArrayList<Connection<?>>(userIds.size()); for (int i = 0; i < userIds.size(); i++) { connections.add(null); } connectionsForUsers.put(providerId, connections); } String providerUserId = connection.getKey().getProviderUserId(); int connectionIndex = userIds.indexOf(providerUserId); connections.set(connectionIndex, connection); } return connectionsForUsers; }
From source file:eu.supersede.gr.rest.GameRest.java
@RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<?> createGame(Authentication auth, @RequestBody HAHPGame game, @RequestParam(required = true) String criteriaValues, @RequestParam Long processId) throws JsonParseException, JsonMappingException, IOException { TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { };//from w w w. j av a 2s . c o m ObjectMapper mapper = new ObjectMapper(); Map<String, Map<String, Integer>> cvs = mapper.readValue(criteriaValues, typeRef); game.setStartTime(new Date()); // re-attach detached requirements List<Requirement> rs = game.getRequirements(); // if( System.currentTimeMillis() > 0 ) // throw new RuntimeException(""); for (int i = 0; i < rs.size(); i++) { rs.set(i, requirements.findOne(rs.get(i).getRequirementId())); } // re-attach detached users List<User> us = game.getPlayers(); for (int i = 0; i < us.size(); i++) { us.set(i, users.findOne(us.get(i).getUserId())); } // re-attach detached criterias List<ValutationCriteria> cs = game.getCriterias(); for (int i = 0; i < cs.size(); i++) { cs.set(i, criterias.findOne(cs.get(i).getCriteriaId())); } Object user = auth.getPrincipal(); if (user instanceof DatabaseUser) { DatabaseUser dbUser = (DatabaseUser) user; User u = users.getOne(dbUser.getUserId()); game.setCreator(u); // add points for the creation of a game pointsLogic.addPoint(u, -3l, -1l); } if (cs.size() < 2) { throw new RuntimeException("Not enough criteria"); } if (us.size() < 1) { throw new RuntimeException("Not enough players"); } if (rs.size() < 2) { throw new RuntimeException("Not enough requirements"); } game.setFinished(false); game = games.save(game); ProcessManager mgr = DMGame.get().getProcessManager(processId); { HActivity a = mgr.createActivity(AHPPlayerMethod.NAME, ((DatabaseUser) auth.getPrincipal()).getUserId()); a.setUserId(null); // do this to avoid showing it in the supervisor pending activities list PropertyBag bag = mgr.getProperties(a); bag.set("gameId", "" + game.getGameId()); } for (int i = 0; i < cs.size() - 1; i++) { for (int j = i + 1; j < cs.size(); j++) { HAHPCriteriasMatrixData cmd = new HAHPCriteriasMatrixData(); cmd.setGame(game); cmd.setRowCriteria(cs.get(j)); cmd.setColumnCriteria(cs.get(i)); String c1Id = cs.get(j).getCriteriaId().toString(); String c2Id = cs.get(i).getCriteriaId().toString(); if (cvs.containsKey(c1Id) && cvs.get(c1Id).containsKey(c2Id)) { cmd.setValue(new Long(cvs.get(c1Id).get(c2Id))); } else { cmd.setValue(new Long(cvs.get(c2Id).get(c1Id))); } criteriasMatricesData.save(cmd); } } for (int c = 0; c < cs.size(); c++) { for (int i = 0; i < rs.size() - 1; i++) { for (int j = i + 1; j < rs.size(); j++) { HAHPRequirementsMatrixData rmd = new HAHPRequirementsMatrixData(); rmd.setGame(game); rmd.setRowRequirement(rs.get(j)); rmd.setColumnRequirement(rs.get(i)); rmd.setCriteria(cs.get(c)); rmd.setValue(-1l); requirementsMatricesData.save(rmd); for (int p = 0; p < us.size(); p++) { HAHPPlayerMove pm = new HAHPPlayerMove(); pm.setPlayer(us.get(p)); pm.setRequirementsMatrixData(rmd); pm.setPlayed(false); playerMoves.save(pm); } HAHPJudgeAct ja = new HAHPJudgeAct(); ja.setVoted(false); ja.setRequirementsMatrixData(rmd); judgeActs.save(ja); } } } DatabaseUser currentUser = (DatabaseUser) auth.getPrincipal(); for (User u : us) { eu.supersede.integration.api.datastore.fe.types.User proxyUser = proxy.getFEDataStoreProxy() .getUser(currentUser.getTenantId(), u.getUserId().intValue(), true, currentUser.getToken()); // creation of email for the players when a game is started supersedeMailSender.sendEmail("New Decision Making Process", "Hi " + proxyUser.getFirst_name() + " " + proxyUser.getLast_name() + ", this is an automatically generated mail. You have just been invited to " + "participate in a prioritization process.", proxyUser.getEmail()); notificationUtil.createNotificationForUser(proxyUser.getEmail(), "A new decision making process has been created, are you ready to vote?", "supersede-dm-app/ahprp/player_games"); // create a GamePlayerPoint for this game and for all the players in the game HAHPGamePlayerPoint gpp = new HAHPGamePlayerPoint(); gpp.setGame(game); gpp.setUser(u); gpp.setPoints(0l); gamesPlayersPoints.save(gpp); HActivity a = mgr.createActivity(AHPPlayerMethod.NAME, u.getUserId()); PropertyBag bag = mgr.getProperties(a); bag.set("gameId", "" + game.getGameId()); } // FIXME // notificationUtil.createNotificationsForProfile("OPINION_NEGOTIATOR", // "A new decision making process has been created, you are in charge to take decisions", // "supersede-dm-app/ahprp/judge_games"); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(game.getGameId()).toUri()); return new ResponseEntity<>(game.getGameId(), httpHeaders, HttpStatus.CREATED); }
From source file:ml.shifu.core.di.builtin.binning.MunroPatBinning.java
/** * set min/max, merge same bins/*from www . ja va2 s . com*/ * * @param bins * @return */ private List<Double> binMerge(List<Double> bins) { List<Double> newBins = new ArrayList<Double>(); if (bins.size() == 0) { bins.add(Double.NaN); return bins; } Double cur = bins.get(0); newBins.add(cur); int i = 1; while (i < bins.size()) { if (Math.abs(cur - bins.get(i)) > 1e-10) { newBins.add(bins.get(i)); } cur = bins.get(i); i++; } if (newBins.size() == 1) { // special case since there is only 1 candidate in the bins double val = newBins.get(0); newBins = Arrays.asList(Double.NEGATIVE_INFINITY, val); } else if (newBins.size() == 2) { newBins.set(0, Double.NEGATIVE_INFINITY); } else { newBins.set(0, Double.NEGATIVE_INFINITY); // remove the max, and became open interval newBins.remove(newBins.size() - 1); } return newBins; }
From source file:edu.brown.utils.UniqueCombinationIterator.java
private boolean calculateCombinations(List<Integer> buffer, int position) { // If we're at the last position, then just return true if (position == this.combo_size) return (true); // Get the last element counter for this position int last_value = this.last.get(position); // Now if we go past the total number of elements, then we need to // return false // Make sure that we reset ourselves to be one more than our preceding // position//from www . jav a 2 s. com for (int i = last_value; i < this.num_elements; i++) { this.last.set(position, i); buffer.set(position, i); if (this.calculateCombinations(buffer, position + 1)) { return (true); } } // FOR // Note that we have to increase ourselves by two, because we know // that the preceding position // is going to get increased by one, so we want to make sure we're one // more than that // But everyone else should just be one more than the preceeding int base_value = this.last.get(position - 1) + 1; for (int i = position; i < this.combo_size; i++) { this.last.set(position, base_value + (i == position ? 1 : 0)); } return (false); }
From source file:com.squid.kraken.v4.core.analysis.engine.index.DimensionStore.java
@Override public String index(List<DimensionMember> members, boolean wait) { synchronized (this) { for (DimensionMember member : members) { DimensionMember check = IDs.get(member.getID()); if (check == null) { member.setIndex(size);// ww w . jav a 2 s . com members.add(member); size++; IDs.put(member.getID(), member); } else { // update values members.set(check.getIndex(), member); IDs.put(member.getID(), member); } } return ""; } }
From source file:com.lixiaocong.social.MyJdbcConnection.java
public MultiValueMap<String, Connection<?>> findConnectionsToUsers( MultiValueMap<String, String> providerUsers) { if (providerUsers == null || providerUsers.isEmpty()) { throw new IllegalArgumentException("Unable to execute find: no providerUsers provided"); }/*from w w w . ja v a 2 s. com*/ StringBuilder providerUsersCriteriaSql = new StringBuilder(); MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("userId", userId); for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) { Entry<String, List<String>> entry = it.next(); String providerId = entry.getKey(); providerUsersCriteriaSql.append("providerId = :providerId_").append(providerId) .append(" and providerUserId in (:providerUserIds_").append(providerId).append(")"); parameters.addValue("providerId_" + providerId, providerId); parameters.addValue("providerUserIds_" + providerId, entry.getValue()); if (it.hasNext()) { providerUsersCriteriaSql.append(" or "); } } List<Connection<?>> resultList = new NamedParameterJdbcTemplate(jdbcTemplate) .query(selectFromUserConnection() + " where userId = :userId and " + providerUsersCriteriaSql + " order by providerId, rank", parameters, connectionMapper); MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>(); for (Connection<?> connection : resultList) { String providerId = connection.getKey().getProviderId(); List<String> userIds = providerUsers.get(providerId); List<Connection<?>> connections = connectionsForUsers.get(providerId); if (connections == null) { connections = new ArrayList<Connection<?>>(userIds.size()); for (int i = 0; i < userIds.size(); i++) { connections.add(null); } connectionsForUsers.put(providerId, connections); } String providerUserId = connection.getKey().getProviderUserId(); int connectionIndex = userIds.indexOf(providerUserId); connections.set(connectionIndex, connection); } return connectionsForUsers; }
From source file:com.iksgmbh.sql.pojomemodb.sqlparser.SelectParser.java
private void removeTableIdFromColumnNamesIfPresent(final TableId tableId, final List<String> selectedColumns) throws SQLDataException { if (selectedColumns == null) return;//from w w w. java2 s .c o m for (int i = 0; i < selectedColumns.size(); i++) { final String oldColumnName = selectedColumns.get(i); final String alias = tableId.getAlias(); if (alias != null && oldColumnName.startsWith(alias + ".")) { // remove alias String newColumnName = oldColumnName.substring(alias.length() + 1); selectedColumns.set(i, newColumnName); } else if (oldColumnName.toUpperCase().startsWith(tableId.getTableName() + ".")) { // remove table name String newColumnName = oldColumnName.substring(tableId.getTableName().length() + 1); selectedColumns.set(i, newColumnName); } else if (!StringUtils.isEmpty(alias)) { throw new SQLDataException("Column name <" + oldColumnName + "> misses table alias."); } } }