List of usage examples for java.util LinkedList isEmpty
boolean isEmpty();
From source file:com.mirth.connect.server.controllers.MuleEngineController.java
private void configureInboundRouter(UMODescriptor descriptor, Channel channel) throws Exception { logger.debug("configuring inbound router for channel: " + channel.getId() + " (" + channel.getName() + ")"); InboundMessageRouter inboundRouter = new InboundMessageRouter(); Exception exceptionRegisteringInboundRouter = null; MuleEndpoint endpoint = new MuleEndpoint(); String connectorReference = getConnectorReferenceForInboundRouter(channel); // Check if the channel is synchronous if ((channel.getProperties().get("synchronous")) != null && ((String) channel.getProperties().get("synchronous")).equalsIgnoreCase("true")) { endpoint.setSynchronous(true);/*from ww w . ja v a 2 s . c o m*/ } // STEP 1. append the default transformers required by the transport // (ex. ByteArrayToString) ConnectorMetaData transport = transports.get(channel.getSourceConnector().getTransportName()); LinkedList<UMOTransformer> transformerList = null; if (transport.getTransformers() != null) { transformerList = chainTransformers(transport.getTransformers()); } // STEP 2. append the preprocessing transformer UMOTransformer preprocessorTransformer = createPreprocessor(channel, connectorReference + "_preprocessor"); try { muleManager.registerTransformer(preprocessorTransformer); } catch (Exception e) { exceptionRegisteringInboundRouter = e; } if (!transformerList.isEmpty()) { transformerList.getLast().setTransformer(preprocessorTransformer); } else { // there were no default transformers, so make the preprocessor // the first transformer in the list transformerList.add(preprocessorTransformer); } // STEP 3. finally, append the JavaScriptTransformer that does the // mappings UMOTransformer javascriptTransformer = createTransformer(channel, channel.getSourceConnector(), connectorReference + "_transformer"); try { muleManager.registerTransformer(javascriptTransformer); } catch (Exception e) { exceptionRegisteringInboundRouter = e; } preprocessorTransformer.setTransformer(javascriptTransformer); // STEP 4. add the transformer sequence as an attribute to the endpoint endpoint.setTransformer(transformerList.getFirst()); SelectiveConsumer selectiveConsumerRouter = new SelectiveConsumer(); selectiveConsumerRouter.setFilter(new ValidMessageFilter()); inboundRouter.addRouter(selectiveConsumerRouter); String endpointUri = getEndpointUri(channel.getSourceConnector()); /* * NOTE: Even though every channel already has a VM Connector, we still * need to add a Channel Reader connector because of its possible * additional properties like "respond from". If a channel reader is * being used, add the channel id to the endpointUri so the endpoint can * be deployed. * * Set the endpoint name to the channelId so * InboundMessageRouter#route(UMOEvent event) gets the right channel id. */ if (endpointUri.equals("vm://")) { endpointUri += channel.getId(); endpoint.setName(channel.getId()); endpoint.setCreateConnector(1); } else { // add source endpoints MuleEndpoint vmEndpoint = new MuleEndpoint(); vmEndpoint.setEndpointURI(new MuleEndpointURI(new URI("vm://" + channel.getId()).toString())); vmEndpoint.setTransformer(preprocessorTransformer); /* * XXX: Set create connector to true so that channel readers will * not use an existing connector (one from a different channel). Not * entirely sure why this is required, but if this is set to 0 then * a VM EndpointService mbean is created, and when undeploying * channels a null pointer is sometimes thrown when calling * unregisterComponent(descriptor). The error occurs in * AbstractConnector.unregisterListener because receivers is null. */ vmEndpoint.setCreateConnector(1); inboundRouter.addEndpoint(vmEndpoint); } endpoint.setEndpointURI(new MuleEndpointURI(endpointUri, channel.getId())); /* * MUST BE LAST STEP: Add the source connector last so that if an * exception occurs (like creating the URI) it wont register the JMX * service. * * If there are any exceptions registering the connector, still add the * endpoint and inbound router so that the channel can be properly * unregistered. */ try { endpoint.setConnector(registerConnector(channel.getSourceConnector(), getConnectorNameForRouter(connectorReference), channel.getId())); } catch (Exception e) { exceptionRegisteringInboundRouter = e; } inboundRouter.addEndpoint(endpoint); descriptor.setInboundRouter(inboundRouter); if (exceptionRegisteringInboundRouter != null) { throw exceptionRegisteringInboundRouter; } }
From source file:org.deegree.framework.xml.XMLFragment.java
/** * reads the encoding of a XML document from its header. If no header available * <code>CharsetUtils.getSystemCharset()</code> will be returned * /*from w ww . j a v a2s . co m*/ * @param pbis * @return encoding of a XML document * @throws IOException */ private String readEncoding(PushbackInputStream pbis) throws IOException { byte[] b = new byte[80]; String s = ""; int rd = 0; LinkedList<byte[]> bs = new LinkedList<byte[]>(); LinkedList<Integer> rds = new LinkedList<Integer>(); while (rd < 80) { rds.addFirst(pbis.read(b)); if (rds.peek() == -1) { rds.poll(); break; } rd += rds.peek(); s += new String(b, 0, rds.peek()).toLowerCase(); bs.addFirst(b); b = new byte[80]; } String encoding = CharsetUtils.getSystemCharset(); if (s.indexOf("?>") > -1) { int p = s.indexOf("encoding="); if (p > -1) { StringBuffer sb = new StringBuffer(); int k = p + 1 + "encoding=".length(); while (s.charAt(k) != '"' && s.charAt(k) != '\'') { sb.append(s.charAt(k++)); } encoding = sb.toString(); } } while (!bs.isEmpty()) { pbis.unread(bs.poll(), 0, rds.poll()); } return encoding; }
From source file:azkaban.execapp.FlowRunner.java
private void resetFailedState(final ExecutableFlowBase flow, final List<ExecutableNode> nodesToRetry) { // bottom up//from www. j a va2 s .c o m final LinkedList<ExecutableNode> queue = new LinkedList<>(); for (final String id : flow.getEndNodes()) { final ExecutableNode node = flow.getExecutableNode(id); queue.add(node); } long maxStartTime = -1; while (!queue.isEmpty()) { final ExecutableNode node = queue.poll(); final Status oldStatus = node.getStatus(); maxStartTime = Math.max(node.getStartTime(), maxStartTime); final long currentTime = System.currentTimeMillis(); if (node.getStatus() == Status.SUCCEEDED) { // This is a candidate parent for restart nodesToRetry.add(node); continue; } else if (node.getStatus() == Status.RUNNING) { continue; } else if (node.getStatus() == Status.KILLING) { continue; } else if (node.getStatus() == Status.SKIPPED) { node.setStatus(Status.DISABLED); node.setEndTime(-1); node.setStartTime(-1); node.setUpdateTime(currentTime); } else if (node instanceof ExecutableFlowBase) { final ExecutableFlowBase base = (ExecutableFlowBase) node; switch (base.getStatus()) { case CANCELLED: node.setStatus(Status.READY); node.setEndTime(-1); node.setStartTime(-1); node.setUpdateTime(currentTime); // Break out of the switch. We'll reset the flow just like a normal // node break; case KILLED: case FAILED: case FAILED_FINISHING: resetFailedState(base, nodesToRetry); continue; default: // Continue the while loop. If the job is in a finished state that's // not // a failure, we don't want to reset the job. continue; } } else if (node.getStatus() == Status.CANCELLED) { // Not a flow, but killed node.setStatus(Status.READY); node.setStartTime(-1); node.setEndTime(-1); node.setUpdateTime(currentTime); } else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) { node.resetForRetry(); nodesToRetry.add(node); } if (!(node instanceof ExecutableFlowBase) && node.getStatus() != oldStatus) { this.logger.info( "Resetting job '" + node.getNestedId() + "' from " + oldStatus + " to " + node.getStatus()); } for (final String inId : node.getInNodes()) { final ExecutableNode nodeUp = flow.getExecutableNode(inId); queue.add(nodeUp); } } // At this point, the following code will reset the flow final Status oldFlowState = flow.getStatus(); if (maxStartTime == -1) { // Nothing has run inside the flow, so we assume the flow hasn't even // started running yet. flow.setStatus(Status.READY); } else { flow.setStatus(Status.RUNNING); // Add any READY start nodes. Usually it means the flow started, but the // start node has not. for (final String id : flow.getStartNodes()) { final ExecutableNode node = flow.getExecutableNode(id); if (node.getStatus() == Status.READY || node.getStatus() == Status.DISABLED) { nodesToRetry.add(node); } } } flow.setUpdateTime(System.currentTimeMillis()); flow.setEndTime(-1); this.logger.info( "Resetting flow '" + flow.getNestedId() + "' from " + oldFlowState + " to " + flow.getStatus()); }
From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.UpdateExerciseAction.java
@Override public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT); JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON); JsonElement idExerciseElement = json.get(Constants.ACTION_PARAM_ID); JsonElement titleElement = json.get(Constants.ACTION_PARAM_TITLE); JsonElement topicsElement = json.get(Constants.ACTION_PARAM_TOPICS); JsonElement descriptionElement = json.get(Constants.ACTION_PARAM_DESCRIPTION); JsonElement difficultyElement = json.get(Constants.ACTION_PARAM_DIFFICULTY); JsonElement technologyElement = json.get(Constants.ACTION_PARAM_TECHNOLOGY); JsonElement durationElement = json.get(Constants.ACTION_PARAM_DURATION); JsonElement trophyTitleElement = json.get(Constants.ACTION_PARAM_TROPHY_TITLE); JsonElement trophyDescriptionElement = json.get(Constants.ACTION_PARAM_TROPHY_DESCRIPTION); JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS); JsonElement typeElement = json.get(Constants.ACTION_PARAM_TYPE); JsonElement authorElement = json.get(Constants.ACTION_PARAM_AUTHOR); AvailableExercise exercise = new AvailableExercise(); AvailableExercise oldExercise = hpc.getAvailableExerciseComplete(idExerciseElement.getAsInt()); if (null == oldExercise) { MessageGenerator.sendErrorMessage("NotFound", response); return;/*from ww w. jav a 2 s. co m*/ } exercise.setDescription(descriptionElement.getAsString()); exercise.setUuid(oldExercise.getUuid()); exercise.setDifficulty(difficultyElement.getAsString()); exercise.setDuration(durationElement.getAsInt()); exercise.setTitle(titleElement.getAsString()); exercise.setSubtitle(topicsElement.getAsString()); exercise.setTechnology(technologyElement.getAsString()); exercise.setStatus(AvailableExerciseStatus.getStatusFromStatusCode(statusElement.getAsInt())); exercise.setAuthor(authorElement.getAsString()); Integer v = oldExercise.getVersion(); if (v == null) v = 0; exercise.setVersion(v + 1); AvailableExerciseType validType = null; for (AvailableExerciseType t : AvailableExerciseType.values()) { if (t.toString().equals(typeElement.getAsString())) { validType = t; break; } } if (validType == null) validType = AvailableExerciseType.BOTH; exercise.setExerciseType(validType); Trophy trophy = new Trophy(); trophy.setDescription(trophyDescriptionElement.getAsString()); trophy.setName(trophyTitleElement.getAsString()); trophy.setTechnology(exercise.getTechnology()); exercise.setTrophy(trophy); JsonElement flags = json.get(Constants.ACTION_PARAM_FLAGS_LIST); JsonElement infos = json.get(Constants.ACTION_PARAM_INFO_LIST); JsonElement resources = json.get(Constants.ACTION_PARAM_RESOURCE_LIST); JsonElement referenceFile = json.get(Constants.ACTION_PARAM_REFERENCE_FILE); if (null != referenceFile) { JsonObject referenceFileObj = referenceFile.getAsJsonObject(); String tmpReferenceFileString = referenceFileObj.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpReferenceFile = null; try { tmpReferenceFileString = tmpReferenceFileString.replaceFirst("(.*);base64,", ""); tmpReferenceFile = Base64.decodeBase64(tmpReferenceFileString); } catch (Exception e) { logger.warn("ReferenceFile Parsing error for user " + user.getIdUser() + " in updating exercise " + idExerciseElement.getAsInt() + " due to: " + e.getMessage(), response); } if (null != tmpReferenceFile && tmpReferenceFile.length != 0) { AvailableExerciseReferenceFile refFile = new AvailableExerciseReferenceFile(); refFile.setFile(tmpReferenceFile); refFile.setFilename(referenceFileObj.get(Constants.ACTION_PARAM_NAME).getAsString()); exercise.setReferenceFile(refFile); exercise.setReferenceFileAvailable(true); } else { exercise.setReferenceFileAvailable(false); } } else { exercise.setReferenceFileAvailable(false); } JsonElement solutionFile = json.get(Constants.ACTION_PARAM_SOLUTION_FILE); JsonObject solutionFileObj = solutionFile.getAsJsonObject(); String tmpSolutionFileString = solutionFileObj.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpSolutioneFile = null; try { tmpSolutionFileString = tmpSolutionFileString.replaceFirst("(.*);base64,", ""); tmpSolutioneFile = Base64.decodeBase64(tmpSolutionFileString); } catch (Exception e) { MessageGenerator.sendErrorMessage("solutioneFileParsing", response); return; } if (null == tmpSolutioneFile || tmpSolutioneFile.length == 0) { MessageGenerator.sendErrorMessage("solutioneFileEmpty", response); return; } AvailableExerciseSolutionFile solFile = new AvailableExerciseSolutionFile(); solFile.setFilename(solutionFileObj.get(Constants.ACTION_PARAM_NAME).getAsString()); solFile.setFile(tmpSolutioneFile); exercise.setSolutionFile(solFile); Map<String, String> resourceMap = new HashMap<String, String>(); for (JsonElement resourceElem : resources.getAsJsonArray()) { JsonObject tmpResource = resourceElem.getAsJsonObject(); resourceMap.put(tmpResource.get(Constants.ACTION_PARAM_TITLE).getAsString(), tmpResource.get(Constants.ACTION_PARAM_URL).getAsString()); } exercise.setResources(resourceMap); LinkedList<AvailableExerciseInfo> infoList = new LinkedList<AvailableExerciseInfo>(); int n = 0; for (JsonElement infoElem : infos.getAsJsonArray()) { JsonObject tmpInfo = infoElem.getAsJsonObject(); AvailableExerciseInfo tmpExInfo = new AvailableExerciseInfo(); tmpExInfo.setTitle(tmpInfo.get(Constants.ACTION_PARAM_TITLE).getAsString()); tmpExInfo.setDescription(tmpInfo.get(Constants.ACTION_PARAM_DESCRIPTION).getAsString()); tmpExInfo.setInfoOrder(n); JsonObject tmpImage = tmpInfo.get(Constants.ACTION_PARAM_IMAGE).getAsJsonObject(); String imageString = tmpImage.get(Constants.ACTION_PARAM_DATA).getAsString(); byte[] tmpImageFile = null; try { imageString = imageString.replaceFirst("(.*);base64,", ""); tmpImageFile = Base64.decodeBase64(imageString); } catch (Exception e) { MessageGenerator.sendErrorMessage("infoImageParsing", response); return; } tmpExInfo.setImage(tmpImageFile); infoList.add(tmpExInfo); n++; } exercise.setInfoList(infoList); if (infoList.isEmpty()) { MessageGenerator.sendErrorMessage("infoListEmpty", response); return; } Integer totalScore = 0; LinkedList<Flag> flagList = new LinkedList<Flag>(); for (JsonElement flagElem : flags.getAsJsonArray()) { Flag flag = new Flag(); JsonObject tmpFlag = flagElem.getAsJsonObject(); JsonElement flagTitle = tmpFlag.get(Constants.ACTION_PARAM_TITLE); JsonElement flagCategory = tmpFlag.get(Constants.ACTION_PARAM_CATEGORY); JsonElement flagQuestions = tmpFlag.get(Constants.ACTION_PARAM_FLAG_QUESTIONS); flag.setCategory(flagCategory.getAsString()); flag.setTitle(flagTitle.getAsString()); LinkedList<FlagQuestion> questionList = new LinkedList<FlagQuestion>(); for (JsonElement questionElem : flagQuestions.getAsJsonArray()) { FlagQuestion tmpQuestion = new FlagQuestion(); JsonObject qEl = questionElem.getAsJsonObject(); tmpQuestion.setType(qEl.get(Constants.ACTION_PARAM_TYPE).getAsString()); tmpQuestion.setOptional(qEl.get(Constants.ACTION_PARAM_OPTIONAL).getAsBoolean()); if (!tmpQuestion.getOptional()) { tmpQuestion.setMaxScore(qEl.get(Constants.ACTION_PARAM_MAX_SCORE).getAsInt()); totalScore += tmpQuestion.getMaxScore(); } tmpQuestion .setSelfCheckAvailable(qEl.get(Constants.ACTION_PARAM_SELF_CHECK_AVAILABLE).getAsBoolean()); if (tmpQuestion.getSelfCheckAvailable()) tmpQuestion.setSelfCheckName(qEl.get(Constants.ACTION_PARAM_SELF_CHECK).getAsString()); else tmpQuestion.setSelfCheckName(null); tmpQuestion.setInstructions(qEl.get(Constants.ACTION_PARAM_INSTRUCTIONS).getAsString()); tmpQuestion.setHintAvailable(qEl.get(Constants.ACTION_PARAM_HINT_AVAILABLE).getAsBoolean()); if (tmpQuestion.getHintAvailable()) { FlagQuestionHint tmpQuestionHint = new FlagQuestionHint(); tmpQuestionHint.setType(tmpQuestion.getType()); Gson gson = new Gson(); FlagQuestionHint newHint = gson.fromJson(qEl.get(Constants.ACTION_PARAM_HINT).getAsJsonObject(), FlagQuestionHint.class); if (null != newHint) { tmpQuestionHint.setText(newHint.getText()); if (!tmpQuestion.getOptional()) tmpQuestionHint.setScoreReducePercentage(newHint.getScoreReducePercentage()); tmpQuestion.setHint(tmpQuestionHint); } else { MessageGenerator.sendErrorMessage("hintEmpty", response); return; } } else { tmpQuestion.setHint(null); } questionList.add(tmpQuestion); } flag.setFlagQuestionList(questionList); flagList.add(flag); } exercise.setFlags(flagList); if (flagList.isEmpty()) { MessageGenerator.sendErrorMessage("flagListEmpty", response); return; } exercise.setScore(totalScore); Integer idNewExercise = hpc.addAvailableExercise(exercise); if (null != idNewExercise) { oldExercise.setStatus(AvailableExerciseStatus.SUPERSEDED); hpc.updateAvailableExercise(oldExercise); List<Organization> organizations = hpc.getAllOrganizations(); oldExercise = hpc.getAvailableExerciseComplete(oldExercise.getId()); AvailableExercise newExercise = hpc.getAvailableExerciseComplete(idNewExercise); for (Organization org : organizations) { if (hpc.isExerciseEnabledForOrganization(org.getId(), oldExercise.getId())) { hpc.addAvailableExerciseForOrganization(org, newExercise); } } hpc.updateAllTaskDefinitionsForExercise(oldExercise.getId(), idNewExercise); MessageGenerator.sendExerciseInfoMessageWithHints(newExercise, response); } else { MessageGenerator.sendErrorMessage("Error", response); } }
From source file:org.eclipse.ecr.core.storage.sql.TestSQLBackend.java
private static Map<String, Set<String>> buildDescendants(List<String[]> graph, String root) { Map<String, Set<String>> ancestors = new HashMap<String, Set<String>>(); Map<String, Set<String>> descendants = new HashMap<String, Set<String>>(); // create all sets, for clearer code later for (String[] edge : graph) { for (String n : edge) { if (!ancestors.containsKey(n)) { ancestors.put(n, new HashSet<String>()); }//from w ww. j av a 2s . c o m if (!descendants.containsKey(n)) { descendants.put(n, new HashSet<String>()); } } } // traverse from root LinkedList<String> todo = new LinkedList<String>(); todo.add(root); do { String p = todo.removeFirst(); for (String[] edge : graph) { if (edge[0].equals(p)) { // found a child String c = edge[1]; todo.add(c); // child's ancestors Set<String> cans = ancestors.get(c); cans.addAll(ancestors.get(p)); cans.add(p); // all ancestors have it as descendant for (String pp : cans) { descendants.get(pp).add(c); } } } } while (!todo.isEmpty()); return descendants; }
From source file:org.pf9.pangu.app.act.rest.diagram.services.ProcessInstanceHighlightsResource.java
/** * getHighlightedFlows//from w w w. j a v a 2 s . co m * * code logic: 1. Loop all activities by id asc order; 2. Check each activity's outgoing transitions and eventBoundery outgoing transitions, if * outgoing transitions's destination.id is in other executed activityIds, add this transition to highLightedFlows List; 3. But if activity is not * a parallelGateway or inclusiveGateway, only choose the earliest flow. * * @param activityList * @param hisActInstList * @param highLightedFlows */ private void getHighlightedFlows(List<ActivityImpl> activityList, LinkedList<HistoricActivityInstance> hisActInstList, List<String> highLightedFlows) { //check out startEvents in activityList List<ActivityImpl> startEventActList = new ArrayList<ActivityImpl>(); Map<String, ActivityImpl> activityMap = new HashMap<String, ActivityImpl>(activityList.size()); for (ActivityImpl activity : activityList) { activityMap.put(activity.getId(), activity); String actType = (String) activity.getProperty("type"); if (actType != null && actType.toLowerCase().indexOf("startevent") >= 0) { startEventActList.add(activity); } } //These codes is used to avoid a bug: //ACT-1728 If the process instance was started by a callActivity, it will be not have the startEvent activity in ACT_HI_ACTINST table //Code logic: //Check the first activity if it is a startEvent, if not check out the startEvent's highlight outgoing flow. HistoricActivityInstance firstHistActInst = hisActInstList.getFirst(); String firstActType = (String) firstHistActInst.getActivityType(); if (firstActType != null && firstActType.toLowerCase().indexOf("startevent") < 0) { PvmTransition startTrans = getStartTransaction(startEventActList, firstHistActInst); if (startTrans != null) { highLightedFlows.add(startTrans.getId()); } } while (!hisActInstList.isEmpty()) { HistoricActivityInstance histActInst = hisActInstList.removeFirst(); ActivityImpl activity = activityMap.get(histActInst.getActivityId()); if (activity != null) { boolean isParallel = false; String type = histActInst.getActivityType(); if ("parallelGateway".equals(type) || "inclusiveGateway".equals(type)) { isParallel = true; } else if ("subProcess".equals(histActInst.getActivityType())) { getHighlightedFlows(activity.getActivities(), hisActInstList, highLightedFlows); } List<PvmTransition> allOutgoingTrans = new ArrayList<PvmTransition>(); allOutgoingTrans.addAll(activity.getOutgoingTransitions()); allOutgoingTrans.addAll(getBoundaryEventOutgoingTransitions(activity)); List<String> activityHighLightedFlowIds = getHighlightedFlows(allOutgoingTrans, hisActInstList, isParallel); highLightedFlows.addAll(activityHighLightedFlowIds); } } }
From source file:org.nd4j.linalg.util.ArrayUtil.java
/** Convert an arbitrary-dimensional rectangular float array to flat vector.<br> * Can pass float[], float[][], float[][][], etc. *//*ww w.ja va 2 s .c o m*/ public static float[] flattenFloatArray(Object floatArray) { if (floatArray instanceof float[]) return (float[]) floatArray; LinkedList<Object> stack = new LinkedList<>(); stack.push(floatArray); int[] shape = arrayShape(floatArray); int length = ArrayUtil.prod(shape); float[] flat = new float[length]; int count = 0; while (!stack.isEmpty()) { Object current = stack.pop(); if (current instanceof float[]) { float[] arr = (float[]) current; for (int i = 0; i < arr.length; i++) flat[count++] = arr[i]; } else if (current instanceof Object[]) { Object[] o = (Object[]) current; for (int i = o.length - 1; i >= 0; i--) stack.push(o[i]); } else throw new IllegalArgumentException("Base array is not float[]"); } if (count != flat.length) throw new IllegalArgumentException("Fewer elements than expected. Array is ragged?"); return flat; }
From source file:org.nd4j.linalg.util.ArrayUtil.java
/** Convert an arbitrary-dimensional rectangular double array to flat vector.<br> * Can pass double[], double[][], double[][][], etc. *///from ww w. j a v a2 s . com public static double[] flattenDoubleArray(Object doubleArray) { if (doubleArray instanceof double[]) return (double[]) doubleArray; LinkedList<Object> stack = new LinkedList<>(); stack.push(doubleArray); int[] shape = arrayShape(doubleArray); int length = ArrayUtil.prod(shape); double[] flat = new double[length]; int count = 0; while (!stack.isEmpty()) { Object current = stack.pop(); if (current instanceof double[]) { double[] arr = (double[]) current; for (int i = 0; i < arr.length; i++) flat[count++] = arr[i]; } else if (current instanceof Object[]) { Object[] o = (Object[]) current; for (int i = o.length - 1; i >= 0; i--) stack.push(o[i]); } else throw new IllegalArgumentException("Base array is not double[]"); } if (count != flat.length) throw new IllegalArgumentException("Fewer elements than expected. Array is ragged?"); return flat; }
From source file:edu.uci.ics.hyracks.algebricks.rewriter.rules.EnforceStructuralPropertiesRule.java
private void addLocalEnforcers(AbstractLogicalOperator op, int i, List<ILocalStructuralProperty> localProperties, boolean nestedPlan, IOptimizationContext context) throws AlgebricksException { if (AlgebricksConfig.DEBUG) { AlgebricksConfig.ALGEBRICKS_LOGGER .fine(">>>> Adding local enforcers for local props = " + localProperties + "\n"); }//from w ww . j a va 2 s .c o m if (localProperties == null || localProperties.isEmpty()) { return; } Mutable<ILogicalOperator> topOp = new MutableObject<ILogicalOperator>(); topOp.setValue(op.getInputs().get(i).getValue()); LinkedList<LocalOrderProperty> oList = new LinkedList<LocalOrderProperty>(); for (ILocalStructuralProperty prop : localProperties) { switch (prop.getPropertyType()) { case LOCAL_ORDER_PROPERTY: { oList.add((LocalOrderProperty) prop); break; } case LOCAL_GROUPING_PROPERTY: { LocalGroupingProperty g = (LocalGroupingProperty) prop; Collection<LogicalVariable> vars = (g.getPreferredOrderEnforcer() != null) ? g.getPreferredOrderEnforcer() : g.getColumnSet(); List<OrderColumn> orderColumns = new ArrayList<OrderColumn>(); for (LogicalVariable v : vars) { OrderColumn oc = new OrderColumn(v, OrderKind.ASC); orderColumns.add(oc); } LocalOrderProperty lop = new LocalOrderProperty(orderColumns); oList.add(lop); break; } default: { throw new IllegalStateException(); } } } if (!oList.isEmpty()) { topOp = enforceOrderProperties(oList, topOp, nestedPlan, context); } op.getInputs().set(i, topOp); OperatorPropertiesUtil.computeSchemaAndPropertiesRecIfNull((AbstractLogicalOperator) topOp.getValue(), context); printOp((AbstractLogicalOperator) topOp.getValue()); }
From source file:com.hichinaschool.flashcards.libanki.Finder.java
private String _findField(String field, String val) { val = val.replace("*", "%"); // find models that have that field Map<Long, Object[]> mods = new HashMap<Long, Object[]>(); try {/*from ww w .j a va2s . c om*/ for (JSONObject m : mCol.getModels().all()) { JSONArray flds = m.getJSONArray("flds"); for (int fi = 0; fi < flds.length(); ++fi) { JSONObject f = flds.getJSONObject(fi); if (f.getString("name").equalsIgnoreCase(field)) { mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") }); } } } } catch (JSONException e) { throw new RuntimeException(e); } if (mods.isEmpty()) { // nothing has that field return ""; } // gather nids // Pattern.quote escapes the meta characters with \Q \E String regex = Pattern.quote(val).replace("\\Q_\\E", ".").replace("\\Q%\\E", ".*"); LinkedList<Long> nids = new LinkedList<Long>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase() .rawQuery("select id, mid, flds from notes where mid in " + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'", new String[] { "%" + val + "%" }); while (cur.moveToNext()) { String[] flds = Utils.splitFields(cur.getString(2)); int ord = (Integer) mods.get(cur.getLong(1))[1]; String strg = flds[ord]; if (Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(strg).matches()) { nids.add(cur.getLong(0)); } } } finally { if (cur != null) { cur.close(); } } if (nids.isEmpty()) { return ""; } return "n.id in " + Utils.ids2str(nids); }