code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@Inline private static void genNullCheck(Assembler asm,GPR objRefReg){
asm.emitTEST_Reg_Reg(objRefReg,objRefReg);
asm.emitBranchLikelyNextInstruction();
ForwardReference fr=asm.forwardJcc(NE);
asm.emitINT_Imm(RuntimeEntrypoints.TRAP_NULL_POINTER + RVM_TRAP_BASE);
fr.resolve(asm);
}
| Generate an explicit null check (compare to zero). |
public Location(String provider){
mProvider=provider;
}
| Construct a new Location with a named provider. <p>By default time, latitude and longitude are 0, and the location has no bearing, altitude, speed, accuracy or extras. |
@Override public void run(){
amIActive=true;
String demHeader=null;
String creekHeader=null;
String ttControlHeader=null;
String eacOutputHeader=null;
String dfcOutputHeader=null;
String gtcOutputHeader=null;
String ttpOutputHeader=null;
WhiteboxRaster dem;
WhiteboxRaster creek;
WhiteboxRaster ttControl=null;
WhiteboxRaster eacOutput;
WhiteboxRaster dfcOutput;
WhiteboxRaster gtcOutput;
WhiteboxRaster ttpOutput;
int numCols, numRows;
double gridRes;
boolean blnTTControl=true;
int flowIndex;
List<FlowCell> flowPath=new ArrayList<>();
int c;
int x, y;
int xn, yn;
double p;
int maxDirection;
double grad, maxGrad;
double deltaElev;
double deltaXY;
int radius;
float maxRadius=200;
int maxX=0, maxY=0;
double ttControlMean;
int[] xd=new int[]{0,-1,-1,-1,0,1,1,1};
int[] yd=new int[]{-1,-1,0,1,1,1,0,-1};
double[] dd=new double[]{1,Math.sqrt(2),1,Math.sqrt(2),1,Math.sqrt(2),1,Math.sqrt(2)};
double noData;
float progress=0;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (int i=0; i < args.length; i++) {
if (i == 0) {
demHeader=args[i];
}
else if (i == 1) {
creekHeader=args[i];
}
else if (i == 2) {
ttControlHeader=args[i];
if (ttControlHeader.toLowerCase().contains("not specified")) {
blnTTControl=false;
}
}
else if (i == 3) {
eacOutputHeader=args[i];
}
else if (i == 4) {
dfcOutputHeader=args[i];
}
else if (i == 5) {
gtcOutputHeader=args[i];
}
else if (i == 6) {
ttpOutputHeader=args[i];
}
}
if ((demHeader == null) || (creekHeader == null) || (eacOutputHeader == null)|| (dfcOutputHeader == null)|| (gtcOutputHeader == null)|| (ttpOutputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
dem=new WhiteboxRaster(demHeader,"r");
creek=new WhiteboxRaster(creekHeader,"r");
if (blnTTControl == true) {
ttControl=new WhiteboxRaster(ttControlHeader,"r");
}
numRows=dem.getNumberRows();
numCols=dem.getNumberColumns();
noData=dem.getNoDataValue();
gridRes=dem.getCellSizeX();
eacOutput=new WhiteboxRaster(eacOutputHeader,"rw",demHeader,WhiteboxRaster.DataType.FLOAT,0);
eacOutput.setPreferredPalette("blueyellow.pal");
eacOutput.setDataScale(WhiteboxRasterBase.DataScale.CONTINUOUS);
eacOutput.setZUnits("dimensionless");
dfcOutput=new WhiteboxRaster(dfcOutputHeader,"rw",demHeader,WhiteboxRaster.DataType.FLOAT,0);
dfcOutput.setPreferredPalette("blueyellow.pal");
dfcOutput.setDataScale(WhiteboxRasterBase.DataScale.CONTINUOUS);
dfcOutput.setZUnits("dimensionless");
gtcOutput=new WhiteboxRaster(gtcOutputHeader,"rw",demHeader,WhiteboxRaster.DataType.FLOAT,0);
gtcOutput.setPreferredPalette("blueyellow.pal");
gtcOutput.setDataScale(WhiteboxRasterBase.DataScale.CONTINUOUS);
gtcOutput.setZUnits("dimensionless");
ttpOutput=new WhiteboxRaster(ttpOutputHeader,"rw",demHeader,WhiteboxRaster.DataType.FLOAT,0);
ttpOutput.setPreferredPalette("blueyellow.pal");
ttpOutput.setDataScale(WhiteboxRasterBase.DataScale.CONTINUOUS);
ttpOutput.setZUnits("dimensionless");
updateProgress("Loop 1 of 2:",0);
for (int row=0; row < numRows; row++) {
for (int col=0; col < numCols; col++) {
if (dem.getValue(row,col) != noData) {
if (creek.getValue(row,col) <= 0) {
eacOutput.setValue(row,col,-1048);
}
}
else {
eacOutput.setValue(row,col,noData);
dfcOutput.setValue(row,col,noData);
gtcOutput.setValue(row,col,noData);
ttpOutput.setValue(row,col,noData);
}
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 1 of 2:",(int)progress);
}
updateProgress("Loop 2 of 2:",0);
for (int row=0; row < numRows; row++) {
for (int col=0; col < numCols; col++) {
if (eacOutput.getValue(row,col) == -1048) {
flowIndex=-1;
flowPath=new ArrayList<>();
x=col;
y=row;
while (eacOutput.getValue(y,x) == -1048) {
flowIndex=flowIndex + 1;
flowPath.add(new FlowCell(y,x));
p=dem.getValue(y,x);
maxDirection=-1;
maxGrad=0;
for (c=0; c < 8; c++) {
xn=x + xd[c];
yn=y + yd[c];
if (dem.getValue(yn,xn) != noData) {
grad=(p - dem.getValue(yn,xn)) / (dd[c] * gridRes);
if (grad > maxGrad) {
maxGrad=grad;
maxDirection=c;
}
}
}
if (maxDirection > -1) {
x=x + xd[maxDirection];
y=y + yd[maxDirection];
}
else {
radius=1;
do {
for (int i=-radius; i <= radius; i++) {
for (int j=-radius; j <= radius; j++) {
if (Math.abs(i) > radius - 1 || Math.abs(j) > radius - 1) {
xn=x + i;
yn=y + j;
if (dem.getValue(yn,xn) != noData && dem.getValue(yn,xn) < p) {
grad=(p - dem.getValue(yn,xn)) / (Math.sqrt(i * i + j * j) * gridRes);
if (grad > maxGrad) {
maxGrad=grad;
maxX=xn;
maxY=yn;
}
}
}
}
}
radius=radius + 1;
}
while (maxGrad == 0 & radius <= maxRadius);
if (maxGrad > 0) {
x=maxX;
y=maxY;
}
else {
eacOutput.setValue(y,x,noData);
dfcOutput.setValue(y,x,noData);
gtcOutput.setValue(y,x,noData);
ttpOutput.setValue(y,x,noData);
}
}
}
if (eacOutput.getValue(y,x) == noData) {
eacOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,noData);
dfcOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,noData);
gtcOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,noData);
ttpOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,noData);
}
else {
deltaElev=dem.getValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex) - dem.getValue(y,x);
deltaXY=Math.sqrt(Math.pow(flowPath.get(flowIndex).rowIndex - y,2) + Math.pow(flowPath.get(flowIndex).columnIndex - x,2)) * gridRes;
eacOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,eacOutput.getValue(y,x) + deltaElev);
dfcOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,dfcOutput.getValue(y,x) + deltaXY);
gtcOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,(gtcOutput.getValue(y,x) * dfcOutput.getValue(y,x) + deltaElev) / dfcOutput.getValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex));
if (blnTTControl == false) {
ttpOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,ttpOutput.getValue(y,x) + Math.pow(deltaXY,2) / deltaElev);
}
else {
ttControlMean=(ttControl.getValue(y,x) + ttControl.getValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex)) / 2;
ttpOutput.setValue(flowPath.get(flowIndex).rowIndex,flowPath.get(flowIndex).columnIndex,ttpOutput.getValue(y,x) + Math.pow(deltaXY,2) / (deltaElev * ttControlMean));
}
}
for (int i=flowIndex - 1; i >= 0; i--) {
if (eacOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) == noData) {
eacOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,noData);
dfcOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,noData);
gtcOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,noData);
ttpOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,noData);
}
else {
deltaElev=dem.getValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex) - dem.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex);
deltaXY=Math.sqrt(Math.pow(flowPath.get(i).rowIndex - flowPath.get(i + 1).rowIndex,2) + Math.pow(flowPath.get(i).columnIndex - flowPath.get(i + 1).columnIndex,2)) * gridRes;
eacOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,eacOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) + deltaElev);
dfcOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,dfcOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) + deltaXY);
gtcOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,(gtcOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) * dfcOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) + deltaElev) / dfcOutput.getValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex));
if (blnTTControl == false) {
ttpOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,ttpOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) + Math.pow(deltaXY,2) / deltaElev);
}
else {
ttControlMean=(ttControl.getValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex) + ttControl.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex)) / 2;
ttpOutput.setValue(flowPath.get(i).rowIndex,flowPath.get(i).columnIndex,ttpOutput.getValue(flowPath.get(i + 1).rowIndex,flowPath.get(i + 1).columnIndex) + Math.pow(deltaXY,2) / (deltaElev * ttControlMean));
}
}
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 2 of 2:",(int)progress);
}
eacOutput.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
eacOutput.addMetadataEntry("Created on " + new Date());
dfcOutput.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
dfcOutput.addMetadataEntry("Created on " + new Date());
gtcOutput.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
gtcOutput.addMetadataEntry("Created on " + new Date());
ttpOutput.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
ttpOutput.addMetadataEntry("Created on " + new Date());
dem.close();
creek.close();
if (blnTTControl == true) {
ttControl.close();
}
eacOutput.close();
dfcOutput.close();
gtcOutput.close();
ttpOutput.close();
returnData(eacOutputHeader);
}
catch ( Exception e) {
showFeedback(e.getMessage());
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public NodesInfoRequest(String... nodesIds){
super(nodesIds);
}
| Get information from nodes based on the nodes ids specified. If none are passed, information for all nodes will be returned. |
public static double norm(double[] a){
double squaredSum=0;
for (int i=0; i < a.length; i++) {
squaredSum+=a[i] * a[i];
}
return Math.sqrt(squaredSum);
}
| Computes 2-norm of vector |
private static double[] toDoubleAray(Integer[] intArray,HashSet<Integer> skipIndex){
double[] res=new double[intArray.length - skipIndex.size()];
int skip=0;
for (int i=0; i < intArray.length; i++) {
if (skipIndex.contains(i)) {
skip++;
continue;
}
res[i - skip]=intArray[i].doubleValue();
}
return res;
}
| Converts an array into array of doubles skipping specified indeces. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public CompositeValidationIssueProcessor(final IValidationIssueProcessor first,final IValidationIssueProcessor... others){
processors=Lists.asList(first,others);
}
| Creates a new composite issue processor with the given sub processor arguments. |
public OptionSet removeMaxAge(){
max_age=null;
return this;
}
| Removes the Max-Age option. Returns the current OptionSet object for a fluent API. |
public Request(){
locality="";
state="";
organization="";
orgunit="";
dnsname="";
uri="";
email="";
ipaddress="";
keyusage=0;
}
| Ctor for the Request Object |
@Override protected Position determineMainLabelPosition(DrawContext dc){
return this.getReferencePosition();
}
| Compute the position for the area's main label. This position indicates the position of the first line of the label. If there are more lines, they will be arranged South of the first line. |
@Override Map<String,Object> extractFields(String line){
if (!initialized) {
init();
initialized=true;
}
String[] values=fixedWidthParser.parseLine(line);
if (hasHeader && Arrays.deepEquals(values,header)) {
return null;
}
Map<String,Object> map=Maps.newHashMap();
int i=0;
for ( FixedWidthField field : fields) {
map.put(field.getName(),getValue(field,values[i++]));
}
return map;
}
| Extracts the fields from a fixed width record and returns a map containing field names and values |
@Override public boolean contains(Value subvalue){
return toString().contains(subvalue.toString());
}
| Returns true if the value is contained in the relation structure. (this is done |
private void applyTo(ClassVisitor v,Field f){
if (Log.isLoggingOn()) {
Log.logLine(String.format("Visiting field %s",f.toGenericString()));
}
v.visit(f);
}
| Apply a visitor to a field. |
@Override protected EClass eStaticClass(){
return ExpressionsPackage.Literals.BITWISE_AND_EXPRESSION;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public final void closePath(){
shape_primitives.addElement(H);
shape_primitive_x.addElement(0);
shape_primitive_y.addElement(0);
shape_primitive_x2.addElement(0);
shape_primitive_y2.addElement(0);
shape_primitive_x3.addElement(0);
shape_primitive_y3.addElement(0);
}
| end a shape, storing info for later |
public DefaultBoundValueOperations(K key,RedisOperations<K,V> operations){
super(key,operations);
this.ops=operations.opsForValue();
}
| Constructs a new <code>DefaultBoundValueOperations</code> instance. |
@Override public void writeBatch() throws IOException {
if (getInstances() == null) {
throw new IOException("No instances to save");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(BATCH);
setWriteMode(WRITE);
if ((retrieveFile() == null) && (getWriter() == null)) {
for (int i=0; i < getInstances().numInstances(); i++) {
System.out.println(instanceToLibsvm(getInstances().instance(i)));
}
setWriteMode(WAIT);
}
else {
PrintWriter outW=new PrintWriter(getWriter());
for (int i=0; i < getInstances().numInstances(); i++) {
outW.println(instanceToLibsvm(getInstances().instance(i)));
}
outW.flush();
outW.close();
setWriteMode(WAIT);
outW=null;
resetWriter();
setWriteMode(CANCEL);
}
}
| Writes a Batch of instances |
public FloatMatrix truthi(){
for (int i=0; i < length; i++) {
put(i,get(i) == 0.0f ? 0.0f : 1.0f);
}
return this;
}
| Maps zero to 0.0 and all non-zero values to 1.0 (in-place). |
public void testCallProcEscapeSequenceWithWhitespaces() throws Exception {
check("CALL func1()","{ call func1()}");
check("CALL func1()","{ call func1()}");
check("CALL func1()","{ \n call\nfunc1()}");
checkFail("{ \n func1()}");
}
| Test escape sequences with additional whitespace characters |
public EnumRowStatus(Long valueIndex) throws IllegalArgumentException {
this(valueIndex.longValue());
}
| Build an <code>EnumRowStatus</code> from a <code>Long</code>. |
private void generateOps708(char[][] screenData,long[][] screenCellData,java.awt.geom.Rectangle2D.Float clipRect,float alphaFactor,float xoff,float yoff,float rowHeight,float currY,float charWidth,float currX){
if (reality.isIntegerPixels()) currY=(float)Math.floor(currY);
StringBuffer sb=new StringBuffer();
printCCBuffer("708 CCData to render",screenData,sb,screenCellData,new StringBuffer());
sb.setLength(0);
for (int row=0; row < sage.media.sub.CCSubtitleHandler.CC_ROWS && screenData != null; row++) {
long lastCellFormat=screenCellData[row][0];
if (CellFormat.getBackgroundOpacity(lastCellFormat) == DTVCCOpacity.TRANSPARENT && screenData[row][0] == 0) {
lastCellFormat=CellFormat.setForeground(lastCellFormat,(byte)CellFormat.getForeground(lastCellFormat),DTVCCOpacity.TRANSPARENT);
}
rowOffsets[row]=-1;
float rowStartY=rowHeight * row;
float textOffset=charWidth;
int maxCols=screenCellData[row].length - 1;
int lastRenderedCol=-1;
for (int col=0; col < maxCols; col++) {
if (lastCellFormat != screenCellData[row][col]) {
int windowID=CellFormat.getWindowID(lastCellFormat);
if ((CellFormat.getForegroundOpacity(lastCellFormat) != DTVCCOpacity.TRANSPARENT || CellFormat.getBackgroundOpacity(lastCellFormat) != DTVCCOpacity.TRANSPARENT)) {
textOffset+=render708ops(screenData,screenCellData,clipRect,alphaFactor,xoff,yoff,rowHeight,currY,charWidth,currX,sb,lastCellFormat,rowStartY,textOffset,lastRenderedCol,row,col);
lastRenderedCol=col - 1;
}
else {
addTo708WindowRect(windowID,xoff + currX + textOffset,yoff + rowStartY,sb.length() * charWidth,rowHeight);
textOffset+=sb.length() * charWidth;
}
sb.setLength(0);
}
lastCellFormat=screenCellData[row][col];
if (CellFormat.getBackgroundOpacity(lastCellFormat) == DTVCCOpacity.TRANSPARENT && screenData[row][col] == 0) {
lastCellFormat=CellFormat.setForeground(lastCellFormat,(byte)CellFormat.getForeground(lastCellFormat),DTVCCOpacity.TRANSPARENT);
}
if (CellFormat.getBackgroundOpacity(lastCellFormat) == DTVCCOpacity.TRANSPARENT && (CellFormat.getForegroundOpacity(lastCellFormat) == DTVCCOpacity.TRANSPARENT || screenData[row][col] == 0)) {
textOffset+=charWidth;
}
else if (screenData[row][col] != 0) {
if (rowOffsets[row] == -1) {
rowOffsets[row]=col;
}
sb.append(screenData[row][col]);
}
else {
sb.append(' ');
}
}
if (sb.length() > 0) {
if (CellFormat.getForegroundOpacity(lastCellFormat) != DTVCCOpacity.TRANSPARENT || CellFormat.getBackgroundOpacity(lastCellFormat) != DTVCCOpacity.TRANSPARENT) {
render708ops(screenData,screenCellData,clipRect,alphaFactor,xoff,yoff,rowHeight,currY,charWidth,currX,sb,lastCellFormat,rowStartY,textOffset,lastRenderedCol,row,maxCols);
}
}
sb.setLength(0);
}
for ( List<RenderingOp> ops : cached708WindowOps) {
cachedRenderOps.addAll(ops);
}
}
| Render the 708 caption text to the screen. BIG NOTE(codefu): This wont draw perfectly square boxes with text on it. e.g.: back-filled with black, 2 rows, 32 columns. Text on second row "testing" will produce and image that is stepped. If we want to draw squares, we need to track the widest character from any font/size that is used. |
public static void putbytes2Uint8s(char[] destUint8s,byte[] srcBytes,int destOffset,int srcOffset,int count){
for (int i=0; i < count; i++) {
destUint8s[destOffset + i]=convertByte2Uint8(srcBytes[srcOffset + i]);
}
}
| Put byte[] into char[]( we treat char[] as uint8[]) |
public static void superposeWithAngle(ComplexVector vec1,ComplexVector vec2,float weight,int[] permutation){
int positionToAdd;
int dim=vec1.getDimension();
short c[]=vec2.getPhaseAngles();
float[] coordinates=vec1.getCoordinates();
if (permutation != null) {
for (int i=0; i < dim; i++) {
positionToAdd=permutation[i] << 1;
coordinates[positionToAdd]+=CircleLookupTable.getRealEntry(c[i]) * weight;
coordinates[positionToAdd + 1]+=CircleLookupTable.getImagEntry(c[i]) * weight;
}
}
else {
for (int i=0; i < dim; i++) {
positionToAdd=i << 1;
coordinates[positionToAdd]+=CircleLookupTable.getRealEntry(c[i]) * weight;
coordinates[positionToAdd + 1]+=CircleLookupTable.getImagEntry(c[i]) * weight;
}
}
}
| Superposes vec2 with vec1 with weight and permutation. vec1 is in CARTESIAN mode. vec2 is in POLAR mode. |
protected void _addFieldMixIns(Class<?> targetClass,Class<?> mixInCls,Map<String,AnnotatedField> fields){
List<Class<?>> parents=new ArrayList<Class<?>>();
parents.add(mixInCls);
ClassUtil.findSuperTypes(mixInCls,targetClass,parents);
for ( Class<?> mixin : parents) {
for ( Field mixinField : mixin.getDeclaredFields()) {
if (!_isIncludableField(mixinField)) {
continue;
}
String name=mixinField.getName();
AnnotatedField maskedField=fields.get(name);
if (maskedField != null) {
for ( Annotation a : mixinField.getDeclaredAnnotations()) {
if (_annotationIntrospector.isHandled(a)) {
maskedField.addOrOverride(a);
}
}
}
}
}
}
| Method called to add field mix-ins from given mix-in class (and its fields) into already collected actual fields (from introspected classes and their super-classes) |
@Override public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch=false;
}
double[] vals=new double[instance.numAttributes() + 1];
for (int i=0; i < instance.numAttributes(); i++) {
if (instance.isMissing(i)) {
vals[i]=Utils.missingValue();
}
else {
vals[i]=instance.value(i);
}
}
m_attributeExpression.evaluateExpression(vals);
Instance inst=null;
if (instance instanceof SparseInstance) {
inst=new SparseInstance(instance.weight(),vals);
}
else {
inst=new DenseInstance(instance.weight(),vals);
}
inst.setDataset(getOutputFormat());
copyValues(inst,false,instance.dataset(),getOutputFormat());
inst.setDataset(getOutputFormat());
push(inst);
return true;
}
| Input an instance for filtering. Ordinarily the instance is processed and made available for output immediately. Some filters require all instances be read before producing output. |
public String lookup(String data){
Iterator<String> it=map.getPrefixedBy(data);
if (!it.hasNext()) return null;
return it.next();
}
| Return the last String in the set that can be prefixed by this String (Trie's are stored in alphabetical order). Return null if no such String exist in the current set. |
public boolean attempt(LiveAnalysis live,Register r1,Register r2){
if (isLiveAtDef(r2,r1,live)) return false;
if (isLiveAtDef(r1,r2,live)) return false;
if (split(r1,r2)) return false;
if (r1 == r2) return false;
live.merge(r1,r2);
for (Enumeration<RegisterOperand> e=DefUse.defs(r2); e.hasMoreElements(); ) {
RegisterOperand def=e.nextElement();
DefUse.removeDef(def);
def.setRegister(r1);
DefUse.recordDef(def);
}
for (Enumeration<RegisterOperand> e=DefUse.uses(r2); e.hasMoreElements(); ) {
RegisterOperand use=e.nextElement();
DefUse.removeUse(use);
use.setRegister(r1);
DefUse.recordUse(use);
}
return true;
}
| Attempt to coalesce register r2 into register r1. If this is legal, <ul> <li> rewrite all defs and uses of r2 as defs and uses of r1 <li> update the liveness information <li> update the def-use chains </ul> <strong>PRECONDITION </strong> def-use chains must be computed and valid. |
private void registerTarget(final Message message,final String virtualHost){
final String thingId=getStringHeaderKey(message,MessageHeaderKey.THING_ID,"ThingId is null");
final String replyTo=message.getMessageProperties().getReplyTo();
if (StringUtils.isEmpty(replyTo)) {
logAndThrowMessageError(message,"No ReplyTo was set for the createThing Event.");
}
final URI amqpUri=IpUtil.createAmqpUri(virtualHost,replyTo);
final Target target=controllerManagement.findOrRegisterTargetIfItDoesNotexist(thingId,amqpUri);
LOG.debug("Target {} reported online state.",thingId);
lookIfUpdateAvailable(target);
}
| Method to create a new target or to find the target if it already exists. |
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. |
public long term(){
return term;
}
| Returns the responding node's current term. |
public void purgePlayer(Player player){
zombies.remove(player.getUniqueId());
humans.remove(player.getUniqueId());
}
| Removes the player from the current ADTs. |
public RestClient(String target,String username,String password,CloseableHttpAsyncClient asyncClient){
checkNotNull(target,"target cannot be null");
checkNotNull(username,"username cannot be null");
checkNotNull(password,"password cannot be null");
this.target=target;
this.clientContext=getHttpClientContext(target,username,password);
this.asyncClient=asyncClient == null ? getHttpClient() : asyncClient;
}
| Constructs a RestClient. |
private String createPatternHash(int baseColorIndex){
String hashSource="" + baseColorIndex + "";
int count=0;
synchronized (PatternList) {
for ( BannerPattern bp : PatternList) {
if (count++ != 0) {
hashSource+="-";
}
hashSource+=bp.toString();
}
}
return hashSource;
}
| Creates a uniq string for combination of patterns |
public void close() throws IOException {
super.close();
disposerRecord.dispose();
stream=null;
cache=null;
cacheFile=null;
StreamCloser.removeFromQueue(closeAction);
}
| Closes this <code>FileCacheImageInputStream</code>, closing and removing the cache file. The source <code>InputStream</code> is not closed. |
public static Uri importContent(String sessionId,String sourcePath) throws IOException {
File sourceFile=new File(sourcePath);
String targetPath="/" + sessionId + "/upload/"+ sourceFile.getName();
targetPath=createUniqueFilename(targetPath);
copyToVfs(sourcePath,targetPath);
return vfsUri(targetPath);
}
| Copy device content into vfs. All imported content is stored under /SESSION_NAME/ The original full path is retained to facilitate browsing The session content can be deleted when the session is over |
public static ProjectActionEvent createProjectClosedEvent(ProjectDescriptor project,boolean closingBeforeOpening){
return new ProjectActionEvent(project,ProjectAction.CLOSED,closingBeforeOpening);
}
| Creates a Project Closed Event. |
public static void initiateItemEvent(EntityPlayer player,ItemStack itemStack,int event,boolean limitRange){
try {
if (NetworkManager_initiateItemEvent == null) NetworkManager_initiateItemEvent=Class.forName(getPackage() + ".core.network.NetworkManager").getMethod("initiateItemEvent",EntityPlayer.class,ItemStack.class,Integer.TYPE,Boolean.TYPE);
if (instance == null) instance=getInstance();
NetworkManager_initiateItemEvent.invoke(instance,player,itemStack,event,limitRange);
}
catch ( Exception e) {
throw new RuntimeException(e);
}
}
| Immediately send an event for the specified Item to the clients in range. The item should implement INetworkItemEventListener to receive the event. If this method is being executed on the client (i.e. Singleplayer), it'll just call INetworkItemEventListener.onNetworkEvent (if implemented by the item). |
public Enumeration<V> elements(){
return new ValueIterator();
}
| Returns an enumeration of the values in this table. |
private boolean trackerAt(StendhalRPZone zone,int x,int y){
final List<Entity> list=zone.getEntitiesAt(x,y);
for ( Entity entity : list) {
if (entity instanceof ExpirationTracker) {
return true;
}
}
return false;
}
| Checks to see if an ExpirationTracker is already at a given coordinate to prevent multiple one from accumulating in the database |
public Segment segment(long index){
assertOpen();
if (currentSegment != null && currentSegment.validIndex(index)) return currentSegment;
Map.Entry<Long,Segment> segment=segments.floorEntry(index);
return segment != null ? segment.getValue() : null;
}
| Returns the segment for the given index. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:01:20.138 -0400",hash_original_method="5CC57CD7C5B9408E54C315A9BE16050C",hash_generated_method="E0C143C4A578FB33A41B66D46278449D") public int nextInt(int least,int bound){
if (least >= bound) throw new IllegalArgumentException();
return nextInt(bound - least) + least;
}
| Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive). |
protected ECPoint multiplyPositive(ECPoint p,BigInteger k){
ECPoint[] R=new ECPoint[]{p.getCurve().getInfinity(),p};
int n=k.bitLength();
for (int i=0; i < n; ++i) {
int b=k.testBit(i) ? 1 : 0;
int bp=1 - b;
R[bp]=R[bp].twicePlus(R[b]);
}
return R[0];
}
| Joye's double-add algorithm. |
void listItemsSortedSecure() throws Exception {
System.out.println("Secure Systems Inc. - list items");
String order=input("order (id, name)?");
if (!order.matches("[a-zA-Z0-9_]*")) {
order="id";
}
try {
ResultSet rs=stat.executeQuery("SELECT ID, NAME FROM ITEMS ORDER BY " + order);
while (rs.next()) {
System.out.println(rs.getString(1) + ": " + rs.getString(2));
}
}
catch ( SQLException e) {
System.out.println(e);
}
}
| List items using a specified sort order. The method is secure as the user input is validated before use. However the database has no chance to verify this. |
private int readInt(InputStream is) throws IOException {
return ((is.read() << 24) | (is.read() << 16) | (is.read() << 8)| (is.read()));
}
| Parses a 32-bit int. |
void enableConfirmButtons(){
confirmChangesButton.setToolTipText(SymbolicProgBundle.getMessage("TipConfirmChangesSheet"));
confirmAllButton.setToolTipText(SymbolicProgBundle.getMessage("TipConfirmAllSheet"));
if (_cvModel.getProgrammer() != null && !_cvModel.getProgrammer().getCanRead()) {
confirmChangesButton.setEnabled(false);
confirmAllButton.setEnabled(false);
confirmChangesButton.setToolTipText(SymbolicProgBundle.getMessage("TipNoRead"));
confirmAllButton.setToolTipText(SymbolicProgBundle.getMessage("TipNoRead"));
}
else {
confirmChangesButton.setEnabled(true);
confirmAllButton.setEnabled(true);
}
}
| Enable the compare all and compare changes button if possible. This checks to make sure this is appropriate, given the attached programmer's capability. |
private String eventName(String taskType,int taskNum,String evtType){
assert nodeId != null;
return taskType + " " + taskNum+ " "+ evtType+ " "+ nodeId;
}
| Generate name that consists of some event information. |
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){
switch (featureID) {
case UmplePackage.ACTION___ANONYMOUS_ACTION_11:
return ((InternalEList<?>)getAnonymous_action_1_1()).basicRemove(otherEnd,msgs);
case UmplePackage.ACTION___ANONYMOUS_ACTION_21:
return ((InternalEList<?>)getAnonymous_action_2_1()).basicRemove(otherEnd,msgs);
}
return super.eInverseRemove(otherEnd,featureID,msgs);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void showPathInFileBrowser(final Path path){
try {
final boolean isFolder=Files.isDirectory(path);
final boolean isFile=!isFolder;
if (isFile && LEnv.OS == OpSys.WINDOWS) {
new ProcessBuilder("explorer.exe","/select,",path.toAbsolutePath().toString()).start();
}
else Desktop.getDesktop().open(isFolder ? path.toFile() : path.getParent().toFile());
}
catch ( final IOException ie) {
LEnv.LOGGER.warning("Failed to open file browser!",ie);
}
}
| Opens the specified file or folder in the default file browser application of the user's OS. <p> If a file is specified, on Windows it will also be selected. </p> |
private <T>T processExtremes(Stamp forX,Stamp forY,BiFunction<Long,Long,T> op){
IntegerStamp xStamp=(IntegerStamp)forX;
IntegerStamp yStamp=(IntegerStamp)forY;
JavaKind kind=getStackKind();
assert kind == JavaKind.Int || kind == JavaKind.Long;
long[] xExtremes=getUnsignedExtremes(xStamp);
long[] yExtremes=getUnsignedExtremes(yStamp);
long min=Long.MAX_VALUE;
long max=Long.MIN_VALUE;
for ( long a : xExtremes) {
for ( long b : yExtremes) {
long result=kind == JavaKind.Int ? multiplyHighUnsigned((int)a,(int)b) : multiplyHighUnsigned(a,b);
min=Math.min(min,result);
max=Math.max(max,result);
}
}
return op.apply(min,max);
}
| Determines the minimum and maximum result of this node for the given inputs and returns the result of the given BiFunction on the minimum and maximum values. Note that the minima and maxima are calculated using signed min/max functions, while the values themselves are unsigned. |
public String toSignatureString(){
StringBuilder sb=new StringBuilder();
String accessLevel=convertModifiersToAccessLevel(mModifier);
if (!"".equals(accessLevel)) {
sb.append(accessLevel).append(" ");
}
if (!JDiffType.INTERFACE.equals(mClassType)) {
String modifierString=convertModifersToModifierString(mModifier);
if (!"".equals(modifierString)) {
sb.append(modifierString).append(" ");
}
sb.append("class ");
}
else {
sb.append("interface ");
}
sb.append(mShortClassName);
if (mExtendedClass != null) {
sb.append(" extends ").append(mExtendedClass).append(" ");
}
if (implInterfaces.size() > 0) {
sb.append(" implements ");
for (int x=0; x < implInterfaces.size(); x++) {
String interf=implInterfaces.get(x);
sb.append(interf);
if (x + 1 != implInterfaces.size()) {
sb.append(", ");
}
}
}
return sb.toString();
}
| Convert the class into a printable signature string. |
public void showPopup(){
if (getPopup() != null) {
getPopup().setVisible(true);
}
}
| if a JPopupMenu is set, it is displayed again. Displaying this dialog closes any JPopupMenu automatically. |
public boolean isGame(){
return true;
}
| Determines if this marker is a game. Default is true, so override is only necessary if implementation is not a game. |
private FigureLayerComparator(){
}
| Creates a new instance. |
public TDoubleDoubleHashMap normalizedDistribution(){
return normalizedDistribution(absoluteDistribution());
}
| Returns a histogram of all samples where the values are normalized so that the sum of all samples equals one. |
private void waitForUsers(URI hostUri,String authToken) throws Throwable {
URI usersLink=UriUtils.buildUri(hostUri,UserService.FACTORY_LINK);
Integer[] numberUsers=new Integer[1];
for (int i=0; i < 20; i++) {
Operation get=Operation.createGet(usersLink).forceRemote().addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER,authToken).setCompletion(null);
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
| Supports createUsers() by waiting for two users to be created. They aren't created immediately, so this polls. |
public synchronized int send(byte[] buffer,int offset,int len) throws IOException {
if (m_state != PseudoTcpState.TCP_ESTABLISHED) {
throw new IOException("Socket not connected");
}
long available_space;
available_space=m_sbuf.getWriteRemaining();
if (available_space == 0) {
m_bWriteEnable=true;
return 0;
}
int written=queue(buffer,offset,len,false);
attemptSend(SendFlags.sfNone);
return written;
}
| Enqueues data in the send buffer |
public SampleAxioms(){
super();
}
| De-serialization ctor. |
public void validateTagTypeKey(TagTypeKey tagTypeKey) throws IllegalArgumentException {
Assert.notNull(tagTypeKey,"A tag type key must be specified.");
tagTypeKey.setTagTypeCode(alternateKeyHelper.validateStringParameter("tag type code",tagTypeKey.getTagTypeCode()));
}
| Validates a tag type key. This method also trims the key parameters. |
public static BigInteger nextPrime(long n){
long i;
boolean found=false;
long result=0;
if (n <= 1) {
return BigInteger.valueOf(2);
}
if (n == 2) {
return BigInteger.valueOf(3);
}
for (i=n + 1 + (n & 1); (i <= n << 1) && !found; i+=2) {
for (long j=3; (j <= i >> 1) && !found; j+=2) {
if (i % j == 0) {
found=true;
}
}
if (found) {
found=false;
}
else {
result=i;
found=true;
}
}
return BigInteger.valueOf(result);
}
| Computes the next prime greater than n. |
@Override public void addCharacterToOutput(final Entry<Character,GrayscaleMatrix> characterEntry,final int[] sourceImagePixels,final int tileX,final int tileY,final int imageWidth){
this.output.append(characterEntry.getKey());
if ((tileX + 1) * this.characterCache.getCharacterImageSize().getWidth() == imageWidth) {
this.output.append(System.lineSeparator());
}
}
| Append choosen character to StringBuffer. |
@VisibleForTesting static int chooseTableSize(int setSize){
if (setSize == 1) {
return 2;
}
int tableSize=Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize<<=1;
}
return tableSize;
}
| Returns an array size suitable for the backing array of a hash table that uses open addressing with linear probing in its implementation. The returned size is the smallest power of two that can hold setSize elements with the desired load factor. |
public void validateMinimum(){
double newMin;
try {
newMin=Double.parseDouble(this.minimumRangeValue.getText());
if (newMin >= this.maximumValue) {
newMin=this.minimumValue;
}
}
catch ( NumberFormatException e) {
newMin=this.minimumValue;
}
this.minimumValue=newMin;
this.minimumRangeValue.setText(Double.toString(this.minimumValue));
}
| Revalidate the range minimum. |
public static void init(ActorSystem actorSystem){
if (instance == null) {
instance=actorSystem.actorOf(Props.create(BatchSigner.class));
}
}
| Initializes the batch signer with the given actor system. |
private static void dump(PrintData pd){
dumpHeader(pd);
for (int i=0; i < pd.getRowCount(); i++) dumpRow(pd,i);
}
| Dump all PrintData - header and rows |
public boolean isHIGHER(){
return value == HIGHER;
}
| Is the condition code HIGHER? |
public Matrix4x3d rotateZ(double ang){
return rotateZ(ang,this);
}
| Apply rotation about the Z axis to this matrix by rotating the given amount of radians. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> |
@Override protected URLConnection openConnection(URL url,Proxy proxy) throws IOException {
if (url == null || proxy == null) {
throw new IllegalArgumentException("url == null || proxy == null");
}
return new FtpURLConnection(url,proxy);
}
| Returns a connection, which is established via the <code>proxy</code>, to the FTP server specified by this <code>URL</code>. If <code>proxy</code> is DIRECT type, the connection is made in normal way. |
private boolean saveMacro(){
if (firstTime) {
try {
Thread.sleep(firstTimeSleep);
}
catch ( InterruptedException e) {
e.printStackTrace();
}
}
firstTime=false;
byte[] macroAccy=new byte[macroSize];
int index=0;
int accyNum=0;
accyNum=getAccyRow(macroAccy,index,textAccy1,accyTextField1,cmdButton1);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy2,accyTextField2,cmdButton2);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy3,accyTextField3,cmdButton3);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy4,accyTextField4,cmdButton4);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy5,accyTextField5,cmdButton5);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy6,accyTextField6,cmdButton6);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy7,accyTextField7,cmdButton7);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
if (!isUsb) {
accyNum=getAccyRow(macroAccy,index,textAccy8,accyTextField8,cmdButton8);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
accyNum=getAccyRow(macroAccy,index,textAccy9,accyTextField9,cmdButton9);
if (accyNum < 0) {
return false;
}
if (accyNum > 0) {
index+=2;
}
}
accyNum=getAccyRow(macroAccy,index,textAccy10,accyTextField10,cmdButton10);
if (accyNum < 0) {
JOptionPane.showMessageDialog(this,rb.getString("EnterMacroNumberLine10"),rb.getString("NceMacro"),JOptionPane.ERROR_MESSAGE);
return false;
}
processMemory(false,true,macroNum,macroAccy);
return true;
}
| Writes all bytes to NCE CS memory as long as there are no user input errors |
private boolean matchesMobile4g(NetworkIdentity ident){
ensureSubtypeAvailable();
if (ident.mType == TYPE_WIMAX) {
return true;
}
else if (matchesMobile(ident)) {
switch (getNetworkClass(ident.mSubType)) {
case NETWORK_CLASS_4_G:
return true;
}
}
return false;
}
| Check if mobile network classified 4G with matching IMSI. |
public void writeToBuffer(ByteBuf buffer) throws Exception {
if (id != -1) {
Type.VAR_INT.write(buffer,id);
}
if (readableObjects.size() > 0) {
packetValues.addAll(readableObjects);
readableObjects.clear();
}
int index=0;
for ( Pair<Type,Object> packetValue : packetValues) {
try {
Object value=packetValue.getValue();
if (value != null) {
if (!packetValue.getKey().getOutputClass().isAssignableFrom(value.getClass())) {
if (packetValue.getKey() instanceof TypeConverter) {
value=((TypeConverter)packetValue.getKey()).from(value);
}
else {
System.out.println("Possible type mismatch: " + value.getClass().getName() + " -> "+ packetValue.getKey().getOutputClass());
}
}
}
packetValue.getKey().write(buffer,value);
}
catch ( Exception e) {
throw new InformativeException(e).set("Index",index).set("Type",packetValue.getKey().getTypeName()).set("Packet ID",getId()).set("Data",packetValues);
}
index++;
}
writeRemaining(buffer);
}
| Write the current output to a buffer. |
public RandomDecisionTree(int numFeatures,int maxDepth,int minSamples,TreePruner.PruningMethod pruningMethod,double testProportion){
super(maxDepth,minSamples,pruningMethod,testProportion);
setRandomFeatureCount(numFeatures);
}
| Creates a new Random Decision Tree |
protected void fireCommentEvent(char[] chars,int start,int length) throws org.xml.sax.SAXException {
if (m_tracer != null) {
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT,new String(chars,start,length));
}
}
| Report the comment trace event |
private void init(Context context,AttributeSet attrs,RuqusTheme theme){
inflate(context,R.layout.rqv_card,this);
outlineView=(FrameLayout)findViewById(R.id.outline);
outlineTextView=(TextView)findViewById(R.id.outline_text);
cardView=(CardView)findViewById(R.id.card);
cardTextView=(TextView)findViewById(R.id.card_text);
setTheme(theme);
TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.RQVCard);
mode=typedArray.getInt(R.styleable.RQVCard_rqv_card_mode,0) == 0 ? Mode.OUTLINE : Mode.CARD;
outlineTextView.setText(typedArray.getString(R.styleable.RQVCard_rqv_outline_text));
cardTextView.setText(typedArray.getString(R.styleable.RQVCard_rqv_card_text));
typedArray.recycle();
}
| Initialize our view. |
public void onUndeploy(ClassLoader ldr){
for ( Class<?> cls : descByCls.keySet()) {
if (ldr.equals(cls.getClassLoader())) descByCls.remove(cls);
}
U.clearClassCache(ldr);
}
| Undeployment callback invoked when class loader is being undeployed. Some marshallers may want to clean their internal state that uses the undeployed class loader somehow. |
@Override public int compare(final Long o1,final Long o2){
if (o1.longValue() < o2.longValue()) return 1;
if (o1.longValue() > o2.longValue()) return -1;
return 0;
}
| Comparator puts the entries into descending order by the query execution time (longest running queries are first). |
public void testResourceParameterOfListType(){
doTest();
}
| Tests that a ResourceParameterInspection error is generated for a resource parameter of List type. |
public TeXFormula add(String s) throws ParseException {
if (s != null && s.length() != 0) {
textStyle=null;
add(new TeXFormula(s));
}
return this;
}
| Parses the given string and inserts the resulting formula at the end of the current TeXFormula. |
public ResponseEntity<List<Recommendation>> defaultRecommendations(int productId){
LOG.warn("Using fallback method for recommendation-service");
return util.createResponse(Arrays.asList(new Recommendation(productId,1,"Fallback Author 1",1,"Fallback Content 1")),HttpStatus.OK);
}
| Fallback method for getRecommendations() |
private void cmd_annotateDifference(){
BigDecimal previousValue, actualValue, difference;
previousValue=(BigDecimal)v_previousBalance.getValue();
actualValue=(BigDecimal)v_ActualBalance.getValue();
difference=actualValue.subtract(previousValue);
MCashBook cashBook=new MCashBook(p_ctx,p_pos.getC_CashBook_ID(),null);
Timestamp today=TimeUtil.getDay(System.currentTimeMillis());
MCash cash=MCash.get(p_ctx,cashBook.getC_CashBook_ID(),today,null);
if (cash != null && cash.get_ID() != 0 && difference.compareTo(cash.getStatementDifference()) != 0) {
MCashLine cl=new MCashLine(cash);
cl.setCashType(MCashLine.CASHTYPE_Difference);
cl.setAmount(difference);
cl.setDescription(Msg.translate(p_pos.getCtx(),"Cash Scrutiny -> Before: ") + previousValue + " Now: "+ actualValue);
cl.saveEx();
}
cash=MCash.get(p_pos.getCtx(),p_pos.getC_CashBook_ID(),today,null);
v_previousBalance.setValue(cash.getEndingBalance());
v_ActualBalance.setValue(Env.ZERO);
v_difference.setValue(Env.ZERO);
}
| Annotate the difference between previous balance and actual from cash scrutiny in the cash book |
public boolean hasJpgThumbnail(){
if (getThumbnailType() != ExifDirectory.COMPRESSION_JPEG) return false;
byte[] thumbData;
try {
ExifDirectory exif=(ExifDirectory)metadata.getDirectory(ExifDirectory.class);
thumbData=exif.getThumbnailData();
}
catch ( MetadataException e) {
return false;
}
if (thumbData.length > 2) {
int magicNumber;
magicNumber=(thumbData[0] & 0xFF) << 8;
magicNumber|=(thumbData[1] & 0xFF);
if (magicNumber == ImageMetadataReader.JPEG_FILE_MAGIC_NUMBER) return true;
}
return false;
}
| Performs checks to determine if the image has a JPG thumbnail in the EXIF data. <p> The EXIF TAG_COMPRESION , and the magic number at the beginning of the thumbnail bytes are used to verify that the thumb is in JPG format |
private void waitForRScriptInitialized() throws InterpreterException {
synchronized (rScriptInitializeNotifier) {
long startTime=System.nanoTime();
while (rScriptInitialized == false && rScriptRunning && System.nanoTime() - startTime < 10L * 1000 * 1000000) {
try {
rScriptInitializeNotifier.wait(1000);
}
catch ( InterruptedException e) {
logger.error(e.getMessage(),e);
}
}
}
String errorMessage="";
try {
initialOutput.flush();
errorMessage=new String(initialOutput.toByteArray());
}
catch ( IOException e) {
e.printStackTrace();
}
if (rScriptInitialized == false) {
throw new InterpreterException("sparkr is not responding " + errorMessage);
}
}
| Wait until src/main/resources/R/zeppelin_sparkr.R is initialized and call onScriptInitialized() |
private DefaultUnitConverter(){
}
| Constructs a DefaultUnitConverter and registers a listener that handles changes in the look&feel. |
public static String morpha(String text,boolean tags){
if (text.isEmpty()) {
return "";
}
String[] textParts=whitespace.split(text);
StringBuilder result=new StringBuilder();
try {
for ( String textPart : textParts) {
Morpha morpha=new Morpha(new StringReader(textPart),tags);
if (result.length() != 0) {
result.append(" ");
}
result.append(morpha.next());
}
}
catch ( Error e) {
return text;
}
catch ( java.io.IOException e) {
return text;
}
return result.toString();
}
| Run the morpha algorithm on the specified string. |
protected void readUnzipedResponse(InputStream input) throws IOException {
super.readResponse(input);
}
| This method can be overridden instead of readResponse |
public EventStream<S> events() throws Exception {
return EventStream.empty();
}
| Returns a stream of events that should be recorded. By default, an empty stream returned. |
public Object invoke(Remote obj,java.lang.reflect.Method method,Object[] params,long opnum) throws Exception {
boolean force=false;
RemoteRef localRef;
Exception exception=null;
synchronized (this) {
if (ref == null) {
localRef=activate(force);
force=true;
}
else {
localRef=ref;
}
}
for (int retries=MAX_RETRIES; retries > 0; retries--) {
try {
return localRef.invoke(obj,method,params,opnum);
}
catch ( NoSuchObjectException e) {
exception=e;
}
catch ( ConnectException e) {
exception=e;
}
catch ( UnknownHostException e) {
exception=e;
}
catch ( ConnectIOException e) {
exception=e;
}
catch ( MarshalException e) {
throw e;
}
catch ( ServerError e) {
throw e;
}
catch ( ServerException e) {
throw e;
}
catch ( RemoteException e) {
synchronized (this) {
if (localRef == ref) {
ref=null;
}
}
throw e;
}
if (retries > 1) {
synchronized (this) {
if (localRef.remoteEquals(ref) || ref == null) {
RemoteRef newRef=activate(force);
if (newRef.remoteEquals(localRef) && exception instanceof NoSuchObjectException && force == false) {
newRef=activate(true);
}
localRef=newRef;
force=true;
}
else {
localRef=ref;
force=false;
}
}
}
}
throw exception;
}
| Invoke method on remote object. This method delegates remote method invocation to the underlying ref type. If the underlying reference is not known (is null), then the object must be activated first. If an attempt at method invocation fails, the object should force reactivation. Method invocation must preserve "at most once" call semantics. In RMI, "at most once" applies to parameter deserialization at the remote site and the remote object's method execution. "At most once" does not apply to parameter serialization at the client so the parameters of a call don't need to be buffered in anticipation of call retry. Thus, a method call is only be retried if the initial method invocation does not execute at all at the server (including parameter deserialization). |
public String lookupCacheSizeTipText(){
return "Set the maximum size of the lookup cache of evaluated subsets. This is " + "expressed as a multiplier of the number of attributes in the data set. " + "(default = 1).";
}
| Returns the tip text for this property |
private SimpleObject providerToJson(Provider provider){
SimpleObject jsonForm=new SimpleObject();
if (provider != null) {
jsonForm.add(USER_ID,provider.getUuid());
jsonForm.add(FULL_NAME,provider.getName());
Person person=provider.getPerson();
if (person != null) {
jsonForm.add(GIVEN_NAME,person.getGivenName());
jsonForm.add(FAMILY_NAME,person.getFamilyName());
}
}
return jsonForm;
}
| Builds a SimpleObject describing the given Provider. |
@Override public int next() throws XMLStreamException {
log.fine("next()");
if (event == START_DOCUMENT) {
event=START_ELEMENT;
elementIndex.currentElement=parser.getDocument().getBody().getElement();
}
else if (event == START_ELEMENT) {
elementIndex.index=0;
event=nextInElement(false);
}
else if (event == ATTRIBUTE) {
elementIndex.index=0;
event=nextInElement(false);
}
else if (event == CHARACTERS) {
elementIndex.index++;
event=nextInElement(false);
}
else if (event == SPACE) {
elementIndex.index++;
event=nextInElement(false);
}
else if (event == ENTITY_REFERENCE) {
elementIndex.index++;
event=nextInElement(false);
}
else if (event == PROCESSING_INSTRUCTION) {
elementIndex.index++;
event=nextInElement(false);
}
else if (event == END_ELEMENT) {
if (parents.isEmpty()) {
event=END_DOCUMENT;
}
else {
elementIndex=parents.pop();
elementIndex.index++;
event=nextInElement(false);
}
}
else if (event == END_DOCUMENT) {
throw new XMLStreamException("End of coument reached!");
}
else {
throw new XMLStreamException("Invalid event state!");
}
log.log(Level.FINE,"next(): {0}",event);
return event;
}
| Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks. If the property javax.xml.stream.isCoalescing is set to true element content must be coalesced and only one CHARACTERS event must be returned for contiguous element content or CDATA Sections. By default entity references must be expanded and reported transparently to the application. An exception will be thrown if an entity reference cannot be expanded. If element content is empty (i.e. content is "") then no CHARACTERS event will be reported. <p>This method marks the current element and index using the elementIndex structure. Besides a queue of parents element index is maintained to cross over all element hierarchy.</p> <p>The WbXMLStreamReader only manages the following states:</p> <ul> <li>START_DOCUMENT</li> <li>PROCESSING_INSTRUCTION</li> <li>START_ELEMENT</li> <li>ATTRIBUTE</li> <lI>CHARACTERS</li> <li>END_ELEMENT</li> <li>SPACE</li> <li>END_DOCUMENT</li> <li>ENTITY_REFERENCE</li> </ul> <p>Therefore the following element does no matter in this stream reader:</p> <ul> <li>CDATA (CHARACTERS are used always).</li> <li>COMMENT (no comments in WBXML).</li> <li>DTD (no DTD section)</li> <li>ENTITY_DECLARATION</li> <li>NAMESPACE</li> <li>NOTATION DECLARATION</li> </ul> |
@SuppressWarnings("unchecked") public synchronized List<Relationship> findAllRelationshipsTo(Vertex vertex){
Query query=this.entityManager.createQuery("Select r from Relationship r where r.target = :vertex or r.type = :vertex");
setHints(query);
query.setParameter("vertex",vertex);
return query.getResultList();
}
| Find all relationships related to the vertex or of the vertex relationship type. |
public static String convertMethodSignature(InvokeInstruction inv,ConstantPoolGen cpg){
return convertMethodSignature(inv.getClassName(cpg),inv.getName(cpg),inv.getSignature(cpg));
}
| Convenience method for generating a method signature in human readable form. |
@Override public int count(Selector obj){
if ((obj.getMask() & Selector.MASK_INSTANCE) > 0) {
if (device.findObject(obj.toUiSelector()).exists()) return 1;
else return 0;
}
else {
UiSelector sel=obj.toUiSelector();
if (!device.findObject(sel).exists()) return 0;
int low=1;
int high=2;
sel=sel.instance(high - 1);
while (device.findObject(sel).exists()) {
low=high;
high=high * 2;
sel=sel.instance(high - 1);
}
while (high > low + 1) {
int mid=(low + high) / 2;
sel=sel.instance(mid - 1);
if (device.findObject(sel).exists()) low=mid;
else high=mid;
}
return low;
}
}
| Get the count of the UiObject instances by the selector |
private boolean isComputeHost(ComputeDescription computeDescription){
List<String> supportedChildren=computeDescription.supportedChildren;
return supportedChildren != null && supportedChildren.contains(ComputeType.VM_GUEST.name());
}
| Returns if the given compute description is a compute host or not. |
public File prepareTestDir(String logDirName) throws Exception {
File logDir=new File(logDirName);
FilePath path=new FilePath(logDir.getAbsolutePath());
fileIO.delete(path,true);
fileIO.mkdir(path);
return logDir;
}
| Create an empty test directory or if the directory exists remove any files within it. |
public void receiveErrorqueryAssociatedPortsForProcessor(java.lang.Exception e){
}
| auto generated Axis2 Error handler override this method for handling error response from queryAssociatedPortsForProcessor operation |
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
| Returns a clone of this instance. |
private void dump(File from,OutputStream out) throws IOException {
writeHeader(from,out);
FileInputStream in=null;
try {
in=new FileInputStream(from);
int count;
while ((count=in.read(buffer)) != -1) {
out.write(buffer,0,count);
}
}
finally {
closeQuietly(in);
}
}
| Copies from a file to an output stream. |
public static long lastLocalId(){
return cntGen.get();
}
| Gets last generated local ID. |
RoleEventImpl(Region region,Operation op,Object callbackArgument,boolean originRemote,DistributedMember distributedMember,Set requiredRoles){
super(region,op,callbackArgument,originRemote,distributedMember);
this.requiredRoles=Collections.unmodifiableSet(requiredRoles);
}
| Constructs new RoleEventImpl. |