code
stringlengths
10
174k
nl
stringlengths
3
129k
public void processLine(LineString l,double weight){ double usedRadius; switch (this.kdeType) { case CELL: usedRadius=Math.max(this.radius,this.grid.getCellWidth() / 2.0); break; case GAUSSIAN: usedRadius=3.0 * this.radius; break; default : usedRadius=this.radius; break; } double sum=0.0; Coordinate c0=l.getCoordinateN(0); Coordinate c1=l.getCoordinateN(1); Collection<Point> neighbours=this.grid.getGrid().getElliptical(c0.x,c0.y,c1.x,c1.y,2 * usedRadius + l.getLength()); Map<Point,Double> interimMap=new HashMap<Point,Double>(neighbours.size()); Iterator<Point> iterator=neighbours.iterator(); while (iterator.hasNext()) { Point centroid=iterator.next(); Geometry cell=this.grid.getCellGeometry(centroid); switch (this.kdeType) { case CELL: Geometry intersection=cell.intersection(l); if (!intersection.isEmpty()) { double w=intersection.getLength() / l.getLength(); interimMap.put(centroid,w); sum+=w; } break; case EPANECHNIKOV: case GAUSSIAN: case TRIANGULAR: case TRIWEIGHT: case UNIFORM: double distance=centroid.distance(l); if (distance <= this.radius) { double w=getFunctionFromDistance(distance) * weight; interimMap.put(centroid,w); sum+=w; } break; default : break; } } for (Point p : interimMap.keySet()) { if (!this.weight.containsKey(p)) { this.weight.put(p,interimMap.get(p) / sum * weight); } else { this.weight.put(p,this.weight.get(p) + interimMap.get(p) / sum * weight); } } lineCounter.incCounter(); }
Currently (September 2014, JWJ) this class processes the area along a given line segment by incrementally identifying points along the line, and finding all the cells within the given radius from the search point.
public Outfit(){ this(0,0,0,0,0,0,0); }
Creates a new default outfit (naked person).
public synchronized BookKeeperClientBuilder zkc(ZooKeeperClient zkc){ this.zkc=zkc; return this; }
Set the zkc used to build bookkeeper client. If a zookeeper client is provided in this method, bookkeeper client will use it rather than creating a brand new one.
public boolean isSyncEnabled(String username){ Account account=getAccount(username); if (account == null) { return false; } return ContentResolver.getSyncAutomatically(account,ContactsContract.AUTHORITY); }
Checks if sync is enabled.
public boolean isAcceptDiscover(){ Object oo=get_Value(COLUMNNAME_AcceptDiscover); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
Get Accept Discover.
public QueryStringQueryBuilder lowercaseExpandedTerms(boolean lowercaseExpandedTerms){ this.lowercaseExpandedTerms=lowercaseExpandedTerms; return this; }
Whether terms of wildcard, prefix, fuzzy and range queries are to be automatically lower-cased or not. Default is <tt>true</tt>.
@Override public boolean retainAll(@NonNull Collection<?> collection){ boolean removed=false; for (int i=mSize - 1; i >= 0; i--) { if (!collection.contains(mArray[i])) { removeAt(i); removed=true; } } return removed; }
Remove all values in the array set that do <b>not</b> exist in the given collection.
public boolean isPost(){ return post; }
Returns true for a post operation and false for a get operation
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; String DEMHeader=null; int row, col, x, y; int progress=0; double z, val, val2, val3; int i, c; int[] dX=new int[]{1,1,1,0,-1,-1,-1,0}; int[] dY=new int[]{-1,0,1,1,1,0,-1,-1}; double[] inflowingVals=new double[]{16,32,64,128,1,2,4,8}; boolean flag=false; double flowDir=0; double flowLength=0; double numUpslopeFlowpaths=0; double flowpathLengthToAdd=0; double conversionFactor=1; double divideElevToAdd=0; double radToDeg=180 / Math.PI; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader=args[0]; DEMHeader=args[1]; outputHeader=args[2]; conversionFactor=Double.parseDouble(args[3]); if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster pntr=new WhiteboxRaster(inputHeader,"r"); int rows=pntr.getNumberRows(); int cols=pntr.getNumberColumns(); double noData=pntr.getNoDataValue(); double gridResX=pntr.getCellSizeX(); double gridResY=pntr.getCellSizeY(); double diagGridRes=Math.sqrt(gridResX * gridResX + gridResY * gridResY); double[] gridLengths=new double[]{diagGridRes,gridResX,diagGridRes,gridResY,diagGridRes,gridResX,diagGridRes,gridResY}; WhiteboxRaster DEM=new WhiteboxRaster(DEMHeader,"r"); if (DEM.getNumberRows() != rows || DEM.getNumberColumns() != cols) { showFeedback("The input files must have the same dimensions, i.e. number of " + "rows and columns."); return; } WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,-999); output.setPreferredPalette("blueyellow.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); output.setZUnits(pntr.getXYUnits()); WhiteboxRaster numInflowingNeighbours=new WhiteboxRaster(outputHeader.replace(".dep","_temp1.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); numInflowingNeighbours.isTemporaryFile=true; WhiteboxRaster numUpslopeDivideCells=new WhiteboxRaster(outputHeader.replace(".dep","_temp2.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); numUpslopeDivideCells.isTemporaryFile=true; WhiteboxRaster totalFlowpathLength=new WhiteboxRaster(outputHeader.replace(".dep","_temp3.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); totalFlowpathLength.isTemporaryFile=true; WhiteboxRaster totalUpslopeDivideElev=new WhiteboxRaster(outputHeader.replace(".dep","_temp4.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); totalUpslopeDivideElev.isTemporaryFile=true; updateProgress("Loop 1 of 3:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (pntr.getValue(row,col) != noData) { z=0; for (i=0; i < 8; i++) { if (pntr.getValue(row + dY[i],col + dX[i]) == inflowingVals[i]) { z++; } } if (z > 0) { numInflowingNeighbours.setValue(row,col,z); } else { numInflowingNeighbours.setValue(row,col,-1); } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 1 of 3:",progress); } updateProgress("Loop 2 of 3:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { val=numInflowingNeighbours.getValue(row,col); if (val <= 0 && val != noData) { flag=false; x=col; y=row; do { val=numInflowingNeighbours.getValue(y,x); if (val <= 0 && val != noData) { if (val == -1) { numUpslopeDivideCells.setValue(y,x,0); numUpslopeFlowpaths=1; divideElevToAdd=DEM.getValue(y,x); } else { numUpslopeFlowpaths=numUpslopeDivideCells.getValue(y,x); divideElevToAdd=totalUpslopeDivideElev.getValue(y,x); } numInflowingNeighbours.setValue(y,x,noData); flowDir=pntr.getValue(y,x); if (flowDir > 0) { c=(int)(Math.log(flowDir) / LnOf2); flowLength=gridLengths[c]; val2=totalFlowpathLength.getValue(y,x); flowpathLengthToAdd=val2 + numUpslopeFlowpaths * flowLength; x+=dX[c]; y+=dY[c]; numUpslopeDivideCells.setValue(y,x,numUpslopeDivideCells.getValue(y,x) + numUpslopeFlowpaths); totalFlowpathLength.setValue(y,x,totalFlowpathLength.getValue(y,x) + flowpathLengthToAdd); totalUpslopeDivideElev.setValue(y,x,totalUpslopeDivideElev.getValue(y,x) + divideElevToAdd); numInflowingNeighbours.setValue(y,x,numInflowingNeighbours.getValue(y,x) - 1); } else { flag=true; } } else { flag=true; } } while (!flag); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 2 of 3:",progress); } numUpslopeDivideCells.flush(); totalFlowpathLength.flush(); totalUpslopeDivideElev.flush(); numInflowingNeighbours.close(); updateProgress("Loop 3 of 3:",0); double[] data1=null; double[] data2=null; double[] data3=null; double[] data4=null; double[] data5=null; for (row=0; row < rows; row++) { data1=numUpslopeDivideCells.getRowValues(row); data2=totalFlowpathLength.getRowValues(row); data3=pntr.getRowValues(row); data4=totalUpslopeDivideElev.getRowValues(row); data5=DEM.getRowValues(row); for (col=0; col < cols; col++) { if (data3[col] != noData) { if (data1[col] > 0) { val=data2[col] / data1[col]; val2=(data4[col] / data1[col] - data5[col]) * conversionFactor; val3=Math.atan(val2 / val) * radToDeg; output.setValue(row,col,val3); } else { output.setValue(row,col,0); } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 3 of 3:",progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); DEM.close(); numUpslopeDivideCells.close(); totalFlowpathLength.close(); totalUpslopeDivideElev.close(); output.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public static void main(String[] args) throws IOException { TestSourceTab tester=new TestSourceTab(); run(tester,ARGS1,TEST,NEGATED_TEST); run(tester,ARGS2,TEST,NEGATED_TEST); tester.runDiffs(FILES_TO_DIFF); }
The entry point of the test.
private void assertZipAndUnzipOfDirectoryMatchesOriginal(File sourceDir) throws IOException { File[] sourceFiles=sourceDir.listFiles(); Arrays.sort(sourceFiles); File zipFile=createZipFileHandle(); ZipFiles.zipDirectory(sourceDir,zipFile); File outputDir=Files.createTempDir(); ZipFiles.unzipFile(zipFile,outputDir); File[] outputFiles=outputDir.listFiles(); Arrays.sort(outputFiles); assertThat(outputFiles,arrayWithSize(sourceFiles.length)); for (int i=0; i < sourceFiles.length; i++) { compareFileContents(sourceFiles[i],outputFiles[i]); } removeRecursive(outputDir.toPath()); assertTrue(zipFile.delete()); }
zip and unzip a certain directory, and verify the content afterward to be identical.
@Provides @Singleton @Named("RetrofitGoodreads") Retrofit provideGoodreadsRetrofit(@ApiClient OkHttpClient apiClient,GoodreadsInterceptor goodreadsInterceptor){ OkHttpClient goodreadsClient=apiClient.clone(); goodreadsClient.interceptors().add(goodreadsInterceptor); return new Retrofit.Builder().client(goodreadsClient).baseUrl(HttpUrl.parse(BuildConfig.GOOD_READ_ENDPOINT_URL)).addConverterFactory(SimpleXmlConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); }
We need to create a new retrofit instance for goodreads api because it needs to hook in to a different base url and uses an xml converter instead.
@SuppressWarnings({"unchecked","rawtypes"}) private static PipelineOp addResolvedAssignment(PipelineOp left,final AssignmentNode assignmentNode,final Set<IVariable<?>> doneSet,final Properties queryHints,final AST2BOpContext ctx){ final IValueExpression ve=assignmentNode.getValueExpression(); final Set<IVariable<IV>> vars=new LinkedHashSet<IVariable<IV>>(); final ComputedMaterializationRequirement req=assignmentNode.getMaterializationRequirement(); vars.addAll(req.getVarsToMaterialize()); vars.removeAll(doneSet); final int bopId=ctx.nextId(); final Var freshVar=Var.var(); final ConditionalBind b=new ConditionalBind(freshVar,assignmentNode.getValueExpression(),false); final IConstraint c=new ProjectedConstraint(b); if (vars.size() > 0) { left=addMaterializationSteps1(left,bopId,ve,vars,queryHints,ctx); if (req.getRequirement() == Requirement.ALWAYS) { doneSet.addAll(vars); } } left=applyQueryHints(new ConditionalRoutingOp(leftOrEmpty(left),new NV(BOp.Annotations.BOP_ID,bopId),new NV(ConditionalRoutingOp.Annotations.CONDITION,c)),queryHints,ctx); final Set<IVariable<IV>> iVars=new LinkedHashSet<IVariable<IV>>(); iVars.add(freshVar); left=addMockTermResolverOp(left,iVars,ChunkedMaterializationOp.Annotations.DEFAULT_MATERIALIZE_INLINE_IVS,null,assignmentNode.getQueryHints(),ctx); left=addVariableUnificationOp(left,assignmentNode.getVar(),freshVar,ctx); return left; }
Add an assignment to the query plan and resolve the IV of the bound variable (which might be bound to a mocked IV) against the dictionary. Using this method for translating assignments. This might come with a performance overhead, since a dictionary join is involved. However, using this method is always safe in the sense that the variable that is bound may be used in subsequent joins. See addAssignment for a performance optimized method that does not resolve constructed (mocked) IVs against the dictionary.
public void execute() throws Exception { DataSet data=this.dataSet; MimbuildTrek mimbuild=new MimbuildTrek(); mimbuild.setAlpha(getParams().getDouble("alpha",0.001)); mimbuild.setKnowledge((IKnowledge)getParams().get("knowledge",new Knowledge2())); if (getParams().getBoolean("includeThreeClusters",true)) { mimbuild.setMinClusterSize(3); } else { mimbuild.setMinClusterSize(4); } Clusters clusters=(Clusters)getParams().get("clusters",null); List<List<Node>> partition=ClusterUtils.clustersToPartition(clusters,data.getVariables()); List<String> latentNames=new ArrayList<>(); for (int i=0; i < clusters.getNumClusters(); i++) { latentNames.add(clusters.getClusterName(i)); } CovarianceMatrix cov=new CovarianceMatrix(data); Graph structureGraph=mimbuild.search(partition,latentNames,cov); GraphUtils.circleLayout(structureGraph,200,200,150); GraphUtils.fruchtermanReingoldLayout(structureGraph); ICovarianceMatrix latentsCov=mimbuild.getLatentsCov(); TetradLogger.getInstance().log("details","Latent covs = \n" + latentsCov); Graph fullGraph=mimbuild.getFullGraph(); GraphUtils.circleLayout(fullGraph,200,200,150); GraphUtils.fruchtermanReingoldLayout(fullGraph); setResultGraph(fullGraph); setFullGraph(fullGraph); setClusters(MimUtils.convertToClusters(structureGraph)); setClusters(ClusterUtils.partitionToClusters(mimbuild.getClustering())); setStructureGraph(structureGraph); getParams().set("latentVariableNames",new ArrayList<>(latentNames)); this.covMatrix=latentsCov; double p=mimbuild.getpValue(); TetradLogger.getInstance().log("details","\nStructure graph = " + structureGraph); TetradLogger.getInstance().log("details",getLatentClustersString(fullGraph).toString()); TetradLogger.getInstance().log("details","P = " + p); if (getParams().getBoolean("showMaxP",false)) { if (p > getParams().getDouble("maxP",1.0)) { getParams().set("maxP",p); getParams().set("maxStructureGraph",structureGraph); getParams().set("maxClusters",getClusters()); getParams().set("maxFullGraph",fullGraph); getParams().set("maxAlpha",getParams().getDouble("alpha",0.001)); } setStructureGraph((Graph)getParams().get("maxStructureGraph",null)); setFullGraph((Graph)getParams().get("maxFullGraph",null)); if (getParams().get("maxClusters",null) != null) { setClusters((Clusters)getParams().get("maxClusters",null)); } setResultGraph((Graph)getParams().get("maxFullGraph",null)); TetradLogger.getInstance().log("maxmodel","\nMAX Graph = " + getParams().get("maxStructureGraph",null)); TetradLogger.getInstance().log("maxmodel",getLatentClustersString((Graph)getParams().get("maxFullGraph",null)).toString()); TetradLogger.getInstance().log("maxmodel","MAX P = " + getParams().getDouble("maxP",1.0)); } }
Executes the algorithm, producing (at least) a result workbench. Must be implemented in the extending class.
void processEvents(){ for (; ; ) { WatchKey key; try { key=watcher.take(); } catch ( InterruptedException x) { return; } for ( WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind=event.kind(); if (kind == OVERFLOW) { continue; } WatchEvent<Path> ev=cast(event); Path name=ev.context(); Path child=((Path)key.watchable()).resolve(name); System.out.format("%s: %s\n",event.kind().name(),child); if (recursive && (kind == ENTRY_CREATE)) { try { if (Files.isDirectory(child,NOFOLLOW_LINKS)) { registerAll(child); } } catch ( IOException x) { } } } boolean valid=key.reset(); if (!valid) { count--; if (count == 0) break; } } }
Process all events for keys queued to the watcher
@NotNull public static PyFunctionBuilder copySignature(@NotNull final PyFunction source,@NotNull final String... decoratorsToCopyIfExist){ final String name=source.getName(); final PyFunctionBuilder functionBuilder=new PyFunctionBuilder((name != null) ? name : ""); for ( final PyParameter parameter : source.getParameterList().getParameters()) { final String parameterName=parameter.getName(); if (parameterName != null) { functionBuilder.parameter(parameterName); } } final PyDecoratorList decoratorList=source.getDecoratorList(); if (decoratorList != null) { for ( final PyDecorator decorator : decoratorList.getDecorators()) { final String decoratorName=decorator.getName(); if (decoratorName != null) { if (ArrayUtil.contains(decoratorName,decoratorsToCopyIfExist)) { functionBuilder.decorate(decoratorName); } } } } final String docString=source.getDocStringValue(); if (docString != null) { functionBuilder.docString(docString); } return functionBuilder; }
Creates builder copying signature and doc from another one.
private TreeNodeVisitor train(OnLineStatistics setScore,List<DataPointPair<Double>> subSet,List<Integer> features,CategoricalData[] catInfo,Random rand,Stack<List<DataPointPair<Double>>> reusableLists){ if (subSet.size() < stopSize || setScore.getVarance() <= 0.0 || Double.isNaN(setScore.getVarance())) return new NodeR(setScore.getMean()); double bestGain=Double.NEGATIVE_INFINITY; double bestThreshold=Double.NaN; int bestAttribute=-1; OnLineStatistics[] bestScores=null; List<List<DataPointPair<Double>>> bestSplit=null; Set<Integer> bestLeftSide=null; Collections.shuffle(features); final int goTo=Math.min(selectionCount,features.size()); for (int i=0; i < goTo; i++) { double gain; double threshold=Double.NaN; Set<Integer> leftSide=null; OnLineStatistics[] stats; int a=features.get(i); List<List<DataPointPair<Double>>> aSplit; if (a < catInfo.length) { final int vals=catInfo[a].getNumOfCategories(); if (binaryCategoricalSplitting || vals == 2) { stats=createStats(2); Set<Integer> catsValsInUse=new IntSet(vals * 2); for ( DataPointPair<Double> dpp : subSet) catsValsInUse.add(dpp.getDataPoint().getCategoricalValue(a)); if (catsValsInUse.size() == 1) return new NodeR(setScore.getMean()); leftSide=new IntSet(vals); int toUse=rand.nextInt(catsValsInUse.size() - 1) + 1; ListUtils.randomSample(catsValsInUse,leftSide,toUse,rand); aSplit=new ArrayList<List<DataPointPair<Double>>>(2); fillList(2,reusableLists,aSplit); for ( DataPointPair<Double> dpp : subSet) { DataPoint dp=dpp.getDataPoint(); int dest=leftSide.contains(dpp.getDataPoint().getCategoricalValue(a)) ? 0 : 1; stats[dest].add(dpp.getPair(),dp.getWeight()); aSplit.get(dest).add(dpp); } } else { stats=createStats(vals); aSplit=new ArrayList<List<DataPointPair<Double>>>(vals); fillList(vals,reusableLists,aSplit); for ( DataPointPair<Double> dpp : subSet) { DataPoint dp=dpp.getDataPoint(); stats[dp.getCategoricalValue(a)].add(dpp.getPair(),dp.getWeight()); aSplit.get(dp.getCategoricalValue(a)).add(dpp); } } } else { int numerA=a - catInfo.length; double min=Double.POSITIVE_INFINITY, max=Double.NEGATIVE_INFINITY; for ( DataPointPair<Double> dpp : subSet) { double val=dpp.getVector().get(numerA); min=Math.min(min,val); max=Math.max(max,val); } threshold=rand.nextDouble() * (max - min) + min; stats=createStats(2); aSplit=new ArrayList<List<DataPointPair<Double>>>(2); fillList(2,reusableLists,aSplit); for ( DataPointPair<Double> dpp : subSet) { double val=dpp.getVector().get(numerA); int toAddTo=val <= threshold ? 0 : 1; aSplit.get(toAddTo).add(dpp); stats[toAddTo].add(dpp.getPair(),dpp.getDataPoint().getWeight()); } } gain=1; double varNorm=setScore.getVarance(); double varSum=setScore.getSumOfWeights(); for ( OnLineStatistics stat : stats) gain-=stat.getSumOfWeights() / varSum * (stat.getVarance() / varNorm); if (gain > bestGain) { bestGain=gain; bestAttribute=a; bestThreshold=threshold; bestScores=stats; if (bestSplit != null) fillStack(reusableLists,bestSplit); bestSplit=aSplit; bestLeftSide=leftSide; } else fillStack(reusableLists,aSplit); } fillStack(reusableLists,Arrays.asList(subSet)); NodeBase toReturn; if (bestAttribute >= 0) { if (bestAttribute < catInfo.length) if (bestSplit.size() == 2) toReturn=new NodeRCat(bestAttribute,bestLeftSide,setScore.getMean()); else { toReturn=new NodeRCat(goTo,bestSplit.size(),setScore.getMean()); features.remove(new Integer(bestAttribute)); } else toReturn=new NodeRNum(bestAttribute - catInfo.length,bestThreshold,setScore.getMean()); for (int i=0; i < toReturn.children.length; i++) { toReturn.children[i]=train(bestScores[i],bestSplit.get(i),features,catInfo,rand,reusableLists); } return toReturn; } return new NodeR(setScore.getMean()); }
Creates a new tree top down
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); }
Util method to write an attribute with the ns prefix
public void pI(){ indentIn(); }
Indent in.
@Override public void closeTab(Tab tab){ if (tab == mTabControl.getCurrentTab()) { closeCurrentTab(); } else { removeTab(tab); } }
Close the tab, remove its associated title bar, and adjust mTabControl's current tab to a valid value.
static void adjustIndicesForSupplementaryChars(StringBuilder content,FormattedTweetText formattedTweetText){ final List<Integer> highSurrogateIndices=new ArrayList<>(); final int len=content.length() - 1; for (int i=0; i < len; ++i) { if (Character.isHighSurrogate(content.charAt(i)) && Character.isLowSurrogate(content.charAt(i + 1))) { highSurrogateIndices.add(i); } } adjustEntitiesWithOffsets(formattedTweetText.urlEntities,highSurrogateIndices); adjustEntitiesWithOffsets(formattedTweetText.mediaEntities,highSurrogateIndices); }
Adjusts entity indices for supplementary characters (Emoji being the most common example) in UTF-8 (ones outside of U+0000 to U+FFFF range) are represented as a pair of char values, the first from the high-surrogates range, and the second from the low-surrogates range.
public String decompileStateMachine(Vertex state,Network network){ long start=System.currentTimeMillis(); StringWriter writer=new StringWriter(); printStateMachine(state,writer,network,start,TIMEOUT); writer.flush(); network.getBot().log(state,"Decompile time",Level.INFO,System.currentTimeMillis() - start); return writer.toString(); }
Print the Self code for the state machine.
protected MetaStore createMetaStore(){ storage=Storage.builder().withDirectory(new File(String.format("target/test-logs/%s",testId))).build(); return new MetaStore("test",storage,new Serializer().resolve(new ProtocolSerialization(),new ServerSerialization(),new StorageSerialization()).register(TestMember.class)); }
Returns a new metastore.
public boolean isBlockWidthRelative(int i){ return (masks[i] & BLOCK_WIDTH_RELATIVE_MASK) != 0; }
Tells whether the given property value is relative to the width of the containing block.
protected I18nSet(){ super(); }
Dear JPA...
void establishConnection(final Publication publication){ final int sessionId=publication.sessionId(); debug("Establishing connection for channel => {}, stream id => {}",publication.channel(),publication.sessionId()); UnsafeBuffer buffer=buffers.get(); buffer.wrap(new byte[BitUtil.SIZE_OF_INT]); buffer.putShort(0,(short)0); buffer.putShort(BitUtil.SIZE_OF_SHORT,(short)MessageType.ESTABLISH_CONNECTION_REQUEST.getEncodedType()); long offer=-1; final long start=System.nanoTime(); for (; ; ) { final long current=System.nanoTime(); if ((current - start) > TimeUnit.MILLISECONDS.toNanos(Constants.CLIENT_ESTABLISH_CONNECT_TIMEOUT_MS)) { throw new RuntimeException("Timed out waiting to establish connection for session id => " + sessionId); } if (offer < 0) { if (publication.isClosed()) { throw new RuntimeException("A closed publication was found when trying to establish for session id => " + sessionId); } offer=publication.offer(buffer); } else { break; } } }
Establishes a connection between the client and server. Waits for 30 seconds before throwing a exception.
private static void addPersonAttributes(Element formDataNode,Element modelNode,Element xformsNode){ List<PersonAttributeType> attributeTypes=Context.getPersonService().getPersonAttributeTypes(PERSON_TYPE.PERSON,null); for ( PersonAttributeType attribute : attributeTypes) addPatientAttributeNode(attribute,formDataNode,modelNode,xformsNode); }
Adds person attributes to the patient creator xform.
public WifiRecord(String bssid,String ssid,String capabilities,int frequency,int level,long timestamp,PositionRecord request,PositionRecord last,CatalogStatus catalogStatus){ this(bssid,ssid,capabilities,frequency,level,timestamp,request,last,RadioBeacon.SESSION_NOT_TRACKING,catalogStatus); }
Initialises Wifi Record without setting session id
private boolean contains(Body body,Vector2 point){ Transform transform=body.getTransform(); int fSize=body.getFixtureCount(); for (int j=fSize - 1; j >= 0; j--) { BodyFixture bodyFixture=body.getFixture(j); Convex convex=bodyFixture.getShape(); if (contains(convex,transform,point)) { return true; } } return false; }
Returns true if the given body contains the given point.
public void downloadExecuteLogic(ActionMapping mappings,ActionForm form,HttpServletRequest request,HttpServletResponse response){ DocumentoVitalPO documentoVital=(DocumentoVitalPO)getFromTemporalSession(request,DocumentosVitalesConstants.DOCUMENTO_VITAL_KEY); if (documentoVital != null) { try { download(response,documentoVital.getNombreCompletoFichero(),documentoVital.getContenido()); } catch ( Exception e) { obtenerErrores(request,true).add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.GLOBAL_ARCHIGEST_EXCEPTION,e.toString())); goLastClientExecuteLogic(mappings,form,request,response); } } else { obtenerErrores(request,true).add(ActionErrors.GLOBAL_MESSAGE,new ActionError(DocumentosVitalesConstants.ERRORS_DOCVITALES_DOC_NO_ENCONTRADO)); goLastClientExecuteLogic(mappings,form,request,response); } }
Descarga el documento vital.
public static String[] values(){ return ALL_VALUES; }
Returns an array of all values defined in this class.
@Override final public FunctionNode visit(ASTFunctionCall node,Object data) throws VisitorException { final ConstantNode uriNode=(ConstantNode)node.jjtGetChild(0).jjtAccept(this,null); final BigdataURI functionURI=(BigdataURI)uriNode.getValue(); final int nargs=node.jjtGetNumChildren() - 1; final ValueExpressionNode[] args=new ValueExpressionNode[nargs]; for (int i=0; i < nargs; i++) { final Node argNode=node.jjtGetChild(i + 1); args[i]=(ValueExpressionNode)argNode.jjtAccept(this,null); } return new FunctionNode(functionURI,null,args); }
ASTFunctionCall (IRIRef, ArgList).
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public static byte[] buildAacAudioSpecificConfig(int audioObjectType,int sampleRateIndex,int channelConfig){ byte[] audioSpecificConfig=new byte[2]; audioSpecificConfig[0]=(byte)((audioObjectType << 3) & 0xF8 | (sampleRateIndex >> 1) & 0x07); audioSpecificConfig[1]=(byte)((sampleRateIndex << 7) & 0x80 | (channelConfig << 3) & 0x78); return audioSpecificConfig; }
Builds a simple AudioSpecificConfig, as defined in ISO 14496-3 1.6.2.1
@Override public void readFrom(ChannelBuffer data,int length){ dataType=data.readInt(); }
Read the vendor data from the ChannelBuffer
protected void updateEnableState(){ if (fLabel != null) { fLabel.setEnabled(fEnabled); } }
Called when the enable state changed. To be extended by dialog field implementors.
public Sheep(final Player owner){ super(); super.setOwner(owner); setRPClass("sheep"); put("type","sheep"); initHP(HP); setUp(); hunger=0; timingAdjust=Rand.rand(10); if (owner != null) { owner.getZone().add(this); owner.setSheep(this); } update(); updateSoundList(); logger.debug("Created Sheep: " + this); }
Creates a new Sheep that is owned by a player.
private static boolean equal(Number[][] array1,Number[][] array2){ if (array1 == null) { return (array2 == null); } if (array2 == null) { return false; } if (array1.length != array2.length) { return false; } for (int i=0; i < array1.length; i++) { if (!Arrays.equals(array1[i],array2[i])) { return false; } } return true; }
Tests two double[][] arrays for equality.
public void removeListener(final IModuleListener listener){ m_listeners.removeListener(listener); }
Removes a listener object from the module.
public org.fife.ui.rsyntaxtextarea.Token yylex() throws java.io.IOException { int zzInput; int zzAction; int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL=zzEndRead; char[] zzBufferL=zzBuffer; char[] zzCMapL=ZZ_CMAP; int[] zzTransL=ZZ_TRANS; int[] zzRowMapL=ZZ_ROWMAP; int[] zzAttrL=ZZ_ATTRIBUTE; while (true) { zzMarkedPosL=zzMarkedPos; zzAction=-1; zzCurrentPosL=zzCurrentPos=zzStartRead=zzMarkedPosL; zzState=zzLexicalState; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput=zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput=YYEOF; break zzForAction; } else { zzCurrentPos=zzCurrentPosL; zzMarkedPos=zzMarkedPosL; boolean eof=zzRefill(); zzCurrentPosL=zzCurrentPos; zzMarkedPosL=zzMarkedPos; zzBufferL=zzBuffer; zzEndReadL=zzEndRead; if (eof) { zzInput=YYEOF; break zzForAction; } else { zzInput=zzBufferL[zzCurrentPosL++]; } } int zzNext=zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]]; if (zzNext == -1) break zzForAction; zzState=zzNext; int zzAttributes=zzAttrL[zzState]; if ((zzAttributes & 1) == 1) { zzAction=zzState; zzMarkedPosL=zzCurrentPosL; if ((zzAttributes & 8) == 8) break zzForAction; } } } zzMarkedPos=zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 3: { addToken(Token.WHITESPACE,false); } case 5: break; case 2: { addNullToken(); return firstToken; } case 6: break; case 4: { addToken(Token.IDENTIFIER,true); } case 7: break; case 1: { addToken(Token.IDENTIFIER,false); } case 8: break; default : if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF=true; switch (zzLexicalState) { case YYINITIAL: { addNullToken(); return firstToken; } case 22: break; default : return null; } } else { zzScanError(ZZ_NO_MATCH); } } } }
Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error occurs.
public Object runSafely(Catbert.FastStack stack) throws Exception { if (stack.getUIMgr() == null) Sage.remove(getString(stack)); else stack.getUIMgr().remove(getString(stack)); return null; }
Removes the specified property from the property map
public AttributeTableModel(Instances instances){ setInstances(instances); }
Creates the tablemodel with the given set of instances.
private StoragePlatform createStoragePlatformFromEntity(StoragePlatformEntity storagePlatformEntity){ StoragePlatform storagePlatform=new StoragePlatform(); storagePlatform.setName(storagePlatformEntity.getName()); return storagePlatform; }
Creates a storage platform object from it's entity object.
@JsonCreator public DefaultInitRequest(@JsonProperty("workingDir") String workingDir,@JsonProperty("bare") boolean bare,@JsonProperty("initCommit") boolean initCommit){ this.workingDir=workingDir; this.bare=bare; this.initCommit=initCommit; }
Creates a default init request object
private VisorResolveHostNameJob(Void arg,boolean debug){ super(arg,debug); }
Create job.
public static Address fromPublicKey(final PublicKey publicKey){ return fromPublicKey(NetworkInfos.getDefault().getVersion(),publicKey); }
Creates an Address from a public key.
void paintGlassImpl(Graphics g){ if (parent != null) { parent.paintGlassImpl(g); } paintTensile(g); }
This method can be overriden by a component to draw on top of itself or its children after the component or the children finished drawing in a similar way to the glass pane but more refined per component
public TerritoryAttachment(final String name,final Attachable attachable,final GameData gameData){ super(name,attachable,gameData); }
Creates new TerritoryAttachment
public void insertBefore(final AbstractInsnNode location,final AbstractInsnNode insn){ ++size; AbstractInsnNode prev=location.prev; if (prev == null) { first=insn; } else { prev.next=insn; } location.prev=insn; insn.next=location; insn.prev=prev; cache=null; insn.index=0; }
Inserts the given instruction before the specified instruction.
public Cursor query(SQLiteDatabase db,String[] projectionIn,String selection,String[] selectionArgs,String groupBy,String having,String sortOrder,String limit){ return query(db,projectionIn,selection,selectionArgs,groupBy,having,sortOrder,limit,null); }
Perform a query by combining all current settings and the information passed into this method.
public InputOutput<T> seekFloor(BytesRef target) throws IOException { this.target=target; targetLength=target.length; super.doSeekFloor(); return setResult(); }
Seeks to biggest term that's &lt;= target.
public boolean handleMessage(Message m,Object o){ if (!super.handleMessage(m,o)) { if (m.getType().equals(MasterAgent.M_EVALUATE_POP_CHUNK)) { output.message("A chunk arrived from " + m.getSender().name); population.subpops[0].individuals=(Individual[])o; evaluator.evaluatePopulation(this); statistics.postEvaluationStatistics(this); } else return false; } return true; }
Handles incoming messages.
public static Bitmap scaleBitmap(Context ctx,Bitmap source,int newHeight){ int w=(int)(newHeight * source.getWidth() / ((double)source.getHeight())); Bitmap photo=Bitmap.createScaledBitmap(source,w,newHeight,true); return photo; }
Scales the image independently of the screen density of the device. Maintains image aspect ratio. When dealing with the bitmaps of bigger size, this method must be called from a non-UI thread.
private static byte[] encode3to4(byte[] source,int srcOffset,int numSigBytes,byte[] destination,int destOffset,int options){ byte[] ALPHABET=getAlphabet(options); int inBuff=(numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3]=ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3]=EQUALS_SIGN; return destination; case 1: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=EQUALS_SIGN; destination[destOffset + 3]=EQUALS_SIGN; return destination; default : return destination; } }
<p>Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64 bytes to <var>destination</var>. The source and destination arrays can be manipulated anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 3 for the <var>source</var> array or <var>destOffset</var> + 4 for the <var>destination</var> array. The actual number of significant bytes in your array is given by <var>numSigBytes</var>.</p> <p>This is the lowest level of the encoding methods with all possible parameters.</p>
public static Rectangle fromPolygon(Polygon[] polygons){ double minLat=Double.POSITIVE_INFINITY; double maxLat=Double.NEGATIVE_INFINITY; double minLon=Double.POSITIVE_INFINITY; double maxLon=Double.NEGATIVE_INFINITY; for (int i=0; i < polygons.length; i++) { minLat=Math.min(polygons[i].minLat,minLat); maxLat=Math.max(polygons[i].maxLat,maxLat); minLon=Math.min(polygons[i].minLon,minLon); maxLon=Math.max(polygons[i].maxLon,maxLon); } return new Rectangle(minLat,maxLat,minLon,maxLon); }
Returns the bounding box over an array of polygons
public INode remove(){ return list.removeFirst(); }
Remove board state with lowest evaluated score.
protected void onContextInitialized0(final IgniteSpiContext spiCtx) throws IgniteSpiException { }
Method to be called in the end of onContextInitialized method.
private static boolean looksLikeAnonymousClassDef(IDocument document,int position,String partitioning){ int previousCommaParenEqual=scanBackward(document,position - 1,partitioning,-1,new char[]{',','(','='}); if (previousCommaParenEqual == -1 || position < previousCommaParenEqual + 5) return false; if (isNewMatch(document,previousCommaParenEqual + 1,position - previousCommaParenEqual - 2,partitioning)) return true; return false; }
Checks whether the content of <code>document</code> at <code>position</code> looks like an anonymous class definition. <code>position</code> must be to the left of the opening parenthesis of the definition's parameter list.
public final static byte[] encodeToByte(byte[] sArr,boolean lineSep){ int sLen=sArr != null ? sArr.length : 0; if (sLen == 0) return new byte[0]; int eLen=(sLen / 3) * 3; int cCnt=((sLen - 1) / 3 + 1) << 2; int dLen=cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); byte[] dArr=new byte[dLen]; for (int s=0, d=0, cc=0; s < eLen; ) { int i=(sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); dArr[d++]=(byte)CA[(i >>> 18) & 0x3f]; dArr[d++]=(byte)CA[(i >>> 12) & 0x3f]; dArr[d++]=(byte)CA[(i >>> 6) & 0x3f]; dArr[d++]=(byte)CA[i & 0x3f]; if (lineSep && ++cc == 19 && d < dLen - 2) { dArr[d++]='\r'; dArr[d++]='\n'; cc=0; } } int left=sLen - eLen; if (left > 0) { int i=((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); dArr[dLen - 4]=(byte)CA[i >> 12]; dArr[dLen - 3]=(byte)CA[(i >>> 6) & 0x3f]; dArr[dLen - 2]=left == 2 ? (byte)CA[i & 0x3f] : (byte)'='; dArr[dLen - 1]='='; } return dArr; }
Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
public SuperBit(final int d,final int n,final int l,final long seed){ this(d,n,l,new Random(seed)); }
Initialize SuperBit algorithm. Super-Bit depth n must be [1 .. d] and number of Super-Bit l in [1 .. The resulting code length k = n * l The K vectors are orthogonalized in L batches of N vectors
public void write(byte[] bytes,int off,int len) throws IOException { buf.put(bytes,off,len); }
write an array of bytes to a specified range of backed buffer
public static Index index(String table,String name){ return new Index(table,name); }
Returns a new index creation statement using the session's keyspace.
public NullPointerException(){ }
Constructs a NullPointerException with no detail message.
@Override public void write(TextWriterStream out,String label,Object object){ }
Ignore this object.
@Override public final void cancel(){ if (isValid) { isValid=false; ((AbstractSelector)selector()).cancel(this); } }
Cancels this key. <p> A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public void Disambiguate(){ for (int vtype=0; vtype <= num_vtypes; vtype++) for (int i=0; i < symtab.size(); i++) { SymTabEntry se=(SymTabEntry)symtab.elementAt(i); if (se.type == vtype) { se.useThis=typePrefix[vtype] + se.id; int suffixLength=0; while (vtype > 0 && Ambiguous(se.useThis)) { suffixLength=suffixLength + 1; if (suffixLength == 1) se.useThis=se.useThis + "_"; else if (suffixLength > se.context.length() + 1) se.useThis=se.useThis + vtype; else se.useThis=se.useThis + se.context.charAt(suffixLength - 2); } if (!se.id.equals(se.useThis)) disambiguateReport.addElement("\\* " + vtypeName[se.type] + " "+ se.id+ ((se.context.length() == 0) ? "" : (" of " + se.cType + " "+ se.context))+ " at line "+ se.line+ " col "+ se.col+ " changed to "+ se.useThis); } } }
Disambiguating names. First, names are prepended with a type specific string, defined in the array typePrefix. Then, the names are considered in increasing type order. The first type in this order are left unchanged. Then, each other order has a suffix appended to it until it is unique from all the current symbol names (both renamed and not yet renamed). The suffix is a prefix of "_context" where "context" is the context in which the name is defined (which is the empty string for the global context). If it is still not unique after all of the context is appended, then the decimal representation of the name type is added repeatedly until it is unambiguous.
public void addItem(T item,int position){ contents.add(position,item); notifyItemInserted(position); }
Adds an item into the contents
public static Match fromString(String match,OFVersion ofVersion) throws IllegalArgumentException { boolean ver10=false; if (match.equals("") || match.equalsIgnoreCase("any") || match.equalsIgnoreCase("all")|| match.equals("[]")) { match="Match[]"; } String[] tokens=match.split("[\\[,\\]]"); int initArg=0; if (tokens[0].equals("Match")) { initArg=1; } int i; String[] tmp; ArrayDeque<String[]> llValues=new ArrayDeque<String[]>(); for (i=initArg; i < tokens.length; i++) { tmp=tokens[i].split("="); if (tmp.length != 2) { throw new IllegalArgumentException("Token " + tokens[i] + " does not have form 'key=value' parsing "+ match); } tmp[0]=tmp[0].toLowerCase(); llValues.add(tmp); } Match.Builder mb=OFFactories.getFactory(ofVersion).buildMatch(); if (ofVersion.equals(OFVersion.OF_10)) { ver10=true; } while (!llValues.isEmpty()) { IpProtocol ipProto=null; String[] key_value=llValues.pollFirst(); String[] dataMask=key_value[1].split("/"); if (dataMask.length > 2) { throw new IllegalArgumentException("[Data, Mask] " + dataMask + " does not have form 'data/mask' or 'data'"+ key_value[1]); } else if (dataMask.length == 1) { log.debug("No mask detected in Match string: {}",key_value[1]); } else if (dataMask.length == 2) { log.debug("Detected mask in Match string: {}",key_value[1]); } switch (key_value[0]) { case STR_IN_PORT: if (dataMask.length == 1) { mb.setExact(MatchField.IN_PORT,OFPort.ofShort(dataMask[0].contains("0x") ? U16.of(Integer.valueOf(dataMask[0].replaceFirst("0x",""),16)).getRaw() : U16.of(Integer.valueOf(dataMask[0])).getRaw())); } else { mb.setMasked(MatchField.IN_PORT,OFPort.ofShort(dataMask[0].contains("0x") ? U16.of(Integer.valueOf(dataMask[0].replaceFirst("0x",""),16)).getRaw() : U16.of(Integer.valueOf(dataMask[0])).getRaw()),OFPort.ofShort(dataMask[1].contains("0x") ? U16.of(Integer.valueOf(dataMask[1].replaceFirst("0x",""),16)).getRaw() : U16.of(Integer.valueOf(dataMask[1])).getRaw())); } break; case STR_DL_DST: if (dataMask.length == 1) { mb.setExact(MatchField.ETH_DST,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.ETH_DST,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_DL_SRC: if (dataMask.length == 1) { mb.setExact(MatchField.ETH_SRC,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.ETH_SRC,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_DL_TYPE: if (dataMask.length == 1) { mb.setExact(MatchField.ETH_TYPE,EthType.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ETH_TYPE,EthType.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),EthType.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } break; case STR_DL_VLAN: if (dataMask.length == 1) { mb.setExact(MatchField.VLAN_VID,OFVlanVidMatch.ofVlan(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.VLAN_VID,OFVlanVidMatchWithMask.of(OFVlanVidMatch.ofVlan(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),OFVlanVidMatch.ofVlan(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1])))); } break; case STR_DL_VLAN_PCP: if (dataMask.length == 1) { mb.setExact(MatchField.VLAN_PCP,VlanPcp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0])))); } else { mb.setMasked(MatchField.VLAN_PCP,VlanPcp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0]))),VlanPcp.of(dataMask[1].contains("0x") ? U8.t(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[1])))); } break; case STR_NW_DST: mb.setMasked(MatchField.IPV4_DST,IPv4AddressWithMask.of(key_value[1])); break; case STR_NW_SRC: mb.setMasked(MatchField.IPV4_SRC,IPv4AddressWithMask.of(key_value[1])); break; case STR_IPV6_DST: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } mb.setMasked(MatchField.IPV6_DST,IPv6AddressWithMask.of(key_value[1])); break; case STR_IPV6_SRC: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } mb.setMasked(MatchField.IPV6_SRC,IPv6AddressWithMask.of(key_value[1])); break; case STR_IPV6_FLOW_LABEL: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } if (dataMask.length == 1) { mb.setExact(MatchField.IPV6_FLABEL,IPv6FlowLabel.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.IPV6_FLABEL,IPv6FlowLabel.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),IPv6FlowLabel.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } break; case STR_NW_PROTO: if (dataMask.length == 1) { mb.setExact(MatchField.IP_PROTO,IpProtocol.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.IP_PROTO,IpProtocol.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0])),IpProtocol.of(dataMask[1].contains("0x") ? Short.valueOf(dataMask[1].replaceFirst("0x",""),16) : Short.valueOf(dataMask[1]))); } break; case STR_NW_TOS: if (dataMask.length == 1) { mb.setExact(MatchField.IP_ECN,IpEcn.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0])))); mb.setExact(MatchField.IP_DSCP,IpDscp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0])))); } else { mb.setMasked(MatchField.IP_ECN,IpEcn.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0]))),IpEcn.of(dataMask[1].contains("0x") ? U8.t(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[1])))); mb.setMasked(MatchField.IP_DSCP,IpDscp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0]))),IpDscp.of(dataMask[1].contains("0x") ? U8.t(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[1])))); } break; case STR_NW_ECN: if (dataMask.length == 1) { mb.setExact(MatchField.IP_ECN,IpEcn.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0])))); } else { mb.setMasked(MatchField.IP_ECN,IpEcn.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0]))),IpEcn.of(dataMask[1].contains("0x") ? U8.t(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[1])))); } break; case STR_NW_DSCP: if (dataMask.length == 1) { mb.setExact(MatchField.IP_DSCP,IpDscp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0])))); } else { mb.setMasked(MatchField.IP_DSCP,IpDscp.of(dataMask[0].contains("0x") ? U8.t(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[0]))),IpDscp.of(dataMask[1].contains("0x") ? U8.t(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.t(Short.valueOf(dataMask[1])))); } break; case STR_SCTP_DST: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.SCTP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.SCTP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_SCTP_SRC: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.SCTP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.SCTP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_UDP_DST: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.UDP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.UDP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_UDP_SRC: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.UDP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.UDP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_TCP_DST: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.TCP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.TCP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_TCP_SRC: if (mb.get(MatchField.IP_PROTO) == null) { llValues.add(key_value); } else { if (dataMask.length == 1) { mb.setExact(MatchField.TCP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.TCP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_TP_DST: if ((ipProto=mb.get(MatchField.IP_PROTO)) == null) { llValues.add(key_value); } else if (ipProto == IpProtocol.TCP) { if (dataMask.length == 1) { mb.setExact(MatchField.TCP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.TCP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } else if (ipProto == IpProtocol.UDP) { if (dataMask.length == 1) { mb.setExact(MatchField.UDP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.UDP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } else if (ipProto == IpProtocol.SCTP) { if (dataMask.length == 1) { mb.setExact(MatchField.SCTP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.SCTP_DST,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_TP_SRC: if ((ipProto=mb.get(MatchField.IP_PROTO)) == null) { llValues.add(key_value); } else if (ipProto == IpProtocol.TCP) { if (dataMask.length == 1) { mb.setExact(MatchField.TCP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.TCP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } else if (ipProto == IpProtocol.UDP) { if (dataMask.length == 1) { mb.setExact(MatchField.UDP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.UDP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } else if (ipProto == IpProtocol.SCTP) { if (dataMask.length == 1) { mb.setExact(MatchField.SCTP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.SCTP_SRC,TransportPort.of(dataMask[0].contains("0x") ? Integer.valueOf(dataMask[0].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[0])),TransportPort.of(dataMask[1].contains("0x") ? Integer.valueOf(dataMask[1].replaceFirst("0x",""),16) : Integer.valueOf(dataMask[1]))); } } break; case STR_ICMP_TYPE: if (dataMask.length == 1) { mb.setExact(MatchField.ICMPV4_TYPE,ICMPv4Type.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ICMPV4_TYPE,ICMPv4Type.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0])),ICMPv4Type.of(dataMask[1].contains("0x") ? Short.valueOf(dataMask[1].replaceFirst("0x",""),16) : Short.valueOf(dataMask[1]))); } break; case STR_ICMP_CODE: if (dataMask.length == 1) { mb.setExact(MatchField.ICMPV4_CODE,ICMPv4Code.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ICMPV4_CODE,ICMPv4Code.of(dataMask[0].contains("0x") ? Short.valueOf(dataMask[0].replaceFirst("0x",""),16) : Short.valueOf(dataMask[0])),ICMPv4Code.of(dataMask[1].contains("0x") ? Short.valueOf(dataMask[1].replaceFirst("0x",""),16) : Short.valueOf(dataMask[1]))); } break; case STR_ICMPV6_TYPE: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } if (dataMask.length == 1) { mb.setExact(MatchField.ICMPV6_TYPE,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ICMPV6_TYPE,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0])),dataMask[1].contains("0x") ? U8.of(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[1]))); } break; case STR_ICMPV6_CODE: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } if (dataMask.length == 1) { mb.setExact(MatchField.ICMPV6_CODE,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ICMPV6_CODE,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0])),dataMask[1].contains("0x") ? U8.of(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[1]))); } break; case STR_IPV6_ND_SSL: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } if (dataMask.length == 1) { mb.setExact(MatchField.IPV6_ND_SLL,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.IPV6_ND_SLL,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_IPV6_ND_TTL: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } if (dataMask.length == 1) { mb.setExact(MatchField.IPV6_ND_TLL,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.IPV6_ND_TLL,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_IPV6_ND_TARGET: if (ver10 == true) { throw new IllegalArgumentException("OF Version incompatible"); } mb.setMasked(MatchField.IPV6_ND_TARGET,IPv6AddressWithMask.of(key_value[1])); break; case STR_ARP_OPCODE: if (dataMask.length == 1) { mb.setExact(MatchField.ARP_OP,dataMask[0].contains("0x") ? ArpOpcode.of(Integer.valueOf(dataMask[0].replaceFirst("0x",""),16)) : ArpOpcode.of(Integer.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.ARP_OP,dataMask[0].contains("0x") ? ArpOpcode.of(Integer.valueOf(dataMask[0].replaceFirst("0x",""),16)) : ArpOpcode.of(Integer.valueOf(dataMask[0])),dataMask[1].contains("0x") ? ArpOpcode.of(Integer.valueOf(dataMask[1].replaceFirst("0x",""),16)) : ArpOpcode.of(Integer.valueOf(dataMask[1]))); } break; case STR_ARP_SHA: if (dataMask.length == 1) { mb.setExact(MatchField.ARP_SHA,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.ARP_SHA,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_ARP_DHA: if (dataMask.length == 1) { mb.setExact(MatchField.ARP_THA,MacAddress.of(dataMask[0])); } else { mb.setMasked(MatchField.ARP_THA,MacAddress.of(dataMask[0]),MacAddress.of(dataMask[1])); } break; case STR_ARP_SPA: mb.setMasked(MatchField.ARP_SPA,IPv4AddressWithMask.of(key_value[1])); break; case STR_ARP_DPA: mb.setMasked(MatchField.ARP_TPA,IPv4AddressWithMask.of(key_value[1])); break; case STR_MPLS_LABEL: if (dataMask.length == 1) { mb.setExact(MatchField.MPLS_LABEL,dataMask[0].contains("0x") ? U32.of(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U32.of(Long.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.MPLS_LABEL,dataMask[0].contains("0x") ? U32.of(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U32.of(Long.valueOf(dataMask[0])),dataMask[1].contains("0x") ? U32.of(Long.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U32.of(Long.valueOf(dataMask[1]))); } break; case STR_MPLS_TC: if (dataMask.length == 1) { mb.setExact(MatchField.MPLS_TC,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.MPLS_TC,dataMask[0].contains("0x") ? U8.of(Short.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[0])),dataMask[1].contains("0x") ? U8.of(Short.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U8.of(Short.valueOf(dataMask[1]))); } break; case STR_MPLS_BOS: mb.setExact(MatchField.MPLS_BOS,key_value[1].equalsIgnoreCase("true") ? OFBooleanValue.TRUE : OFBooleanValue.FALSE); break; case STR_METADATA: if (dataMask.length == 1) { mb.setExact(MatchField.METADATA,dataMask[0].contains("0x") ? OFMetadata.ofRaw(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : OFMetadata.ofRaw(Long.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.METADATA,dataMask[0].contains("0x") ? OFMetadata.ofRaw(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : OFMetadata.ofRaw(Long.valueOf(dataMask[0])),dataMask[1].contains("0x") ? OFMetadata.ofRaw(Long.valueOf(dataMask[1].replaceFirst("0x",""),16)) : OFMetadata.ofRaw(Long.valueOf(dataMask[1]))); } break; case STR_TUNNEL_ID: if (dataMask.length == 1) { mb.setExact(MatchField.TUNNEL_ID,dataMask[0].contains("0x") ? U64.of(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U64.of(Long.valueOf(dataMask[0]))); } else { mb.setMasked(MatchField.TUNNEL_ID,dataMask[0].contains("0x") ? U64.of(Long.valueOf(dataMask[0].replaceFirst("0x",""),16)) : U64.of(Long.valueOf(dataMask[0])),dataMask[1].contains("0x") ? U64.of(Long.valueOf(dataMask[1].replaceFirst("0x",""),16)) : U64.of(Long.valueOf(dataMask[1]))); } break; case STR_PBB_ISID: break; default : throw new IllegalArgumentException("unknown token " + key_value + " parsing "+ match); } } return mb.build(); }
Based on the method from OFMatch in openflowj 1.0. Set this Match's parameters based on a comma-separated key=value pair dpctl-style string, e.g., from the output of OFMatch.toString(). The exact syntax for each key is defined by the string constants at the top of MatchUtils.java. <br> <p> Supported keys/values include <br> <p> <TABLE border=1> <TR> <TD>KEY(s) <TD>VALUE </TR> <TR> <TD>"in_port" <TD>integer </TR> <TR> <TD>"eth_src", "eth_dst" <TD>hex-string </TR> <TR> <TD>"eth_type", "eth_vlan_vid", "eth_vlan_pcp" <TD>integer </TR> <TR> <TD>"ipv4_src", "ipv4_dst" <TD>CIDR-style netmask </TR> <TR> <TD>"tp_src","tp_dst", "tcp_src", "tcp_dst", "udp_src", "udp_dst", etc. <TD>integer (max 64k) </TR> </TABLE> <p> The CIDR-style netmasks assume 32 netmask if none given, so: "128.8.128.118/32" is the same as "128.8.128.118"
public void addDatapoints(Map<Long,String> datapoints){ if (datapoints != null) { _datapoints.putAll(datapoints); } }
Adds the current set of data points to the current set.
public static double uniform(double min,double max){ double x=min + (max - min) * raw(); return x; }
Generate a random number from a uniform random variable.
public boolean isPublic(){ return (Modifier.isPublic(modifiers())); }
Convenience routine
public static double noise(double x,double y,double z){ double n0=0, n1=0, n2=0, n3=0; double s=(x + y + z) * F3; int i=fastfloor(x + s); int j=fastfloor(y + s); int k=fastfloor(z + s); double t=(i + j + k) * G3; double x0=x - (i - t); double y0=y - (j - t); double z0=z - (k - t); int i1, j1, k1; int i2, j2, k2; if (x0 >= y0) { if (y0 >= z0) { i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; } else if (x0 >= z0) { i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; } else { i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; } } else { if (y0 < z0) { i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; } else if (x0 < z0) { i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; } else { i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; } } double x1=x0 - i1 + G3; double y1=y0 - j1 + G3; double z1=z0 - k1 + G3; double x2=x0 - i2 + F3; double y2=y0 - j2 + F3; double z2=z0 - k2 + F3; double x3=x0 - 0.5; double y3=y0 - 0.5; double z3=z0 - 0.5; int ii=i & 0xff; int jj=j & 0xff; int kk=k & 0xff; double t0=0.6 - x0 * x0 - y0 * y0 - z0 * z0; if (t0 > 0) { t0*=t0; int gi0=perm[ii + perm[jj + perm[kk]]] % 12; n0=t0 * t0 * dot(grad3[gi0],x0,y0,z0); } double t1=0.6 - x1 * x1 - y1 * y1 - z1 * z1; if (t1 > 0) { t1*=t1; int gi1=perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] % 12; n1=t1 * t1 * dot(grad3[gi1],x1,y1,z1); } double t2=0.6 - x2 * x2 - y2 * y2 - z2 * z2; if (t2 > 0) { t2*=t2; int gi2=perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] % 12; n2=t2 * t2 * dot(grad3[gi2],x2,y2,z2); } double t3=0.6 - x3 * x3 - y3 * y3 - z3 * z3; if (t3 > 0) { t3*=t3; int gi3=perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] % 12; n3=t3 * t3 * dot(grad3[gi3],x3,y3,z3); } return 32.0 * (n0 + n1 + n2+ n3); }
Computes 3D Simplex Noise.
@SuppressWarnings("UnusedParameters") public final float[] findText(int x1,int y1,int x2,int y2,final String[] terms,final int searchType) throws PdfException { if (terms == null) { return new float[]{}; } final Vector_Float resultCoords=new Vector_Float(0); final Vector_String resultTeasers=new Vector_String(0); final int[] v=validateCoordinates(x1,y1,x2,y2); x1=v[0]; y1=v[1]; x2=v[2]; y2=v[3]; copyToArraysPartial(x1,y2,x2,y1); cleanupShadowsAndDrownedObjects(false); final int[] items=getsortedUnusedFragments(true,false); final int[] unsorted=getWritingModeCounts(items); final int[] writingModes=getWritingModeOrder(unsorted); for (int u=0; u != writingModes.length; u++) { final int mode=writingModes[u]; if (unsorted[mode] != 0) { searchWritingMode(items,mode,searchType,terms,resultCoords,resultTeasers); } } return resultCoords.get(); }
Search a particular area with in pdf page currently loaded
public String makeRelative(RepositoryLocation relativeToFolder){ if (!this.repositoryName.equals(relativeToFolder.repositoryName)) { return getAbsoluteLocation(); } int min=Math.min(this.path.length,relativeToFolder.path.length); int i=0; while (i < min && this.path[i].equals(relativeToFolder.path[i])) { i++; } StringBuilder result=new StringBuilder(); for (int j=i; j < relativeToFolder.path.length; j++) { result.append(".."); result.append(RepositoryLocation.SEPARATOR); } for (int j=i; j < this.path.length; j++) { result.append(this.path[j]); if (j < this.path.length - 1) { result.append(RepositoryLocation.SEPARATOR); } } return result.toString(); }
Assume absoluteLocation == "//MyRepos/foo/bar/object" and relativeToFolder=//MyRepos/foo/baz/, then this method will return ../bar/object.
private void updateMinMaxYByIteration(){ this.minY=Double.NaN; this.maxY=Double.NaN; Iterator iterator=this.data.iterator(); while (iterator.hasNext()) { TimeSeriesDataItem item=(TimeSeriesDataItem)iterator.next(); updateBoundsForAddedItem(item); } }
Finds the bounds of the x and y values for the series, by iterating through all the data items.
public Rational(){ this(0,1); }
Construct a ratinoal with default properties
public AcceptHeader createAcceptHeader(String contentType,String contentSubType) throws ParseException { if (contentType == null || contentSubType == null) throw new NullPointerException("contentType or subtype is null "); Accept accept=new Accept(); accept.setContentType(contentType); accept.setContentSubType(contentSubType); return accept; }
Creates a new AcceptHeader based on the newly supplied contentType and contentSubType values.
public static boolean isDatabaseOK(Properties ctx){ String version="?"; String sql="SELECT Version FROM AD_System"; PreparedStatement pstmt=null; ResultSet rs=null; try { pstmt=prepareStatement(sql,null); rs=pstmt.executeQuery(); if (rs.next()) version=rs.getString(1); } catch ( SQLException e) { log.log(Level.SEVERE,"Problem with AD_System Table - Run system.sql script - " + e.toString()); return false; } finally { close(rs); close(pstmt); rs=null; pstmt=null; } log.info("DB_Version=" + version); if (Adempiere.DB_VERSION.equals(version)) return true; String AD_Message="DatabaseVersionError"; String title=org.compiere.Adempiere.getName() + " " + Msg.getMsg(ctx,AD_Message,true); String msg=Msg.getMsg(ctx,AD_Message); msg=MessageFormat.format(msg,new Object[]{Adempiere.DB_VERSION,version}); Object[] options={UIManager.get("OptionPane.noButtonText"),"Migrate"}; int no=JOptionPane.showOptionDialog(null,msg,title,JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,UIManager.getIcon("OptionPane.errorIcon"),options,options[0]); if (no == 1) { JOptionPane.showMessageDialog(null,"Start RUN_Migrate (in utils)\nSee: http://www.adempiere.com/maintain",title,JOptionPane.INFORMATION_MESSAGE); Env.exitEnv(1); } return false; }
Check database Version with Code version
public final static float geographicLatitude(float lat,float flat){ float f=1.0f - flat; return (float)Math.atan((float)Math.tan(lat) / (f * f)); }
Calculate the geographic latitude given a geocentric latitude. Translated from Ken Anderson's lisp code <i>Freeing the Essence of Computation </i>
public PivotSeries(Strategy strategy,String name,String type,String description,Boolean displayOnChart,Integer chartRGBColor,Boolean subChart){ super(strategy,name,type,description,displayOnChart,chartRGBColor,subChart); }
Creates a new empty series. By default, items added to the series will be sorted into ascending order by period, and duplicate periods will not be allowed.
@Override public void agg(Object newVal){ if (newVal instanceof byte[]) { ByteBuffer buffer=ByteBuffer.wrap((byte[])newVal); buffer.rewind(); while (buffer.hasRemaining()) { aggVal+=buffer.getDouble(); count+=buffer.getDouble(); firstTime=false; } return; } aggVal+=((Number)newVal).doubleValue(); count++; firstTime=false; }
Average Aggregate function which will add all the aggregate values and it will increment the total count every time, for average value
private FileShare prepareEmptyFileSystem(FileSystemParam param,Project project,TenantOrg tenantOrg,VirtualArray varray,VirtualPool vpool,DataObject.Flag[] flags,String task){ _log.debug("prepareEmptyFileSystem start..."); StoragePool pool=null; FileShare fs=new FileShare(); fs.setId(URIUtil.createId(FileShare.class)); fs.setLabel(param.getLabel()); String convertedName=param.getLabel().replaceAll("[^\\dA-Za-z\\_]",""); _log.info("Original name {} and converted name {}",param.getLabel(),convertedName); fs.setName(convertedName); Long fsSize=SizeUtil.translateSize(param.getSize()); fs.setCapacity(fsSize); fs.setNotificationLimit(Long.valueOf(param.getNotificationLimit())); fs.setSoftLimit(Long.valueOf(param.getSoftLimit())); fs.setSoftGracePeriod(param.getSoftGrace()); fs.setVirtualPool(param.getVpool()); if (project != null) { fs.setProject(new NamedURI(project.getId(),fs.getLabel())); } fs.setTenant(new NamedURI(tenantOrg.getId(),param.getLabel())); fs.setVirtualArray(varray.getId()); if (VirtualPool.ProvisioningType.Thin.toString().equalsIgnoreCase(vpool.getSupportedProvisioningType())) { fs.setThinlyProvisioned(Boolean.TRUE); } fs.setOpStatus(new OpStatusMap()); Operation op=new Operation(); op.setResourceType(ResourceOperationTypeEnum.CREATE_FILE_SYSTEM); fs.getOpStatus().createTaskStatus(task,op); if (flags != null) { fs.addInternalFlags(flags); } _dbClient.createObject(fs); return fs; }
Allocate, initialize and persist state of the fileSystem being created.
public void callback(String url,T object,AjaxStatus status){ }
The callback method to be overwritten for subclasses.
private void buildFromSorted(int size,Iterator it,java.io.ObjectInputStream str,Object defaultVal) throws java.io.IOException, ClassNotFoundException { this.size=size; root=buildFromSorted(0,0,size - 1,computeRedLevel(size),it,str,defaultVal); }
Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too many parameters, but seems better than alternatives. The four formats that this method accepts are: 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == null, defaultVal != null). It is assumed that the comparator of the TreeMap is already set prior to calling this method.
protected void startSourceConnection(){ try { sourceConn.start(); } catch ( JMSException e) { ActiveMQJMSBridgeLogger.LOGGER.jmsBridgeSrcConnectError(e,bridgeName); } }
Start the source connection - note the source connection must not be started before otherwise messages will be received and ignored
private void compareSurrogateKeyData(List<String> data,Dictionary forwardDictionary){ int surrogateKey=0; for (int i=0; i < data.size(); i++) { surrogateKey++; String dictionaryValue=forwardDictionary.getDictionaryValueForKey(surrogateKey); assertTrue(data.get(i).equals(dictionaryValue)); } }
This method will compare the actual data with expected data
@Override public boolean putProfile(Profile profile,boolean forceProfile){ assert profile instanceof BucketProfile; BucketProfile bp=(BucketProfile)profile; if (!bp.isHosting && !bp.isInitializing) { if (logger.isTraceEnabled(LogMarker.DA)) { logger.trace(LogMarker.DA,"BucketAdvisor#putProfile early out"); } return false; } if (logger.isTraceEnabled(LogMarker.DA)) { logger.trace(LogMarker.DA,"BucketAdvisor#putProfile profile=<{}> force={}; profile = {}",profile,forceProfile,bp); } final boolean applied; synchronized (this) { profile.initialMembershipVersion=Long.MIN_VALUE; applied=super.putProfile(profile,forceProfile); if (applied && !isPrimary()) { if (bp.isPrimary) { setPrimaryMember(bp.getDistributedMember()); } else { notPrimary(bp.getDistributedMember()); } } } return applied; }
Only allows profiles that actually hosting this bucket. If the profile is primary, then primaryMember will be set to that member but only if we are not already the primary.
public void removeBookmarkedConference(String jid) throws XMPPException { retrieveBookmarks(); Iterator<BookmarkedConference> it=bookmarks.getBookmarkedConferences().iterator(); while (it.hasNext()) { BookmarkedConference conference=it.next(); if (conference.getJid().equalsIgnoreCase(jid)) { if (conference.isShared()) { throw new IllegalArgumentException("Conference is shared and can't be removed"); } it.remove(); privateDataManager.setPrivateData(bookmarks); return; } } }
Removes a conference from the bookmarks.
private void initResponseSource() throws IOException { responseSource=ResponseSource.NETWORK; if (!policy.getUseCaches()) return; OkResponseCache responseCache=client.getOkResponseCache(); if (responseCache == null) return; CacheResponse candidate=responseCache.get(uri,method,requestHeaders.getHeaders().toMultimap(false)); if (candidate == null) return; Map<String,List<String>> responseHeadersMap=candidate.getHeaders(); cachedResponseBody=candidate.getBody(); if (!acceptCacheResponseType(candidate) || responseHeadersMap == null || cachedResponseBody == null) { Util.closeQuietly(cachedResponseBody); return; } RawHeaders rawResponseHeaders=RawHeaders.fromMultimap(responseHeadersMap,true); cachedResponseHeaders=new ResponseHeaders(uri,rawResponseHeaders); long now=System.currentTimeMillis(); this.responseSource=cachedResponseHeaders.chooseResponseSource(now,requestHeaders); if (responseSource == ResponseSource.CACHE) { this.cacheResponse=candidate; setResponse(cachedResponseHeaders,cachedResponseBody); } else if (responseSource == ResponseSource.CONDITIONAL_CACHE) { this.cacheResponse=candidate; } else if (responseSource == ResponseSource.NETWORK) { Util.closeQuietly(cachedResponseBody); } else { throw new AssertionError(); } }
Initialize the source for this response. It may be corrected later if the request headers forbids network use.
protected boolean notDeleted(){ if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) { fPosition.delete(); try { fDocument.removePosition(fCategory,fPosition); } catch ( BadPositionCategoryException x) { } return false; } return true; }
Determines whether the currently investigated position has been deleted by the replace operation specified in the current event. If so, it deletes the position and removes it from the document's position category.
protected void enableButtons(){ if (m_PAttributeButton != null) { if (p_table == null) return; int row=p_table.getSelectedIndex(); int rows=p_table.getRowCount(); if (p_table.getShowTotals()) rows=rows - 1; if (row < 0 || row > rows) { m_PAttributeButton.setEnabled(false); super.enableButtons(); return; } boolean enabled=false; try { Object value=p_table.getValueAt(row,INDEX_PATTRIBUTE); enabled=Boolean.TRUE.equals(value); } catch ( Exception e) { enabled=false; } if (enabled && p_table.isMultiSelection()) { int checkedRows=getNumRecordsSelected(); log.fine("Checked Rows: " + checkedRows); if (checkedRows > 1) enabled=false; } m_PAttributeButton.setEnabled(enabled); } super.enableButtons(); }
Enable PAttribute if row selected/changed
@SuppressWarnings("unchecked") public final int compare(Object o1,Object o2){ LabelValue lhs=(LabelValue)o1; LabelValue rhs=(LabelValue)o2; return c.compare(lhs.getLabel(),rhs.getLabel()); }
Compares the localized labels of two LabelValues.
private void ensureEntryArrayMutable(){ checkMutable(); if (entryList.isEmpty() && !(entryList instanceof ArrayList)) { entryList=new ArrayList<Entry>(maxArraySize); } }
Lazily creates the entry list. Any code that adds to the list must first call this method.
@PrePersist public void prePersist(){ lockTime=System.currentTimeMillis(); }
Used to automatically update the timestamp of locks.
@VisibleForTesting ResponseDecisionMeta handleFeature(final Feature feature,final CheckRequest checkRequest){ ResponseDecisionMeta responseDecisionMeta; if (feature.state == null) { if (feature.rules == null) { throw new IllegalStateException("You must have rules in case the feature does not have a base state"); } for ( Rule rule : feature.rules) { if (RuleMatcher.matchRule(rule)) { responseDecisionMeta=getRuleMatchedResponseDecision(rule); responseDecisionMeta.featureMetadata=feature.featureMetadata; return responseDecisionMeta; } } responseDecisionMeta=getDefaultResponseDecision(feature,checkRequest); responseDecisionMeta.featureMetadata=feature.featureMetadata; return responseDecisionMeta; } else { responseDecisionMeta=getStatePoweredResponseDecision(feature); responseDecisionMeta.featureMetadata=feature.featureMetadata; return responseDecisionMeta; } }
Get the result of handling a given feature (when a match between a requested feature and the store feature is found)
private static String execCommand(String command){ Process cmd; try { cmd=Runtime.getRuntime().exec(command); } catch ( Exception e) { System.err.println("-- Error executing command: " + command + " - "+ e.toString()); return null; } if (DEBUG) System.out.println("** Command executed: " + command); StringBuffer bufOut=new StringBuffer(); StringBuffer bufErr=new StringBuffer(); try { InputStream in=cmd.getInputStream(); InputStream err=cmd.getErrorStream(); int c; while ((c=in.read()) != -1) bufOut.append((char)c); in.close(); while ((c=err.read()) != -1) bufErr.append((char)c); err.close(); } catch ( Exception e) { System.err.println("-- Error reading output: " + e.toString()); return null; } if (DEBUG) { System.out.println("** Command result: " + bufOut.toString()); System.out.println("** Command error: " + bufErr.toString()); } return bufOut.toString(); }
Execute command and return output
public static <E>ImmutableList<E> of(E e1,E e2){ return construct(e1,e2); }
Returns an immutable list containing the given elements, in order.
public static String concatenateName(String name1,String name2){ StringBuffer buf=new StringBuffer(); if (name1 != null && name1.length() > 0) { buf.append(name1); } if (name2 != null && name2.length() > 0) { if (buf.length() > 0) { buf.append('.'); } buf.append(name2); } return buf.toString(); }
Concatenates two names. Uses a dot for separation. Both strings can be empty or <code>null</code>.