code
stringlengths
10
174k
nl
stringlengths
3
129k
public GuacamoleInvalidCredentialsException(Throwable cause,CredentialsInfo credentialsInfo){ super(cause,credentialsInfo); }
Creates a new GuacamoleInvalidCredentialsException with the given cause and associated credential information.
public static String readAsciiLine(InputStream in) throws IOException { StringBuilder result=new StringBuilder(80); while (true) { int c=in.read(); if (c == -1) { throw new EOFException(); } else if (c == '\n') { break; } result.append((char)c); } int length=result.length(); if (length > 0 && result.charAt(length - 1) == '\r') { result.setLength(length - 1); } return result.toString(); }
Returns the ASCII characters up to but not including the next "\r\n", or "\n".
public void severe(String msg,Throwable thrown){ log(Level.SEVERE,thrown,msg,thrown); }
Log a SEVERE message. <p> If the logger is currently enabled for the SEVERE message level then the given message is forwarded to all the registered output Handler objects.
public static <O>SQLParser<O> forPojo(Class<O> pojoClass){ return new SQLParser<O>(pojoClass); }
Creates a new SQLParser for the given POJO class.
protected void installDefaults(){ super.installDefaults(); String prefix=getPropertyPrefix(); Character echoChar=(Character)UIManager.getDefaults().get(prefix + ".echoChar"); if (echoChar != null) { LookAndFeel.installProperty(getComponent(),"echoChar",echoChar); } }
Installs the necessary properties on the JPasswordField.
public String toString(){ return toXML(false); }
Devuelve los valores de la instancia en una cadena de caracteres.
public synchronized void destroy(){ if (log.isDebugEnabled()) { log.debug("Destroying Esper HTTP Adapter"); } for ( EsperHttpServiceBase service : services.values()) { try { service.destroy(); } catch ( Throwable t) { log.info("Error destroying service '" + service.getServiceName() + "' :"+ t.getMessage()); } } services.clear(); }
Destroy the adapter.
public PaymentGatewayParameterServiceImpl(final PaymentModuleGenericDAO<PaymentGatewayParameter,Long> genericDao){ super(genericDao); }
Construct service to work with pg parameters.
public BuildImageParams withAuthConfigs(AuthConfigs authConfigs){ this.authConfigs=authConfigs; return this; }
Adds auth configuration to this parameters.
InlineSequence(NormalMethod method,InlineSequence caller,int bcIndex){ this.method=method; this.caller=caller; this.callSite=null; this.bcIndex=bcIndex; }
Constructs a new inline sequence operand.
private static int distance(Rectangle bounds,int x,int y){ x-=normalize(x,bounds.x,bounds.x + bounds.width); y-=normalize(y,bounds.y,bounds.y + bounds.height); return x * x + y * y; }
Returns a square of the distance from the specified point to the specified rectangle, which does not contain the specified point.
private void terminate(IceProcessingState terminationState){ if (!IceProcessingState.FAILED.equals(terminationState) && !IceProcessingState.TERMINATED.equals(terminationState)) throw new IllegalArgumentException("terminationState"); connCheckClient.stop(); setState(terminationState); }
Terminates this <tt>Agent</tt> by stopping the handling of connectivity checks and setting a specific termination state on it.
public static IOException convertToIOException(Throwable e){ if (e instanceof IOException) { return (IOException)e; } if (e instanceof JdbcSQLException) { JdbcSQLException e2=(JdbcSQLException)e; if (e2.getOriginalCause() != null) { e=e2.getOriginalCause(); } } return new IOException(e.toString(),e); }
Convert an exception to an IO exception.
public void detachStructure(){ processOperation(new DetachOperation()); }
Detaches all xml elements
private static Object parse(XMLTokener x,boolean arrayForm,JSONArray ja) throws JSONException { String attribute; char c; String closeTag=null; int i; JSONArray newja=null; JSONObject newjo=null; Object token; String tagName=null; while (true) { if (!x.more()) { throw x.syntaxError("Bad XML"); } token=x.nextContent(); if (token == XML.LT) { token=x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { token=x.nextToken(); if (!(token instanceof String)) { throw new JSONException("Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { c=x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } else { x.back(); } } else if (c == '[') { token=x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i=1; do { token=x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i+=1; } else if (token == XML.GT) { i-=1; } } while (i > 0); } } else if (token == XML.QUEST) { x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName=(String)token; newja=new JSONArray(); newjo=new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName",tagName); if (ja != null) { ja.put(newjo); } } token=null; for (; ; ) { if (token == null) { token=x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } attribute=(String)token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token=x.nextToken(); if (token == XML.EQ) { token=x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute,XML.stringToValue((String)token)); token=null; } else { newjo.accumulate(attribute,""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag=(String)parse(x,arrayForm,newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '"+ closeTag+ "'"); } tagName=null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes",newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? XML.stringToValue((String)token) : token); } } } }
Parse XML values and store them in a JSONArray.
public static void simulatedJoystick(int id,SimulatedJoystick stick){ joysticks[id]=stick; }
Register a Simulated Joystick on the Data class
@Override public void onTCPConnected(boolean isServer){ if (isServer) { roomState=ConnectionState.CONNECTED; SignalingParameters parameters=new SignalingParameters(new LinkedList<PeerConnection.IceServer>(),isServer,null,null,null,null,null); events.onConnectedToRoom(parameters); } }
If the client is the server side, this will trigger onConnectedToRoom.
public static String generateJMXObjectName(String schedName,String schedInstId){ return "quartz:type=QuartzScheduler" + ",name=" + schedName.replaceAll(":|=|\n",".") + ",instance="+ schedInstId; }
Create the name under which this scheduler should be registered in JMX. <p> The name is composed as: quartz:type=QuartzScheduler,name=<i>[schedName]</i>,instance=<i>[schedInstId]</i> </p>
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static Problem readProblem(File file,double bias) throws IOException, InvalidInputDataException { BufferedReader fp=new BufferedReader(new FileReader(file)); List<Double> vy=new ArrayList<Double>(); List<Feature[]> vx=new ArrayList<Feature[]>(); int max_index=0; int lineNr=0; try { while (true) { String line=fp.readLine(); if (line == null) { break; } lineNr++; StringTokenizer st=new StringTokenizer(line," \t\n\r\f:"); String token; try { token=st.nextToken(); } catch ( NoSuchElementException e) { throw new InvalidInputDataException("empty line",file,lineNr,e); } try { vy.add(atof(token)); } catch ( NumberFormatException e) { throw new InvalidInputDataException("invalid label: " + token,file,lineNr,e); } int m=st.countTokens() / 2; Feature[] x; if (bias >= 0) { x=new Feature[m + 1]; } else { x=new Feature[m]; } int indexBefore=0; for (int j=0; j < m; j++) { token=st.nextToken(); int index; try { index=atoi(token); } catch ( NumberFormatException e) { throw new InvalidInputDataException("invalid index: " + token,file,lineNr,e); } if (index < 0) { throw new InvalidInputDataException("invalid index: " + index,file,lineNr); } if (index <= indexBefore) { throw new InvalidInputDataException("indices must be sorted in ascending order",file,lineNr); } indexBefore=index; token=st.nextToken(); try { double value=atof(token); x[j]=new FeatureNode(index,value); } catch ( NumberFormatException e) { throw new InvalidInputDataException("invalid value: " + token,file,lineNr); } } if (m > 0) { max_index=Math.max(max_index,x[m - 1].getIndex()); } vx.add(x); } return constructProblem(vy,vx,max_index,bias); } finally { fp.close(); } }
reads a problem from LibSVM format
public static SnmpEngineId createEngineId(byte[] arr) throws IllegalArgumentException { if ((arr == null) || arr.length == 0) return null; validateId(arr); return new SnmpEngineId(arr); }
Generates an engine Id based on the passed array.
private void initialize(){ width=getContext().getResources().getDimensionPixelSize(R.dimen.default_width); maximize=false; adapter=new DividableGridAdapter(getContext(),Style.LIST,width); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { super.setOnShowListener(createOnShowListener()); } }
Initializes the bottom sheet.
public int api_danger(Method m){ int danger=0; String perms=api_descriptors(m).toString(); if (perms.contains("intent")) danger++; if (perms.contains("permission")) danger++; if (perms.contains("reflect") || perms.contains("thread") || perms.contains("loader")) danger++; if ((danger == 0) && (perms.contains("gui"))) danger--; return danger; }
Returns the relative dangerousness of the API. 0 is average, Negative numbers are safer, positive numbers are more dangerous.
protected JSDocCharScanner(JSDocCharScanner src,int maxOffsetExcluded){ this.s=src.s; this.nextFencePost=maxOffsetExcluded; this.nextOffset=src.nextOffset; this.offset=src.offset; }
Initiate scanner with values of other scanner.
@SuppressWarnings("deprecation") @Deprecated public final void suspend(){ if (suspendHelper()) { Thread.currentThread().suspend(); } }
Suspends every thread in this group and recursively in all its subgroups.
@Override public void run(){ amIActive=true; int progress; int row, col, i; int baseCol, baseRow, appendCol, appendRow; double x, y, z, zN, zBase, zAppend; double w1, w2, dist1, dist2, sumDist; double r1, g1, b1, r2, g2, b2; int r, g, b; boolean performHistoMatching=true; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } String inputBaseHeader=args[0]; String inputHeader=args[1]; String outputHeader=args[2]; String resampleMethod=args[3].toLowerCase().trim(); if (!resampleMethod.equals("nearest neighbour") && !resampleMethod.equals("bilinear") && !resampleMethod.contains("cubic")) { showFeedback("Resample method not recognized"); return; } if (args[4].toLowerCase().contains("true")) { performHistoMatching=true; } else { performHistoMatching=false; } double power=Double.parseDouble(args[5]); if (power > 15.0) { power=15.0; } if (power < 1.0) { power=1.0; } try { if (performHistoMatching) { String inputHeaderAdjusted=StringUtilities.replaceLast(inputHeader,".dep","_temp1.dep"); histogramMatching(inputHeader,inputBaseHeader,inputHeaderAdjusted); inputHeader=inputHeaderAdjusted; } WhiteboxRaster baseRaster=new WhiteboxRaster(inputBaseHeader,"r"); WhiteboxRaster appendRaster=new WhiteboxRaster(inputHeader,"r"); boolean rgbMode=((baseRaster.getDataScale() == WhiteboxRasterBase.DataScale.RGB) & (appendRaster.getDataScale() == WhiteboxRasterBase.DataScale.RGB)); double cellSizeX=baseRaster.getCellSizeX(); double cellSizeY=baseRaster.getCellSizeY(); double baseNoData=baseRaster.getNoDataValue(); double appendNoData=appendRaster.getNoDataValue(); double outputNoData=baseNoData; int baseCols=baseRaster.getNumberColumns(); int baseRows=baseRaster.getNumberRows(); int appendCols=appendRaster.getNumberColumns(); int appendRows=appendRaster.getNumberRows(); double baseNorth=baseRaster.getNorth(); double baseSouth=baseRaster.getSouth(); double baseEast=baseRaster.getEast(); double baseWest=baseRaster.getWest(); double baseNSRange=baseNorth - baseSouth; double baseEWRange=baseEast - baseWest; double appendNorth=appendRaster.getNorth(); double appendSouth=appendRaster.getSouth(); double appendEast=appendRaster.getEast(); double appendWest=appendRaster.getWest(); double appendNSRange=appendNorth - appendSouth; double appendEWRange=appendEast - appendWest; double north, south, east, west; if (baseNorth > baseSouth) { north=Double.NEGATIVE_INFINITY; south=Double.POSITIVE_INFINITY; if (baseNorth > north) { north=baseNorth; } if (appendNorth > north) { north=appendNorth; } if (baseSouth < south) { south=baseSouth; } if (appendSouth < south) { south=appendSouth; } } else { north=Double.POSITIVE_INFINITY; south=Double.NEGATIVE_INFINITY; if (baseNorth < north) { north=baseNorth; } if (appendNorth < north) { north=appendNorth; } if (baseSouth > south) { south=baseSouth; } if (appendSouth > south) { south=appendSouth; } } if (baseEast > baseWest) { east=Double.NEGATIVE_INFINITY; west=Double.POSITIVE_INFINITY; if (baseEast > east) { east=baseEast; } if (appendEast > east) { east=appendEast; } if (baseWest < west) { west=baseWest; } if (appendWest < west) { west=appendWest; } } else { east=Double.POSITIVE_INFINITY; west=Double.NEGATIVE_INFINITY; if (baseEast < east) { east=baseEast; } if (appendEast < east) { east=appendEast; } if (baseWest > west) { west=baseWest; } if (appendWest > west) { west=appendWest; } } int nRows=(int)Math.round(Math.abs(north - south) / cellSizeY); int nCols=(int)Math.round(Math.abs(east - west) / cellSizeX); WhiteboxRaster destination=new WhiteboxRaster(outputHeader,north,south,east,west,nRows,nCols,WhiteboxRasterBase.DataScale.CONTINUOUS,WhiteboxRasterBase.DataType.FLOAT,outputNoData,outputNoData); if (rgbMode) { destination.setDataScale(WhiteboxRasterBase.DataScale.RGB); } int nRowsLessOne=nRows - 1; String distToEdgeBaseHeader=StringUtilities.replaceLast(inputBaseHeader,".dep","_temp1.dep"); WhiteboxRaster distToEdgeBase=new WhiteboxRaster(distToEdgeBaseHeader,"rw",inputBaseHeader,WhiteboxRaster.DataType.FLOAT,Float.POSITIVE_INFINITY); distToEdgeBase.isTemporaryFile=true; double[] data; for (row=0; row < baseRows; row++) { data=baseRaster.getRowValues(row); for (col=0; col < baseCols; col++) { if (row == 0 || row == baseRows - 1) { distToEdgeBase.setValue(row,col,0.0); } else if (col == 0 || col == baseCols - 1) { distToEdgeBase.setValue(row,col,0.0); } else { if (data[col] != baseNoData) { if (data[col - 1] == baseNoData || data[col + 1] == baseNoData) { distToEdgeBase.setValue(row,col,0.0); } } else { distToEdgeBase.setValue(row,col,0.0); } } } } calculateDistance(distToEdgeBase); String distToEdgeAppendHeader=whitebox.utilities.StringUtilities.replaceLast(inputBaseHeader,".dep","_temp2.dep"); WhiteboxRaster distToEdgeAppend=new WhiteboxRaster(distToEdgeAppendHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,Float.POSITIVE_INFINITY); distToEdgeAppend.isTemporaryFile=true; for (row=0; row < appendRows; row++) { data=appendRaster.getRowValues(row); for (col=0; col < appendCols; col++) { if (row == 0 || row == appendRows - 1) { distToEdgeAppend.setValue(row,col,0.0); } else if (col == 0 || col == appendCols - 1) { distToEdgeAppend.setValue(row,col,0.0); } else { if (data[col] != appendNoData) { if (data[col - 1] == appendNoData || data[col + 1] == appendNoData) { distToEdgeAppend.setValue(row,col,0.0); } } else { distToEdgeAppend.setValue(row,col,0.0); } } } } calculateDistance(distToEdgeAppend); if (resampleMethod.contains("nearest")) { for (row=0; row < nRows; row++) { for (col=0; col < nCols; col++) { x=destination.getXCoordinateFromColumn(col); y=destination.getYCoordinateFromRow(row); baseCol=baseRaster.getColumnFromXCoordinate(x); baseRow=baseRaster.getRowFromYCoordinate(y); appendCol=appendRaster.getColumnFromXCoordinate(x); appendRow=appendRaster.getRowFromYCoordinate(y); zBase=baseRaster.getValue(baseRow,baseCol); zAppend=appendRaster.getValue(appendRow,appendCol); if (zBase != baseNoData && zAppend == appendNoData) { destination.setValue(row,col,zBase); } else if (zBase == baseNoData && zAppend != appendNoData) { destination.setValue(row,col,zAppend); } else if (zBase == baseNoData && zAppend == appendNoData) { destination.setValue(row,col,outputNoData); } else { dist1=distToEdgeBase.getValue(baseRow,baseCol); dist2=distToEdgeAppend.getValue(appendRow,appendCol); sumDist=Math.pow(dist1,power) + Math.pow(dist2,power); w1=Math.pow(dist1,power) / sumDist; w2=Math.pow(dist2,power) / sumDist; if (!rgbMode) { z=w1 * zBase + w2 * zAppend; } else { r1=(double)((int)zBase & 0xFF); g1=(double)(((int)zBase >> 8) & 0xFF); b1=(double)(((int)zBase >> 16) & 0xFF); r2=(double)((int)zAppend & 0xFF); g2=(double)(((int)zAppend >> 8) & 0xFF); b2=(double)(((int)zAppend >> 16) & 0xFF); r=(int)((r1 * w1) + (r2 * w2)); g=(int)((g1 * w1) + (g2 * w2)); b=(int)((b1 * w1) + (b2 * w2)); z=(double)((255 << 24) | (b << 16) | (g << 8)| r); } destination.setValue(row,col,z); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / nRowsLessOne); updateProgress("Resampling images: ",progress); } } else { if (destination.getDataType() != WhiteboxRaster.DataType.DOUBLE && destination.getDataType() != WhiteboxRaster.DataType.FLOAT) { showFeedback("The destination image is not of an appropriate data" + " type (i.e. double or float) to perform this operation."); return; } double dX, dY; double srcRow, srcCol; double originRow, originCol; double rowN, colN; double sumOfDist; double[] shiftX; double[] shiftY; int numNeighbours=0; double[][] neighbour; if (resampleMethod.contains("cubic")) { shiftX=new double[]{-1,0,1,2,-1,0,1,2,-1,0,1,2,-1,0,1,2}; shiftY=new double[]{-1,-1,-1,-1,0,0,0,0,1,1,1,1,2,2,2,2}; numNeighbours=16; neighbour=new double[numNeighbours][2]; } else { shiftX=new double[]{0,1,0,1}; shiftY=new double[]{0,0,1,1}; numNeighbours=4; neighbour=new double[numNeighbours][2]; } for (row=0; row < nRows; row++) { for (col=0; col < nCols; col++) { x=destination.getXCoordinateFromColumn(col); y=destination.getYCoordinateFromRow(row); baseCol=baseRaster.getColumnFromXCoordinate(x); baseRow=baseRaster.getRowFromYCoordinate(y); srcRow=(baseNorth - y) / baseNSRange * (baseRows - 0.5); srcCol=(x - baseWest) / baseEWRange * (baseCols - 0.5); originRow=Math.floor(srcRow); originCol=Math.floor(srcCol); sumOfDist=0; for (i=0; i < numNeighbours; i++) { rowN=originRow + shiftY[i]; colN=originCol + shiftX[i]; neighbour[i][0]=baseRaster.getValue((int)rowN,(int)colN); dY=rowN - srcRow; dX=colN - srcCol; if ((dX + dY) != 0 && neighbour[i][0] != baseNoData) { neighbour[i][1]=1 / (dX * dX + dY * dY); sumOfDist+=neighbour[i][1]; } else if (neighbour[i][0] == baseNoData) { neighbour[i][1]=0; } else { neighbour[i][1]=99999999; sumOfDist+=neighbour[i][1]; } } if (sumOfDist > 0) { z=0; for (i=0; i < numNeighbours; i++) { z+=neighbour[i][0] * neighbour[i][1] / sumOfDist; } zBase=z; } else { zBase=baseNoData; } appendCol=appendRaster.getColumnFromXCoordinate(x); appendRow=appendRaster.getRowFromYCoordinate(y); srcRow=(appendNorth - y) / appendNSRange * (appendRows - 0.5); srcCol=(x - appendWest) / appendEWRange * (appendCols - 0.5); originRow=Math.floor(srcRow); originCol=Math.floor(srcCol); sumOfDist=0; for (i=0; i < numNeighbours; i++) { rowN=originRow + shiftY[i]; colN=originCol + shiftX[i]; neighbour[i][0]=appendRaster.getValue((int)rowN,(int)colN); dY=rowN - srcRow; dX=colN - srcCol; if ((dX + dY) != 0 && neighbour[i][0] != appendNoData) { neighbour[i][1]=1 / (dX * dX + dY * dY); sumOfDist+=neighbour[i][1]; } else if (neighbour[i][0] == appendNoData) { neighbour[i][1]=0; } else { neighbour[i][1]=99999999; sumOfDist+=neighbour[i][1]; } } if (sumOfDist > 0) { z=0; for (i=0; i < numNeighbours; i++) { z+=(neighbour[i][0] * neighbour[i][1]) / sumOfDist; } zAppend=z; } else { zAppend=appendNoData; } if (zBase != baseNoData && zAppend == appendNoData) { destination.setValue(row,col,zBase); } else if (zBase == baseNoData && zAppend != appendNoData) { destination.setValue(row,col,zAppend); } else if (zBase == baseNoData && zAppend == appendNoData) { destination.setValue(row,col,outputNoData); } else { dist1=distToEdgeBase.getValue(baseRow,baseCol); dist2=distToEdgeAppend.getValue(appendRow,appendCol); sumDist=dist1 + dist2; w1=dist1 / sumDist; w2=dist2 / sumDist; z=w1 * zBase + w2 * zAppend; destination.setValue(row,col,z); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / nRowsLessOne); updateProgress("Resampling images: ",progress); } } destination.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); destination.addMetadataEntry("Created on " + new Date()); destination.close(); distToEdgeBase.close(); distToEdgeAppend.close(); baseRaster.close(); if (performHistoMatching) { File header=new File(inputHeader); if (header.exists()) { header.delete(); } File dataFile=new File(StringUtilities.replaceLast(inputHeader,".dep",".tas")); if (dataFile.exists()) { dataFile.delete(); } } else { appendRaster.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 outputHistogramUnitConversion(Gate g){ if (g.Type == Gate.GateType.OUTPUT || g.Type == Gate.GateType.OUTPUT_OR) { ArrayList<double[]> histogram_rpus=g.get_histogram_rpus(); ArrayList<double[]> shifted_histogram_rpus=new ArrayList<double[]>(); for ( double[] histogram : histogram_rpus) { double current_median=HistogramUtil.median(histogram,g.get_histogram_bins()); double new_median=current_median * g.get_unit_conversion(); double[] shifted_histogram=HistogramUtil.normalizeHistogramToNewMedian(histogram,new_median,g.get_histogram_bins()); shifted_histogram_rpus.add(shifted_histogram); } g.set_histogram_rpus(shifted_histogram_rpus); } }
If the output module is on a different plasmid (with a different copy number or different affect on cell growth), the RPU units of the circuit might need to be converted.
public boolean removeTelegramWriter(TelegramWriter remWriter){ return (telegramWriters.remove(remWriter)); }
remove a Writer to be notified about new telegrams
public static MapDialogFragment newInstance(Branch branch){ return newInstance(null,null,branch); }
Creates dialog which handles the branch detail with an interactive map.
protected void drawHexagon(int x,int y,int w,int h,Color fillColor,Paint fillPaint,Color penColor,boolean shadow,String direction){ Polygon hexagon=new Polygon(); if (direction.equals(mxConstants.DIRECTION_NORTH) || direction.equals(mxConstants.DIRECTION_SOUTH)) { hexagon.addPoint(x + (int)(0.5 * w),y); hexagon.addPoint(x + w,y + (int)(0.25 * h)); hexagon.addPoint(x + w,y + (int)(0.75 * h)); hexagon.addPoint(x + (int)(0.5 * w),y + h); hexagon.addPoint(x,y + (int)(0.75 * h)); hexagon.addPoint(x,y + (int)(0.25 * h)); } else { hexagon.addPoint(x + (int)(0.25 * w),y); hexagon.addPoint(x + (int)(0.75 * w),y); hexagon.addPoint(x + w,y + (int)(0.5 * h)); hexagon.addPoint(x + (int)(0.75 * w),y + h); hexagon.addPoint(x + (int)(0.25 * w),y + h); hexagon.addPoint(x,y + (int)(0.5 * h)); } drawPolygon(hexagon,fillColor,fillPaint,penColor,shadow); }
Draws a hexagon shape for the given parameters.
public SimpleEnvironmentViewCtrl(StackPane viewRoot){ splitPane=new SplitPane(); textArea=new TextArea(); textArea.setMinWidth(0.0); splitPane.getItems().add(textArea); viewRoot.getChildren().add(splitPane); }
Adds a split pane and a text area to the provided pane. The result is an environment view which prints messages about environment changes on the text area.
private void populateDataDomainAccessProfile(AccessProfile accessProfile,StorageProvider providerInfo){ accessProfile.setSystemId(providerInfo.getId()); accessProfile.setSystemClazz(providerInfo.getClass()); accessProfile.setIpAddress(providerInfo.getIPAddress()); accessProfile.setUserName(providerInfo.getUserName()); accessProfile.setPassword(providerInfo.getPassword()); accessProfile.setSystemType(DiscoveredDataObject.Type.datadomain.name()); accessProfile.setPortNumber(providerInfo.getPortNumber()); }
inject details needed for Scanning
@Override public void run(){ amIActive=true; String slopeHeader=null; String aspectHeader=null; String outputHeader=null; String horizonAngleHeader=null; double z; int progress; int[] dY={-1,0,1,1,1,0,-1,-1}; int[] dX={1,1,1,0,-1,-1,-1,0}; int row, col; double azimuth=0; boolean blnSlope=false; double relativeAspect=0; double slopeVal=0; double aspectVal=0; double HAval=0; double gridRes=0; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (int i=0; i < args.length; i++) { if (i == 0) { slopeHeader=args[i]; } else if (i == 1) { aspectHeader=args[i]; } else if (i == 2) { outputHeader=args[i]; } else if (i == 2) { azimuth=Math.toRadians(Double.parseDouble(args[i]) - 90); } else if (i == 3) { if (args[i].toLowerCase().contains("slope")) { blnSlope=true; } else { blnSlope=false; } } else if (i == 4) { if (blnSlope) { if (args[i].toLowerCase().contains("not specified")) { showFeedback("The horizon angle raster must be specified"); break; } horizonAngleHeader=args[i]; } } } if ((slopeHeader == null) || aspectHeader == null || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster slope=new WhiteboxRaster(slopeHeader,"r"); int rows=slope.getNumberRows(); int cols=slope.getNumberColumns(); gridRes=(slope.getCellSizeX() + slope.getCellSizeY()) / 2; double slopeNoData=slope.getNoDataValue(); WhiteboxRaster aspect=new WhiteboxRaster(aspectHeader,"r"); if (aspect.getNumberRows() != rows || aspect.getNumberColumns() != cols) { showFeedback("the input images must have the same dimensions (i.e. rows and columns)."); return; } double aspectNoData=aspect.getNoDataValue(); WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",slopeHeader,WhiteboxRaster.DataType.FLOAT,slopeNoData); output.setPreferredPalette("grey.pal"); double[] slopeData; double[] aspectData; if (blnSlope) { WhiteboxRaster horizonAngle=new WhiteboxRaster(horizonAngleHeader,"r"); if (horizonAngle.getNumberRows() != rows || horizonAngle.getNumberColumns() != cols) { showFeedback("the input images must have the same dimensions (i.e. rows and columns)."); return; } double HANoData=horizonAngle.getNoDataValue(); double[] HAdata; for (row=0; row < rows; row++) { slopeData=slope.getRowValues(row); aspectData=aspect.getRowValues(row); HAdata=horizonAngle.getRowValues(row); for (col=0; col < cols; col++) { relativeAspect=azimuth - aspectData[col]; if (relativeAspect > 180) { relativeAspect=360 - relativeAspect; if (slopeData[col] != slopeNoData && aspectData[col] != aspectNoData && HAdata[col] != HANoData) { slopeVal=Math.toRadians(slopeData[col]); aspectVal=Math.toRadians(aspectData[col]); HAval=Math.toRadians(HAdata[col]); relativeAspect=Math.toRadians(relativeAspect); output.setValue(row,col,Math.cos(slopeVal) * Math.sin(HAval) + Math.sin(slopeVal) * Math.cos(HAval) * Math.cos(relativeAspect)); } else { output.setValue(row,col,slopeNoData); } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress(progress); } horizonAngle.close(); } else { HAval=0; for (row=0; row < rows; row++) { slopeData=slope.getRowValues(row); aspectData=aspect.getRowValues(row); for (col=0; col < cols; col++) { relativeAspect=azimuth - aspectData[col]; if (relativeAspect > 180) { relativeAspect=360 - relativeAspect; } if (slopeData[col] != slopeNoData && aspectData[col] != aspectNoData) { slopeVal=Math.toRadians(slopeData[col]); aspectVal=Math.toRadians(aspectData[col]); relativeAspect=Math.toRadians(relativeAspect); output.setValue(row,col,Math.cos(slopeVal) * Math.sin(HAval) + Math.sin(slopeVal) * Math.cos(HAval) * Math.cos(relativeAspect)); } else { output.setValue(row,col,slopeNoData); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress(progress); } } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); slope.close(); aspect.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 boolean isDraft(){ Control control=getControl(); return (control != null && control.isDraft()); }
Draft status.
public CardImagesLoader(Component peer){ this.peer=peer; }
Load deck.
public static ComponentUI createUI(JComponent a){ ComponentUI mui=new MultiMenuItemUI(); return MultiLookAndFeel.createUIs(mui,((MultiMenuItemUI)mui).uis,a); }
Returns a multiplexing UI instance if any of the auxiliary <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the UI object obtained from the default <code>LookAndFeel</code>.
public double[] readAllDoubles(){ String[] fields=readAllStrings(); double[] vals=new double[fields.length]; for (int i=0; i < fields.length; i++) vals[i]=Double.parseDouble(fields[i]); return vals; }
Read all doubles until the end of input is reached, and return them.
public static double findMinDistance(Instances inst,int attrIndex){ double min=Double.MAX_VALUE; int numInst=inst.numInstances(); double diff; if (numInst < 2) { return min; } int begin=-1; Instance instance=null; do { begin++; if (begin < numInst) { instance=inst.instance(begin); } } while (begin < numInst && instance.isMissing(attrIndex)); double secondValue=inst.instance(begin).value(attrIndex); for (int i=begin; i < numInst && !inst.instance(i).isMissing(attrIndex); i++) { double firstValue=secondValue; secondValue=inst.instance(i).value(attrIndex); if (secondValue != firstValue) { diff=secondValue - firstValue; if (diff < min && diff > 0.0) { min=diff; } } } return min; }
Find the minimum distance between values
@Override public boolean test(Object receiver,String property,Object[] args,Object expectedValue){ if (IS_ANGULAR2_PROJECT_PROPERTY.equals(property)) { return testIsTypeScriptProject(receiver); } return false; }
Tests if the receiver object is a project is a Angular2 project
@Override public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){ Log.w(TAG,"Upgrading database from version " + oldVersion + " to "+ newVersion+ ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); }
Demonstrates that the provider must consider what happens when the underlying datastore is changed. In this sample, the database is upgraded the database by destroying the existing data. A real application should upgrade the database in place.
private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i=lruEntries.values().iterator(); i.hasNext(); ) { Entry entry=i.next(); if (entry.currentEditor == null) { for (int t=0; t < valueCount; t++) { size+=entry.lengths[t]; } } else { entry.currentEditor=null; for (int t=0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } }
Computes the initial size and collects garbage as a part of opening the cache. Dirty entries are assumed to be inconsistent and will be deleted.
public boolean isUpdate(){ boolean is; if (m_editFlag == FolderEditFlag.UPDATE) is=true; else is=false; return is; }
Devuelve <tt>true</tt> si el nodo ha sido modificado
public void removeTileEntity(BlockPos pos){ if (this.isCubeLoaded) { TileEntity tileEntity=this.tileEntityMap.remove(pos); if (tileEntity != null) { tileEntity.invalidate(); this.isModified=true; } } }
Remove the tile entity at the specified location
public void paintRadioButtonBackground(SynthContext context,Graphics g,int x,int y,int w,int h){ paintBackground(context,g,x,y,w,h,null); }
Paints the background of a radio button.
private void addToken(int tokenType){ addToken(zzStartRead,zzMarkedPos - 1,tokenType); }
Adds the token specified to the current linked list of tokens.
public InternalTenantServiceClient(String server){ setServer(server); }
Client with specific host
private RdapSearchResults searchByNameserverLdhName(final RdapSearchPattern partialStringQuery,final DateTime now){ Iterable<Key<HostResource>> hostKeys=getNameserverRefsByLdhName(partialStringQuery,now); if (Iterables.isEmpty(hostKeys)) { throw new NotFoundException("No matching nameservers found"); } return searchByNameserverRefs(hostKeys,now); }
Searches for domains by nameserver name, returning a JSON array of domain info maps.
public Body(String html,String text){ this.html=html; this.text=text; }
Directly creates an email body given both HTML and plain text content.
private void sendStageProgressPatch(State current,TaskState.TaskStage stage,TaskState.SubStage subStage){ if (current.isSelfProgressionDisabled) { return; } sendSelfPatch(buildPatch(stage,subStage,null)); }
Send a patch message to ourselves to update the execution stage.
@Override protected void rehash(int newCapacity){ int oldCapacity=_set.length; double[] oldKeys=_set; double[] oldVals=_values; byte[] oldStates=_states; _set=new double[newCapacity]; _values=new double[newCapacity]; _states=new byte[newCapacity]; for (int i=oldCapacity; i-- > 0; ) { if (oldStates[i] == FULL) { double o=oldKeys[i]; int index=insertionIndex(o); _set[index]=o; _values[index]=oldVals[i]; _states[index]=FULL; } } }
rehashes the map to the new capacity.
protected Cipher(CipherSpi cipherSpi,Provider provider,String transformation){ if (cipherSpi == null) { throw new NullPointerException("cipherSpi == null"); } if (!(cipherSpi instanceof NullCipherSpi) && provider == null) { throw new NullPointerException("provider == null"); } this.provider=provider; this.transformation=transformation; this.spiImpl=cipherSpi; }
Creates a new Cipher instance.
public Builder host(final String host){ checkNotNull(host,"host"); this.host=of(host); return this; }
Host to bind service to.
@Override public Consist addConsist(DccLocoAddress address){ if (consistTable.containsKey(address)) { return consistTable.get(address); } EasyDccConsist consist; consist=new EasyDccConsist(address); consistTable.put(address,consist); return consist; }
Add a new EasyDccConsist with the given address to consistTable/consistList
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
private Map<String,ExecutableElement> makeSetterMap(Map<ExecutableElement,String> getterToPropertyName){ Map<String,TypeMirror> getterMap=new TreeMap<String,TypeMirror>(); for ( Map.Entry<ExecutableElement,String> entry : getterToPropertyName.entrySet()) { getterMap.put(entry.getValue(),entry.getKey().getReturnType()); } Map<String,ExecutableElement> noPrefixMap=Maps.newLinkedHashMap(); Map<String,ExecutableElement> prefixMap=Maps.newLinkedHashMap(); boolean ok=true; for ( ExecutableElement setter : setters) { Map<String,ExecutableElement> map=noPrefixMap; String name=setter.getSimpleName().toString(); TypeMirror type=getterMap.get(name); if (type == null && name.startsWith("set")) { name=Introspector.decapitalize(name.substring(3)); type=getterMap.get(name); map=prefixMap; } if (type == null) { errorReporter.reportError("Method does not correspond to a property of " + autoValueClass,setter); ok=false; } else { VariableElement parameter=Iterables.getOnlyElement(setter.getParameters()); if (TYPE_EQUIVALENCE.equivalent(type,parameter.asType())) { getterMap.remove(name); map.put(name,setter); } else { errorReporter.reportError("Parameter type should be " + type,parameter); ok=false; } } } if (!ok) { return null; } boolean prefixing=!prefixMap.isEmpty(); if (prefixing && !noPrefixMap.isEmpty()) { errorReporter.reportError("If any setter methods use the setFoo convention then all must",noPrefixMap.values().iterator().next()); return null; } if (!getterMap.isEmpty()) { for ( Map.Entry<String,TypeMirror> entry : getterMap.entrySet()) { String setterName=prefixing ? prefixWithSet(entry.getKey()) : entry.getKey(); String error=String.format("Expected a method with this signature: %s%s %s(%s)",builderTypeElement,TypeSimplifier.actualTypeParametersString(builderTypeElement),setterName,entry.getValue()); errorReporter.reportError(error,builderTypeElement); } return null; } return noPrefixMap.isEmpty() ? prefixMap : noPrefixMap; }
Returns a map from property name to setter method. If the setter methods are invalid (for example not every getter has a setter, or some setters don't correspond to getters) then emits an error message and returns null.
public synchronized void closeDriver(){ if (camera != null) { camera.release(); camera=null; framingRect=null; framingRectInPreview=null; } }
Closes the camera driver if still in use.
public boolean isPopupOpen(){ return (popup != null); }
isPopupOpen, This returns true if the time menu popup is open. This returns false if the time menu popup is closed
ValueForKeyIterator(@Nullable Object key){ this.key=key; KeyList<K,V> keyList=keyToKeyList.get(key); next=(keyList == null) ? null : keyList.head; }
Constructs a new iterator over all values for the specified key.
@Override public int hashCode(){ return super.hashCode(); }
Returns a hash code for this instance.
public void replay(ReplayCallback replayCallback){ TempBuffer tReadBuffer=TempBuffer.createLarge(); byte[] readBuffer=tReadBuffer.buffer(); int bufferLength=readBuffer.length; try (InStore jIn=_blockStore.openRead(_startAddress,getSegmentSize())){ Replay replay=readReplay(jIn); if (replay == null) { return; } long address=replay.getCheckpointStart(); long next; setSequence(replay.getSequence()); TempBuffer tBuffer=TempBuffer.create(); byte[] tempBuffer=tBuffer.buffer(); jIn.read(getBlockAddress(address),readBuffer,0,bufferLength); ReadStream is=new ReadStream(); while (address < _tailAddress && (next=scanItem(jIn,address,readBuffer,tempBuffer)) > 0) { boolean isOverflow=getBlockAddress(address) != getBlockAddress(next); if (isOverflow) { jIn.read(getBlockAddress(address),readBuffer,0,bufferLength); } ReplayInputStream rIn=new ReplayInputStream(jIn,readBuffer,address); is.init(rIn); try { replayCallback.onItem(is); } catch ( Exception e) { e.printStackTrace(); log.log(Level.FINER,e.toString(),e); } address=next; if (isOverflow) { jIn.read(getBlockAddress(address),readBuffer,0,bufferLength); } _index=address; _flushIndex=address; } } }
Replays all open journal entries. The journal entry will call into the callback listener with an open InputStream to read the entry.
public TLongHashSet(TLongHashingStrategy strategy){ super(strategy); }
Creates a new <code>TLongHash</code> instance with the default capacity and load factor.
public CustomizedDistributedRowLock<K> withConsistencyLevel(ConsistencyLevel consistencyLevel){ this.consistencyLevel=consistencyLevel; return this; }
Modify the consistency level being used. Consistency should always be a variant of quorum. The default is CL_QUORUM, which is OK for single region. For multi region the consistency level should be CL_LOCAL_QUORUM. CL_EACH_QUORUM can be used but will Incur substantial latency.
public static void showFormattedMessage(String messageKey,Object... args){ _callback.showFormattedMessage(messageKey,args); }
Shows a locale-specific formatted message to the user using the specified key to look up the message in the resource bundles.
public void addSerialisedObjectToIntentBundle(String key,Intent intent,Object object){ if (key == null) { throw new InvalidParameterException("IntentHelper error adding serialised object to intentbundle, key may not be null"); } if (intent == null) { throw new InvalidParameterException("IntentHelper error adding serialised object to intentbundle, intent may not be null"); } if (object == null) { throw new InvalidParameterException("IntentHelper error adding serialised object to intentbundle, object may not be null"); } Gson gson=new Gson(); intent.putExtra(key,gson.toJson(object)); }
Stores the object serialised as JSON string in the Intent extradata
public static void main(String[] args){ java.util.Random r=new java.util.Random(); Bits bits=new Bits(); for (int i=0; i < 125; i++) { int k; do { k=r.nextInt(250); } while (bits.isMember(k)); System.out.println("adding " + k); bits.incl(k); } int count=0; for (int i=bits.nextBit(0); i >= 0; i=bits.nextBit(i + 1)) { System.out.println("found " + i); count++; } if (count != 125) { throw new Error(); } }
Test Bits.nextBit(int).
boolean cancel(int propertyConstant){ if ((mPropertyMask & propertyConstant) != 0 && mNameValuesHolder != null) { int count=mNameValuesHolder.size(); for (int i=0; i < count; ++i) { NameValuesHolder nameValuesHolder=mNameValuesHolder.get(i); if (nameValuesHolder.mNameConstant == propertyConstant) { mNameValuesHolder.remove(i); mPropertyMask&=~propertyConstant; return true; } } } return false; }
Removes the given property from being animated as a part of this PropertyBundle. If the property was a part of this bundle, it returns true to indicate that it was, in fact, canceled. This is an indication to the caller that a cancellation actually occurred.
public static long parseUnsignedLong(String str) throws NumberFormatException { if (str.length() > 16) { throw new NumberFormatException(); } int lowstart=str.length() - 8; if (lowstart <= 0) return Long.parseLong(str,16); else return Long.parseLong(str.substring(0,lowstart),16) << 32 | Long.parseLong(str.substring(lowstart),16); }
Parses the string argument as a signed long with the radix 16.
public Enumeration oids(){ return ordering.elements(); }
return an Enumeration of the extension field's object ids.
public static boolean deleteFiles(String... files){ if (files == null || files.length == 0) { return true; } Log.d(TAG,"Number of files to delete: " + files.length); boolean allFilesDeleted=true; for (int i=0; i < files.length; i++) { Log.d(TAG,"Deleting file: " + files[i]); URI fileUri=URI.create(files[i]); File fileToDelete=new File(fileUri); boolean deleted=fileToDelete.delete(); if (!deleted) { allFilesDeleted=false; } } return allFilesDeleted; }
Deletes an array of files from the local storage
public void reloadDocument(String URI){ reloadDocument(loadDocument(URI)); }
Reloads the document using the same base URL and namespace handler. Reloading will pick up changes to styles within the document.
Node[][] genArrays(int size,int narrays){ Node[][] arrays=new Node[narrays][size]; for (int i=0; i < narrays; i++) { for (int j=0; j < size; j++) { arrays[i][j]=new Node(null,0); } } return arrays; }
Generate object arrays.
public boolean isSet(_Fields field){ if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CATEGORY: return isSetCategory(); case MESSAGE: return isSetMessage(); } throw new IllegalStateException(); }
Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise
public Ambulance(){ super(); }
Needed by CGLib
public PRLoad(float weight,float[] bucketReadLoads,float[] bucketWriteLoads){ this.weight=weight; this.bucketReadLoads=bucketReadLoads; this.bucketWriteLoads=bucketWriteLoads; }
Constructs a new PRLoad. The bucket read and writes loads are backed by the provided arrays which will be owned and potentially modified by this instance.
void removeComponentImplNoAnimationSafety(Component cmp){ Form parentForm=cmp.getComponentForm(); layout.removeLayoutComponent(cmp); cmp.setParent(this); cmp.deinitializeImpl(); components.remove(cmp); cmp.setParent(null); if (parentForm != null) { if (parentForm.getFocused() == cmp || cmp instanceof Container && ((Container)cmp).contains(parentForm.getFocused())) { parentForm.setFocused(null); } Component dragged=parentForm.getDraggedComponent(); if (dragged == cmp) { parentForm.setDraggedComponent(null); } if (cmp.isSmoothScrolling()) { parentForm.deregisterAnimatedInternal(cmp); } } cmp.cancelRepaints(); if (cmp instanceof Form) { cmp.setVisible(false); } setShouldCalcPreferredSize(true); Display.impl.componentRemoved(cmp); }
removes a Component from the Container
public static String serialize(GPathResult node){ return serialize(asString(node)); }
Return a pretty version of the GPathResult.
@Override public void retry(VolleyError error) throws VolleyError { mCurrentRetryCount++; mCurrentTimeoutMs+=(mCurrentTimeoutMs * mBackoffMultiplier); if (!hasAttemptRemaining()) { throw error; } }
Prepares for the next retry by applying a backoff to the timeout.
public TIntByteHash(int initialCapacity,float loadFactor){ super(initialCapacity,loadFactor); no_entry_key=(int)0; no_entry_value=(byte)0; }
Creates a new <code>TIntByteHash</code> instance with a prime value at or near the specified capacity and load factor.
public void add(Object o){ synchronized (_queue) { _queue.addElement(o); _queue.notify(); } }
Adds an Object to the end of the Queue.
private int calculateLeft(View child,boolean duringLayout){ int mWidth=duringLayout ? getMeasuredWidth() : getWidth(); int childWidth=duringLayout ? child.getMeasuredWidth() : child.getWidth(); int childLeft=0; switch (mGravity) { case Gravity.LEFT: childLeft=mSpinnerPadding.left; break; case Gravity.CENTER_HORIZONTAL: int availableSpace=mWidth - mSpinnerPadding.right - mSpinnerPadding.left- childWidth; childLeft=mSpinnerPadding.left + (availableSpace / 2); break; case Gravity.RIGHT: childLeft=mWidth - mSpinnerPadding.right - childWidth; break; } return childLeft; }
Figure out horizontal placement based on mGravity
private KeySelectorResult certSelect(X509Certificate xcert,SignatureMethod sm) throws KeyStoreException { boolean[] keyUsage=xcert.getKeyUsage(); if (keyUsage != null && keyUsage[0] == false) { return null; } String alias=ks.getCertificateAlias(xcert); if (alias != null) { PublicKey pk=ks.getCertificate(alias).getPublicKey(); if (algEquals(sm.getAlgorithm(),pk.getAlgorithm())) { return new SimpleKeySelectorResult(pk); } } return null; }
Searches the specified keystore for a certificate that matches the specified X509Certificate and contains a public key that is compatible with the specified SignatureMethod.
public void ancestorRemoved(final AncestorEvent event){ }
If the JRootPane was removed from the window we should clear the screen menu bar. That's a non-trivial problem, because you need to know which window the JRootPane was in before it was removed. By the time ancestorRemoved was called, the JRootPane has already been removed
private LoadBalancedConnectionProxy(List<String> hosts,Properties props) throws SQLException { super(); String group=props.getProperty("loadBalanceConnectionGroup",null); boolean enableJMX=false; String enableJMXAsString=props.getProperty("loadBalanceEnableJMX","false"); try { enableJMX=Boolean.parseBoolean(enableJMXAsString); } catch ( Exception e) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForLoadBalanceEnableJMX",new Object[]{enableJMXAsString}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } if (group != null) { this.connectionGroup=ConnectionGroupManager.getConnectionGroupInstance(group); if (enableJMX) { ConnectionGroupManager.registerJmx(); } this.connectionGroupProxyID=this.connectionGroup.registerConnectionProxy(this,hosts); hosts=new ArrayList<String>(this.connectionGroup.getInitialHosts()); } int numHosts=initializeHostsSpecs(hosts,props); this.liveConnections=new HashMap<String,ConnectionImpl>(numHosts); this.hostsToListIndexMap=new HashMap<String,Integer>(numHosts); for (int i=0; i < numHosts; i++) { this.hostsToListIndexMap.put(this.hostList.get(i),i); } this.connectionsToHostsMap=new HashMap<ConnectionImpl,String>(numHosts); this.responseTimes=new long[numHosts]; String retriesAllDownAsString=this.localProps.getProperty("retriesAllDown","120"); try { this.retriesAllDown=Integer.parseInt(retriesAllDownAsString); } catch ( NumberFormatException nfe) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForRetriesAllDown",new Object[]{retriesAllDownAsString}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } String blacklistTimeoutAsString=this.localProps.getProperty(BLACKLIST_TIMEOUT_PROPERTY_KEY,"0"); try { this.globalBlacklistTimeout=Integer.parseInt(blacklistTimeoutAsString); } catch ( NumberFormatException nfe) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForLoadBalanceBlacklistTimeout",new Object[]{blacklistTimeoutAsString}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } String hostRemovalGracePeriodAsString=this.localProps.getProperty(HOST_REMOVAL_GRACE_PERIOD_PROPERTY_KEY,"15000"); try { this.hostRemovalGracePeriod=Integer.parseInt(hostRemovalGracePeriodAsString); } catch ( NumberFormatException nfe) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForLoadBalanceHostRemovalGracePeriod",new Object[]{hostRemovalGracePeriodAsString}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } String strategy=this.localProps.getProperty("loadBalanceStrategy","random"); if ("random".equals(strategy)) { this.balancer=(BalanceStrategy)Util.loadExtensions(null,props,"com.mysql.jdbc.RandomBalanceStrategy","InvalidLoadBalanceStrategy",null).get(0); } else if ("bestResponseTime".equals(strategy)) { this.balancer=(BalanceStrategy)Util.loadExtensions(null,props,"com.mysql.jdbc.BestResponseTimeBalanceStrategy","InvalidLoadBalanceStrategy",null).get(0); } else { this.balancer=(BalanceStrategy)Util.loadExtensions(null,props,strategy,"InvalidLoadBalanceStrategy",null).get(0); } String autoCommitSwapThresholdAsString=props.getProperty("loadBalanceAutoCommitStatementThreshold","0"); try { this.autoCommitSwapThreshold=Integer.parseInt(autoCommitSwapThresholdAsString); } catch ( NumberFormatException nfe) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForLoadBalanceAutoCommitStatementThreshold",new Object[]{autoCommitSwapThresholdAsString}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } String autoCommitSwapRegex=props.getProperty("loadBalanceAutoCommitStatementRegex",""); if (!("".equals(autoCommitSwapRegex))) { try { "".matches(autoCommitSwapRegex); } catch ( Exception e) { throw SQLError.createSQLException(Messages.getString("LoadBalancedConnectionProxy.badValueForLoadBalanceAutoCommitStatementRegex",new Object[]{autoCommitSwapRegex}),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,null); } } if (this.autoCommitSwapThreshold > 0) { String statementInterceptors=this.localProps.getProperty("statementInterceptors"); if (statementInterceptors == null) { this.localProps.setProperty("statementInterceptors","com.mysql.jdbc.LoadBalancedAutoCommitInterceptor"); } else if (statementInterceptors.length() > 0) { this.localProps.setProperty("statementInterceptors",statementInterceptors + ",com.mysql.jdbc.LoadBalancedAutoCommitInterceptor"); } props.setProperty("statementInterceptors",this.localProps.getProperty("statementInterceptors")); } this.balancer.init(null,props); String lbExceptionChecker=this.localProps.getProperty("loadBalanceExceptionChecker","com.mysql.jdbc.StandardLoadBalanceExceptionChecker"); this.exceptionChecker=(LoadBalanceExceptionChecker)Util.loadExtensions(null,props,lbExceptionChecker,"InvalidLoadBalanceExceptionChecker",null).get(0); pickNewConnection(); }
Creates a proxy for java.sql.Connection that routes requests between the given list of host:port and uses the given properties when creating connections.
public void visitMethodInsn(int opcode,String owner,String name,String desc,boolean itf){ if (api < Opcodes.ASM5) { if (itf != (opcode == Opcodes.INVOKEINTERFACE)) { throw new IllegalArgumentException("INVOKESPECIAL/STATIC on interfaces require ASM 5"); } visitMethodInsn(opcode,owner,name,desc); return; } if (mv != null) { mv.visitMethodInsn(opcode,owner,name,desc,itf); } }
Visits a method instruction. A method instruction is an instruction that invokes a method.
public static void printSummary(PrintStream out){ printSummary(out,null); printErrorSummary(out); }
Print the statistics report to specified stream
public boolean replyToMessage(String quickReply){ setMessageRead(); SmsMessageSender sender=new SmsMessageSender(context,new String[]{fromAddress},quickReply,getThreadId()); return sender.sendMessage(); }
Send a reply to this message
public void unsetMatchColumn(int[] columnIdxes) throws SQLException { int i_val; for (int j=0; j < columnIdxes.length; j++) { i_val=(Integer.parseInt(iMatchColumns.get(j).toString())); if (columnIdxes[j] != i_val) { throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols").toString()); } } for (int i=0; i < columnIdxes.length; i++) { iMatchColumns.set(i,Integer.valueOf(-1)); } }
Unsets the designated parameter to the given int array. This was set using <code>setMatchColumn</code> as the column which will form the basis of the join. <P> The parameter value unset by this method should be same as was set.
public int push(int i){ if ((m_firstFree + 1) >= m_mapSize) { m_mapSize+=m_blocksize; int newMap[]=new int[m_mapSize]; System.arraycopy(m_map,0,newMap,0,m_firstFree + 1); m_map=newMap; } m_map[m_firstFree]=i; m_firstFree++; return i; }
Pushes an item onto the top of this stack.
public final static void writeUnescapedXML(Writer out,String tag,String val,Object... attrs) throws IOException { out.write('<'); out.write(tag); for (int i=0; i < attrs.length; i++) { out.write(' '); out.write(attrs[i++].toString()); out.write('='); out.write('"'); out.write(attrs[i].toString()); out.write('"'); } if (val == null) { out.write('/'); out.write('>'); } else { out.write('>'); out.write(val); out.write('<'); out.write('/'); out.write(tag); out.write('>'); } }
does NOT escape character data in val, must already be valid XML
public static void generateRPClass(String ATTR_TITLE){ final RPClass entity=new RPClass("rpentity"); entity.isA("active_entity"); entity.addAttribute("name",Type.STRING); entity.addAttribute(ATTR_TITLE,Type.STRING); entity.addAttribute("level",Type.SHORT); entity.addAttribute("xp",Type.INT); entity.addAttribute("mana",Type.INT); entity.addAttribute("base_mana",Type.INT); entity.addAttribute("base_hp",Type.SHORT); entity.addAttribute("hp",Type.SHORT); entity.addAttribute("atk",Type.SHORT,Definition.PRIVATE); entity.addAttribute("atk_xp",Type.INT,Definition.PRIVATE); entity.addAttribute("atk_item",Type.INT,(byte)(Definition.PRIVATE | Definition.VOLATILE)); entity.addAttribute("def",Type.SHORT,Definition.PRIVATE); entity.addAttribute("def_xp",Type.INT,Definition.PRIVATE); entity.addAttribute("def_item",Type.INT,(byte)(Definition.PRIVATE | Definition.VOLATILE)); if (Testing.COMBAT) { entity.addAttribute("ratk",Type.SHORT,(byte)(Definition.PRIVATE | Definition.VOLATILE)); entity.addAttribute("ratk_xp",Type.INT,(byte)(Definition.PRIVATE | Definition.VOLATILE)); entity.addAttribute("ratk_item",Type.INT,(byte)(Definition.PRIVATE | Definition.VOLATILE)); } entity.addAttribute("risk",Type.BYTE,Definition.VOLATILE); entity.addAttribute("damage",Type.INT,Definition.VOLATILE); entity.addAttribute("heal",Type.INT,Definition.VOLATILE); entity.addAttribute("target",Type.INT,Definition.VOLATILE); entity.addAttribute("title_type",Type.STRING,Definition.VOLATILE); entity.addAttribute("base_speed",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("ignore_collision",Type.FLAG,Definition.VOLATILE); entity.addAttribute("unnamed",Type.FLAG,Definition.VOLATILE); entity.addAttribute("no_hpbar",Type.FLAG,Definition.VOLATILE); entity.addAttribute("job_merchant",Type.FLAG,Definition.VOLATILE); entity.addAttribute("job_healer",Type.FLAG,Definition.VOLATILE); entity.addAttribute("choking",Type.SHORT,Definition.VOLATILE); entity.addAttribute("status_confuse",Type.SHORT,Definition.VOLATILE); entity.addAttribute("eating",Type.SHORT,Definition.VOLATILE); entity.addAttribute("poisoned",Type.SHORT,Definition.VOLATILE); entity.addAttribute("status_shock",Type.SHORT,Definition.VOLATILE); entity.addAttribute("status_zombie",Type.SHORT,Definition.VOLATILE); entity.addAttribute("status_heavy",Type.SHORT,Definition.VOLATILE); entity.addAttribute("resist_confused",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("resist_drunk",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("resist_heavy",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("resist_poisoned",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("resist_shocked",Type.FLOAT,Definition.VOLATILE); entity.addAttribute("resist_zombie",Type.FLOAT,Definition.VOLATILE); entity.addAttribute(PATHSET,Type.STRING,Definition.VOLATILE); entity.addRPSlot("head",1,Definition.PRIVATE); entity.addRPSlot("rhand",1,Definition.PRIVATE); entity.addRPSlot("lhand",1,Definition.PRIVATE); entity.addRPSlot("armor",1,Definition.PRIVATE); entity.addRPSlot("finger",1,Definition.PRIVATE); entity.addRPSlot("cloak",1,Definition.PRIVATE); entity.addRPSlot("legs",1,Definition.PRIVATE); entity.addRPSlot("feet",1,Definition.PRIVATE); entity.addRPSlot("back",1,Definition.PRIVATE); entity.addRPSlot("belt",1,Definition.PRIVATE); entity.addRPSlot("bag",12,Definition.PRIVATE); entity.addRPSlot("keyring",8,Definition.PRIVATE); entity.addRPEvent("attack",Definition.VOLATILE); }
Generates the RPClass and specifies slots and attributes.
@DELETE @Path(PathParameters.TENANT_NAME_VAR) @RequiresRole(role=Role.ADMINISTRATOR) public void delete(@PathParam(PathParameters.TENANT_NAME) String tenantName){ try { getIDMClient().deleteTenant(tenantName); } catch ( NoSuchTenantException e) { log.debug("Failed to delete tenant '{}'",tenantName,e); throw new NotFoundException(sm.getString("ec.404"),e); } catch ( InvalidArgumentException e) { log.error("Failed to delete tenant '{}' due to a client side error",tenantName,e); throw new BadRequestException(sm.getString("res.ten.delete.failed",tenantName),e); } catch ( Exception e) { log.error("Failed to delete tenant '{}' due to a server side error",tenantName,e); throw new InternalServerErrorException(sm.getString("ec.500"),e); } }
Delete a tenant
private void startForegroundCompat(int id,Notification notification){ if (mStartForeground != null) { try { mStartForeground.invoke(this,Integer.valueOf(id),notification); } catch ( InvocationTargetException e) { L.d("Unable to invoke startForeground"); } catch ( IllegalAccessException e) { L.d("Unable to invoke startForeground"); } return; } if (mSetForeground != null) { try { mSetForeground.invoke(this,Boolean.TRUE); } catch ( IllegalAccessException e) { L.d("Unable to invoke setForeground"); } catch ( InvocationTargetException e) { L.d("Unable to invoke setForeground"); } } mNM.notify(id,notification); }
This is a wrapper around the new startForeground method, using the older APIs if it is not available.
public MemcacheClientBuilder<V> withAddress(HostAndPort address){ this.addresses=ImmutableList.of(address); return this; }
Define which memcache server to connect to.
public float value(){ return _map._values[_index]; }
Provides access to the value of the mapping at the iterator's position. Note that you must <tt>advance()</tt> the iterator at least once before invoking this method.
public PropertyChangeListenerProxy(String propertyName,PropertyChangeListener listener){ super(listener); this.propertyName=propertyName; }
Creates a new listener proxy that associates a listener with a property name.
public static Snapshot generateStatistics(String outDir,Manager manager) throws SQLException, IOException, MitroServletException { final long runTimestampMs=System.currentTimeMillis(); Snapshot output=new Snapshot(); Multimap<Integer,Link> countToFile=TreeMultimap.create(Ordering.natural().reverse(),Ordering.natural()); Map<Integer,GroupInfo> orgIdToOrg=Maps.newHashMap(); for ( DBGroup o : DBGroup.getAllOrganizations(manager)) { GroupInfo newGi=new GroupInfo(); newGi.autoDelete=o.isAutoDelete(); newGi.groupId=o.getId(); newGi.isTopLevelOrg=true; newGi.name=o.getName(); Set<String> users=Sets.newHashSet(); for ( DBGroup orgGroup : o.getAllOrgGroups(manager)) { users.add(orgGroup.getName()); } newGi.users=Lists.newArrayList(users); orgIdToOrg.put(newGi.groupId,newGi); } int numPeople=0; for ( DBIdentity id : manager.identityDao.queryForAll()) { ++numPeople; try { logger.info(id.getName() + ": " + id.getGuidCookie()); DBHistoricalUserState userState=getHistoricalUserState(manager,runTimestampMs,orgIdToOrg,id); output.userStateObjects.add(userState); String filename=id.getName() + ".html"; renderIfOutputEnabled(outDir,"/users/" + filename,userStateTemplate,userState); countToFile.put(userState.numSecrets,new Link(id.getName(),filename,userState.numSecrets)); } catch ( MitroServletException e) { logger.error("UNKNOWN ERROR",e); } } renderIfOutputEnabled(outDir,"/users/index.html",indexTemplate,countToFile.values()); countToFile.clear(); int numOrgs=0; for ( DBGroup org : DBGroup.getAllOrganizations(manager)) { ++numOrgs; Set<Integer> admins=Sets.newHashSet(); org.putDirectUsersIntoSet(admins,DBAcl.adminAccess()); int userId=admins.iterator().next(); DBIdentity dbi=manager.identityDao.queryForId(userId); MitroRequestContext context=new MitroRequestContext(dbi,null,manager,null); GetOrganizationStateResponse resp=GetOrganizationState.doOperation(context,org.getId()); DBHistoricalOrgState orgState=new DBHistoricalOrgState(resp,org.getId(),runTimestampMs); output.orgStateObjects.add(orgState); String filename=org.getId() + ".html"; renderIfOutputEnabled(outDir,"/orgs/" + filename,orgStateTemplate,orgState); countToFile.put(orgState.numMembers + orgState.numAdmins,new Link(org.getName() + org.getId(),org.getId() + ".html",orgState.numAdmins + orgState.numMembers)); } renderIfOutputEnabled(outDir,"/orgs/index.html",indexTemplate,countToFile.values()); renderIfOutputEnabled(outDir,"/index.html",indexTemplate,ImmutableList.of(new Link("organizations","orgs/index.html",numOrgs),new Link("users","users/index.html",numPeople))); return output; }
Generate statistics and return newly created objects that have not been committed.
public boolean isExtended(){ return this.isExtended; }
Returns whether this completion context is an extended context. Some methods of this context can be used only if this context is an extended context but an extended context consumes more memory.
public void put(double[] data){ final int l=data.length; for (int i=0; i < l; i++) { final double val=data[i]; min=val < min ? val : min; max=val > max ? val : max; } }
Process a whole array of double values. If any of the values is smaller than the current minimum, it will become the new minimum. If any of the values is larger than the current maximum, it will become the new maximum.
public RC6Engine(){ _S=null; }
Create an instance of the RC6 encryption algorithm and set some defaults
public void updateAfkStatus(){ purgeNotOnline(); final AFKConfig config=aca.getNodeOrDefault(); long afkTime=config.getAfkTime(); long afkTimeKick=config.getAfkTimeToKick(); Instant now=Instant.now(); CommandPermissionHandler cph=getPermissionUtil(); if (afkTime > 0) { workOnAfkPlayers(now.minus(afkTime,ChronoUnit.SECONDS),cph,exempttoggle,null,null); } if (afkTimeKick > 0) { workOnAfkPlayers(now.minus(afkTimeKick,ChronoUnit.SECONDS),cph,exemptkick,null,null); } }
Updates all players' AFK status if they are inactive.