code
stringlengths
10
174k
nl
stringlengths
3
129k
public static void main(String[] args){ doMain(args); }
Application entry point.
public static void applyDebuggerSystemProperty(Arguments args){ if ("1".equals(SystemProperties.get("ro.debuggable"))) { args.debugFlags|=Zygote.DEBUG_ENABLE_DEBUGGER; } }
Applies debugger system properties to the zygote arguments. If "ro.debuggable" is "1", all apps are debuggable. Otherwise, the debugger state is specified via the "--enable-debugger" flag in the spawn request.
public String encode(){ return encode(new StringBuffer()).toString(); }
Get the encoded version of this id.
void copyProductAndModifyParametersForUpdate(Subscription subscription,Product targetProduct,PlatformUser currentUser,List<VOParameter> voTargetParameters) throws SubscriptionMigrationException, TechnicalServiceNotAliveException { Product targetProductCopy=null; ProvisioningType provisioningType=targetProduct.getTechnicalProduct().getProvisioningType(); if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) { targetProductCopy=targetProduct; } else if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) { targetProductCopy=copyProductForSubscription(targetProduct,subscription,true); } List<Parameter> modifiedParametersForLog=updateConfiguredParameterValues(targetProductCopy,voTargetParameters,subscription); checkPlatformParameterConstraints(subscription,targetProductCopy,currentUser); try { if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) { subscription.setAsyncTempProduct(targetProductCopy); handleAsyncUpdateSubscription(subscription,targetProductCopy); } else if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) { if (subscription.getStatus() != SubscriptionStatus.PENDING) { appManager.modifySubscription(subscription); } } } catch ( TechnicalServiceNotAliveException e) { sessionCtx.setRollbackOnly(); throw e; } catch ( TechnicalServiceOperationException e1) { sessionCtx.setRollbackOnly(); Object[] params; String subscriptionId=subscription.getSubscriptionId(); if (e1.getMessageParams() != null && e1.getMessageParams().length > 1) { params=new Object[]{subscriptionId,e1.getMessage(),e1.getMessageParams()[1]}; } else { params=new Object[]{subscriptionId,e1.getMessage(),""}; } SubscriptionMigrationException smf=new SubscriptionMigrationException("Modify ParameterSet failed",Reason.PARAMETER,params); LOG.logError(Log4jLogger.SYSTEM_LOG,smf,LogMessageIdentifier.ERROR_MODIFY_PARAMETER_SET_FAILED); throw smf; } audit.editSubscriptionParameterConfiguration(dataManager,targetProductCopy,modifiedParametersForLog); }
Copies the product and modifies the given parameters. Also informs the technical service about the changed parameter set.
public static String humanReadableByteCount(long bytes,boolean si){ int unit=si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp=(int)(Math.log(bytes) / Math.log(unit)); String pre=(si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format(Locale.getDefault(),"%.1f %sB",bytes / Math.pow(unit,exp),pre); }
Converts byte size into human readable format
public LevelDBBlockStore(Context context,File directory) throws BlockStoreException { this(context,directory,JniDBFactory.factory); }
Creates a LevelDB SPV block store using the JNI/C++ version of LevelDB.
public ParetoDistr(double shape,double location){ numGen=new ParetoDistribution(location,shape); }
Instantiates a new Pareto pseudo random number generator.
public DateTimeFormatterBuilder appendFractionOfMinute(int minDigits,int maxDigits){ return appendFraction(DateTimeFieldType.minuteOfDay(),minDigits,maxDigits); }
Appends the print/parse of a fractional minute. <p> This reliably handles the case where fractional digits are being handled beyond a visible decimal point. The digits parsed will always be treated as the most significant (numerically largest) digits. Thus '23' will be parsed as 0.23 minutes (converted to milliseconds). This method does not print or parse the decimal point itself.
protected void addToGUI(JPanel gui,JTextField b,String cmd){ b.setActionCommand(cmd); b.addActionListener(this); gui.add(b); }
Adds a feature to the Gui attribute of the E00Layer object
public String toString(){ final String TAB=" "; StringBuffer retValue=new StringBuffer(); retValue.append("ContainsOperator ( ").append("value = ").append(this.value).append(TAB).append(" )"); return retValue.toString(); }
Constructs a <code>String</code> with all attributes in name = value format.
public static void removeAllView(final JFrame parent,final BackEndDebuggerProvider debuggerProvider,final INaviView view){ Preconditions.checkNotNull(parent,"IE01933: Parent argument can't be null"); Preconditions.checkNotNull(debuggerProvider,"IE02251: Debugger provider argument can not be null"); Preconditions.checkNotNull(view,"IE01956: View argument can't be null"); if (JOptionPane.YES_OPTION == CMessageBox.showYesNoCancelQuestion(parent,"Do you really want to remove all breakpoints from this view?")) { for ( final IDebugger debugger : debuggerProvider) { removeAllView(debugger.getBreakpointManager(),view); } } }
Removes all breakpoints that are part of a given view.
@Override public int hashCode(){ return getClass().hashCode(); }
Returns a hash code value for this LocalRMIServerSocketFactory.
public String toString(){ StringBuffer sb=new StringBuffer("MCost["); sb.append("AD_Client_ID=").append(getAD_Client_ID()); if (getAD_Org_ID() != 0) sb.append(",AD_Org_ID=").append(getAD_Org_ID()); if (getM_Warehouse_ID() != 0) sb.append(",M_Warehouse_ID=").append(getM_Warehouse_ID()); sb.append(",M_Product_ID=").append(getM_Product_ID()); if (getM_AttributeSetInstance_ID() != 0) sb.append(",AD_ASI_ID=").append(getM_AttributeSetInstance_ID()); sb.append(",M_CostElement_ID=").append(getM_CostElement_ID()); sb.append(", CurrentCost=").append(getCurrentCostPrice()).append(", C.Amt=").append(getCumulatedAmt()).append(",C.Qty=").append(getCumulatedQty()).append("]"); return sb.toString(); }
String Representation
public int bitAt(int position){ boolean bit=bits.get(position + firstBitNum); if (!bit) { return 0; } else { return 1; } }
Returns the bit in the given position.
public PowerShellResponse executeScript(String scriptPath,String params){ BufferedReader reader=null; BufferedWriter writer=null; File tmpFile=null; try { File scriptToExecute=new File(scriptPath); if (!scriptToExecute.exists()) { return new PowerShellResponse(true,"Wrong script path: " + scriptToExecute,false); } tmpFile=File.createTempFile("psscript_" + new Date().getTime(),".ps1"); if (tmpFile == null || !tmpFile.exists()) { return new PowerShellResponse(true,"Cannot create temp script file",false); } reader=new BufferedReader(new FileReader(scriptToExecute)); writer=new BufferedWriter(new FileWriter(tmpFile)); String line; while ((line=reader.readLine()) != null) { writer.write(line); writer.newLine(); } writer.write("Write-Host \"" + END_SCRIPT_STRING + "\""); } catch ( FileNotFoundException fnfex) { Logger.getLogger(PowerShell.class.getName()).log(Level.SEVERE,"Unexpected error when processing PowerShell script",fnfex); } catch ( IOException ioex) { Logger.getLogger(PowerShell.class.getName()).log(Level.SEVERE,"Unexpected error when processing PowerShell script",ioex); } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch ( IOException ex) { Logger.getLogger(PowerShell.class.getName()).log(Level.SEVERE,"Unexpected error when processing PowerShell script",ex); } } this.scriptMode=true; return executeCommand(tmpFile.getAbsolutePath() + " " + params); }
Executed the provided PowerShell script in PowerShell console and gets result.
public ElementRule(String name,XMLSyntaxRule[] rules,String description,int min,int max){ this.name=name; this.rules=rules; this.description=description; this.min=min; this.max=max; }
Creates an element rule.
public void testApp(){ assertTrue(true); }
Rigourous Test :-)
public void testTestBitNegative1(){ byte aBytes[]={-1,-128,56,100,-2,-76,89,45,91,3,-15,35,26}; int aSign=-1; int number=7; BigInteger aNumber=new BigInteger(aSign,aBytes); assertTrue(aNumber.testBit(number)); }
testBit(int n) of a negative number
public static byte[] imageToByteArray(BufferedImage image,String imageFileName,OpenStegoPlugin plugin) throws OpenStegoException { ByteArrayOutputStream barrOS=new ByteArrayOutputStream(); String imageType=null; try { if (imageFileName != null) { imageType=imageFileName.substring(imageFileName.lastIndexOf('.') + 1).toLowerCase(); if (!plugin.getWritableFileExtensions().contains(imageType)) { throw new OpenStegoException(null,OpenStego.NAMESPACE,OpenStegoException.IMAGE_TYPE_INVALID,imageType); } if (imageType.equals("jp2")) { imageType="jpeg 2000"; } ImageIO.write(image,imageType,barrOS); } else { ImageIO.write(image,DEFAULT_IMAGE_TYPE,barrOS); } return barrOS.toByteArray(); } catch ( IOException ioEx) { throw new OpenStegoException(ioEx); } }
Method to convert BufferedImage to byte array
public UnrecoverableEntryException(){ super(); }
Constructs an UnrecoverableEntryException with no detail message.
@Override public String globalInfo(){ return "Multinomial BMA Estimator."; }
Returns a string describing this object
public boolean isWordStart(char aChar){ return aChar == '#'; }
Determines if the specified character is permissible as the first character in a Velocity directive. A character may start a Velocity directive if and only if it is one of the following: <ul> <li>a hash (#) </ul>
public Cliff(){ super(); }
Needed by CGLib
@Override public void registerResourceFactories(ResourceSet resourceSet){ super.registerResourceFactories(resourceSet); }
This can be used to update the resource set's resource factory registry with all needed factories.
public static int ENOLCK(){ return Errno.ENOLCK.intValue(); }
No record locks available
public void lock(final T tx,final long timeout) throws InterruptedException, DeadlockException { if (tx == null) throw new NullPointerException(); if (timeout < 0L) throw new IllegalArgumentException(); if (DEBUG) log.debug("enter: tx=" + tx + ", queue="+ this); lock.lock(); if (DEBUG) log.debug("have private lock: tx=" + tx + ", queue="+ this); final long begin=System.currentTimeMillis(); try { assertNotDead(); if (queue.peek() == tx) { if (INFO) log.info("Already owns lock: tx=" + tx + ", queue="+ this); return; } if (queue.isEmpty()) { queue.add(tx); if (INFO) log.info("Granted lock with empty queue: tx=" + tx + ", queue="+ this); return; } if (waitsFor != null) { final Object[] predecessors=queue.toArray(); try { waitsFor.addEdges(tx,predecessors); } catch ( DeadlockException ex) { log.warn("Deadlock: tx=" + tx + ", queue="+ this); throw ex; } } queue.add(tx); try { while (true) { final long elapsed=System.currentTimeMillis() - begin; if (timeout != 0L && elapsed >= timeout) { throw new TimeoutException("After " + elapsed + " ms: tx="+ tx+ ", queue="+ this); } if (INFO) log.info("Awaiting resource: tx=" + tx + ", queue="+ this); final long remaining=timeout - elapsed; if (timeout == 0L) { available.await(); } else { if (!available.await(remaining,TimeUnit.MILLISECONDS)) { throw new TimeoutException("After " + elapsed + " ms: tx="+ tx+ ", queue="+ this); } } if (INFO) log.info("Continuing after wait: tx=" + tx + ", queue="+ this); if (dead.get()) { throw new InterruptedException("Resource is dead: " + resource); } if (queue.peek() == tx) { if (INFO) log.info("Lock granted after wait: tx=" + tx + ", queue="+ this); return; } } } catch ( Throwable t) { if (waitsFor != null) { synchronized (waitsFor) { try { final boolean waiting=true; waitsFor.removeEdges(tx,waiting); } catch ( Throwable t2) { log.warn(t2); } } } queue.remove(tx); if (t instanceof RuntimeException) throw (RuntimeException)t; if (t instanceof InterruptedException) throw (InterruptedException)t; throw new RuntimeException(t); } } finally { lock.unlock(); if (DEBUG) log.debug("released private lock: tx=" + tx + ", queue="+ this); } }
Obtain a lock on the resource.
private boolean isClosed(){ return str == null; }
Returns a boolean indicating whether this reader is closed.
public static void verifyClearRecursively(FinishedTriggers finishedSet){ ExecutableTriggerStateMachine trigger=ExecutableTriggerStateMachine.create(AfterAllStateMachine.of(AfterFirstStateMachine.of(AfterPaneStateMachine.elementCountAtLeast(3),AfterWatermarkStateMachine.pastEndOfWindow()),AfterAllStateMachine.of(AfterPaneStateMachine.elementCountAtLeast(10),AfterProcessingTimeStateMachine.pastFirstElementInPane()))); setFinishedRecursively(finishedSet,trigger); assertTrue(finishedSet.isFinished(trigger)); assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0))); assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(0))); assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(1))); finishedSet.clearRecursively(trigger.subTriggers().get(1)); assertTrue(finishedSet.isFinished(trigger)); verifyFinishedRecursively(finishedSet,trigger.subTriggers().get(0)); verifyUnfinishedRecursively(finishedSet,trigger.subTriggers().get(1)); }
Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no others.
public UserConfig fetch(UserConfig config){ config.addCredentials(this); String xml=POST(this.url + "/check-user",config.toXML()); Element root=parse(xml); if (root == null) { return null; } try { UserConfig user=new UserConfig(); user.parseXML(root); return user; } catch ( Exception exception) { this.exception=SDKException.parseFailure(exception); throw this.exception; } }
Fetch the user details for the user credentials. A token or password is required to validate the user.
public MovieScraperMetadataPanel(MovieScraperMetadataConfig config){ this.config=config; initComponents(); }
Instantiates a new movie scraper metadata panel.
private void computeImpliedVersions(Version... versionList){ impliedVersions.add(this); for ( Version v : versionList) { addImpliedVersion(v); } }
Compute the fully resolved list of implied versions, including the local instance and all directly and indirectly implied versions.
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 X509CertImpl(byte[] encoding) throws IOException { this((Certificate)Certificate.ASN1.decode(encoding)); }
Constructs the instance on the base of ASN.1 encoded form of X.509 certificate provided via array of bytes.
protected void insertTimestamp(final String header){ final Document doc=textPane.getDocument(); try { if (header.length() > 0) { doc.insertString(doc.getLength(),header,textPane.getStyle("timestamp")); } } catch ( final BadLocationException e) { logger.error("Couldn't insert initial text.",e); } }
Insert time stamp.
protected void rollback(){ Trx trx=null; if (trxName != null) trx=Trx.get(trxName,false); if (trx != null && trx.isActive()) { try { trx.rollback(); } finally { trx.close(); } } trx=null; }
Rollback active transaction
private static BitMatrix bitMatrixFrombitArray(byte[][] input,int margin){ BitMatrix output=new BitMatrix(input[0].length + 2 * margin,input.length + 2 * margin); output.clear(); for (int y=0, yOutput=output.getHeight() - margin - 1; y < input.length; y++, yOutput--) { for (int x=0; x < input[0].length; x++) { if (input[y][x] == 1) { output.set(x + margin,yOutput); } } } return output; }
This takes an array holding the values of the PDF 417
public int scale(){ return scale; }
Get the scale of this expression.
public static boolean focusEditor(final IEditorPart editor){ Check.notNull(editor,"editor"); if (editor.getEditorInput() == null) { log.warn("Asked to focus editor with no editor input"); return false; } if (editor.getEditorSite() == null || editor.getEditorSite().getId() == null) { log.warn("Asked to focus editor with no editor site"); return false; } Check.notNull(editor.getEditorInput(),"editor.getEditorInput"); final IWorkbenchPage page=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page == null) { log.warn(MessageFormat.format("Could not locate workbench page to focus editor '{0}'",editor.getEditorInput().getName())); return false; } try { page.openEditor(editor.getEditorInput(),editor.getEditorSite().getId()); } catch ( final PartInitException e) { log.warn(MessageFormat.format("Could not focus editor '{0}'",editor.getEditorInput().getName()),e); return false; } return true; }
Try to focus an editor that is already open.
private void zzScanError(int errorCode){ String message; try { message=ZZ_ERROR_MSG[errorCode]; } catch ( ArrayIndexOutOfBoundsException e) { message=ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); }
Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner etc.). Usual syntax/scanner level error handling should be done in error fallback rules.
private Zeroes(){ }
This class is uninstantiable.
public static void writePopulationData2CSV(final Map<Id,SpatialReferenceObject> personLocations,UrbanSimParameterConfigModuleV3 module){ try { log.info("Initializing AnalysisPopulationCSVWriter ..."); BufferedWriter bwPopulation=IOUtils.getBufferedWriter(module.getMATSim4OpusOutput() + FILE_NAME); log.info("Writing (population) data into " + module.getMATSim4OpusOutput() + FILE_NAME+ " ..."); bwPopulation.write(InternalConstants.PERSON_ID + "," + InternalConstants.PARCEL_ID+ ","+ InternalConstants.X_COORDINATE+ ","+ InternalConstants.Y_COORDINATE); bwPopulation.newLine(); Iterator<SpatialReferenceObject> personIterator=personLocations.values().iterator(); while (personIterator.hasNext()) { SpatialReferenceObject person=personIterator.next(); bwPopulation.write(person.getObjectID() + "," + person.getParcelID()+ ","+ person.getCoord().getX()+ ","+ person.getCoord().getY()); bwPopulation.newLine(); } bwPopulation.flush(); bwPopulation.close(); log.info("... done!"); } catch ( Exception e) { e.printStackTrace(); } }
writing raw population data to disc
public boolean isSubDirectoryOf(IgfsPath path){ A.notNull(path,"path"); return this.path.startsWith(path.path.endsWith(SLASH) ? path.path : path.path + SLASH); }
Checks whether this path is a sub-directory of argument.
protected void updateConsistencyGroup(URI cguri,DbClient dbClient){ BlockConsistencyGroup cg=dbClient.queryObject(BlockConsistencyGroup.class,cguri); if (cg != null && !cg.getInactive()) { if (cg.getArrayConsistency()) { log.info("Updated consistency group arrayConsistency"); cg.setArrayConsistency(false); dbClient.updateObject(cg); } } }
Update arrayConsistency attribute
public XObject operate(XObject left,XObject right) throws javax.xml.transform.TransformerException { return new XNumber((int)(left.num() / right.num())); }
Apply the operation to two operands, and return the result.
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 static _Fields findByThriftId(int fieldId){ switch (fieldId) { case 1: return HEADER; case 2: return STORE; case 3: return VALUES; case 4: return RESPONSE_TO; default : return null; } }
Find the _Fields constant that matches fieldId, or null if its not found.
@Override public synchronized boolean addLogger(Logger logger){ EnvironmentLogger envLogger=addLogger(logger.getName(),logger.getResourceBundleName()); if (!logger.getClass().equals(Logger.class)) { return envLogger.addCustomLogger(logger); } return false; }
Adds a logger.
public T value(String value){ return attr("value",value); }
Sets the <code>value</code> attribute on the last started tag that has not been closed.
protected String printOptions(String[] options){ if (options == null) { return ("<null>"); } else { return Utils.joinOptions(options); } }
Prints the given options to a string.
public void testBug20888() throws Exception { String s="SELECT 'What do you think about D\\'Artanian''?', \"What do you think about D\\\"Artanian\"\"?\""; this.pstmt=((com.mysql.jdbc.Connection)this.conn).clientPrepareStatement(s); this.rs=this.pstmt.executeQuery(); this.rs.next(); assertEquals(this.rs.getString(1),"What do you think about D'Artanian'?"); assertEquals(this.rs.getString(2),"What do you think about D\"Artanian\"?"); }
Tests fix for BUG#20888 - escape of quotes in client-side prepared statements parsing not respected.
public Collection<SynchronizingStorageEngine> values(){ return localStores.values(); }
Get a collection containing all the currently-registered stores
public TextEditor deleteAll(String pattern){ return replaceAll(pattern,""); }
Remove all occurrences of the given regex pattern, replacing them with the empty string.
public void proceed(String username,String password){ this.handler.proceed(username,password); }
Instructs the WebView to proceed with the authentication with the given credentials.
protected ProcessorsFactory newProcessorsFactory(){ return new DefaultProcessorsFactory(); }
Override to provide a different or modified default factory implementation.
protected Map<String,Double> loadLexicon(String path) throws FileNotFoundException { Map<String,Double> lexiMap=new HashMap<String,Double>(); File file=new File("resources/lexi/" + path + ".txt"); Scanner scanner=new Scanner(file); while (scanner.hasNextLine()) { String[] line=scanner.nextLine().split("\t"); if (line.length == 4) { lexiMap.put(line[0],Double.parseDouble(line[1])); } } scanner.close(); return lexiMap; }
Loads and parses a sentiment lexica
public void addRow(Assignment condition,double head,double prob){ addRow(condition,ValueFactory.create(head),prob); }
Adds a new row to the probability table, given the conditional assignment, the head assignment and the probability value. If the table already contains a probability, it is erased.
public void parseDataTypes(OneRowChange oneRowChange) throws UnsupportedEncodingException, ReplicatorException, SerialException, SQLException { oneColVal currentCol=null; columnValues=new ArrayList<oneColVal>(); for (Iterator<PlogLCRTag> iterator=rawTags.iterator(); iterator.hasNext(); ) { PlogLCRTag tag=iterator.next(); switch (tag.id) { case PlogLCRTag.TAG_COL_ID: currentCol=new oneColVal(); columnValues.add(currentCol); currentCol.id=tag.valueInt(); currentCol.columnSpec=oneRowChange.new ColumnSpec(); currentCol.columnSpec.setBlob(false); currentCol.columnSpec.setNotNull(false); currentCol.columnVal=oneRowChange.new ColumnVal(); iterator.remove(); break; case PlogLCRTag.TAG_COL_NAME: currentCol.name=tag.valueString(); currentCol.columnSpec.setName(currentCol.name); iterator.remove(); break; case PlogLCRTag.TAG_COL_TYPE: currentCol.datatype=tag.valueString(); currentCol.columnSpec.setTypeDescription(currentCol.datatype); int tagTypeAsSQLType=currentCol.typeAsSQLType(); currentCol.columnSpec.setType(tagTypeAsSQLType); currentCol.columnSpec.setSigned(tagTypeAsSQLType == java.sql.Types.NUMERIC); iterator.remove(); break; case PlogLCRTag.TAG_LOB_POSITION: currentCol.lobPosition=tag.valueInt(); iterator.remove(); break; case PlogLCRTag.TAG_LOBOFFSET: currentCol.lobOffset=tag.valueLong(); iterator.remove(); break; case PlogLCRTag.TAG_LOBLEN: currentCol.lobLength=tag.valueLong(); iterator.remove(); break; case PlogLCRTag.TAG_PREIMAGE: case PlogLCRTag.TAG_POSTIMAGE: case PlogLCRTag.TAG_KEYIMAGE: case PlogLCRTag.TAG_LOBDATA: currentCol.imageType=tag.id; currentCol.rawVal=tag.rawData; currentCol.parseValue(); iterator.remove(); break; default : } } }
Fill in the given oneRowChange with info from this LCR
protected final DTMAxisIterator resetPosition(){ _position=0; return this; }
Reset the position to zero. NOTE that this does not change the iteration state, only the position number associated with that state. %REVIEW% Document when this would be used?
@Nullable public static <T>CloseableReference<T> cloneOrNull(@Nullable CloseableReference<T> ref){ return (ref != null) ? ref.cloneOrNull() : null; }
Returns the cloned reference if valid, null otherwise.
public DatabaseAggregatedTimerData(Timestamp timestamp,long platformIdent,long sensorTypeIdent,long methodIdent){ super(timestamp,platformIdent,sensorTypeIdent,methodIdent); }
Creates a new instance.
public static synchronized boolean deleteOldActivityDatabase(Context context){ DBHelper dbHelper=new DBHelper(context); boolean result=true; if (dbHelper.existsDB(DBConstants.DATABASE_NAME)) { result=getContext().deleteDatabase(DBConstants.DATABASE_NAME); } return result; }
Deletes the legacy (pre 0.12) Activity database
protected boolean isRegionVisible(DrawContext dc){ if (this.getCurrentData().getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && dc.getVisibleSector() != null && this.getCurrentData().getSector() != null && !dc.getVisibleSector().intersects(this.getCurrentData().getSector())) { return false; } if (this.getCurrentData().getExtent() != null && dc.isSmall(this.getCurrentData().getExtent(),1)) return false; return this.intersectsFrustum(dc); }
Indicates whether this Region is visible for the specified <code>DrawContext</code>. If this Region's <code>altitudeMode</code> is <code>clampToGround</code>, this Region is considered visible if its sector intersects the <code>DrawContext's</code> visible sector and its frustum intersects the <code>DrawContext's</code> viewing frustum. Otherwise, this Region is considered visible its frustum intersects the <code>DrawContext's</code> viewing frustum.
@Override public void update(ExampleSet exampleSet){ Attribute weightAttribute=exampleSet.getAttributes().getWeight(); for ( Example example : exampleSet) { double weight=weightAttribute == null ? 1.0d : example.getWeight(); totalWeight+=weight; double labelValue=example.getLabel(); if (!Double.isNaN(labelValue)) { int classIndex=(int)example.getLabel(); classWeights[classIndex]+=weight; int attributeIndex=0; for ( Attribute attribute : exampleSet.getAttributes()) { double attributeValue=example.getValue(attribute); if (nominal[attributeIndex]) { if (!Double.isNaN(attributeValue)) { if ((int)attributeValue < weightSums[attributeIndex][classIndex].length - 1) { weightSums[attributeIndex][classIndex][(int)attributeValue]+=weight; } else { for (int i=0; i < numberOfClasses; i++) { double[] newWeightSums=new double[(int)attributeValue + 2]; newWeightSums[newWeightSums.length - 1]=weightSums[attributeIndex][i][weightSums[attributeIndex][i].length - 1]; for (int j=0; j < weightSums[attributeIndex][i].length - 1; j++) { newWeightSums[j]=weightSums[attributeIndex][i][j]; } weightSums[attributeIndex][i]=newWeightSums; distributionProperties[attributeIndex][i]=new double[(int)attributeValue + 2]; } weightSums[attributeIndex][classIndex][(int)attributeValue]+=weight; attributeValues[attributeIndex]=new String[(int)attributeValue + 2]; for (int i=0; i < attributeValues[attributeIndex].length - 1; i++) { attributeValues[attributeIndex][i]=attribute.getMapping().mapIndex(i); } attributeValues[attributeIndex][attributeValues[attributeIndex].length - 1]=UNKNOWN_VALUE_NAME; } } else { weightSums[attributeIndex][classIndex][weightSums[attributeIndex][classIndex].length - 1]+=weight; } } else { if (!Double.isNaN(attributeValue)) { kernelDistributions[attributeIndex][classIndex].update(attributeValue,weight); } } attributeIndex++; } } } modelRecentlyUpdated=true; }
Updates the model by counting the occurrences of classes and attribute values in combination with the class values. ATTENTION: only updates the weight counters, distribution properties are not updated, call updateDistributionProperties() to accomplish this task
public static void main(final String[] args){ DOMTestCase.doMain(createAttributeNS01.class,args); }
Runs this test from the command line.
public boolean connectedToNetwork(URI networkUri){ if (networkUri != null) { if (networkUri.equals(_id)) { return true; } if (_routedNetworks != null) { return _routedNetworks.contains(networkUri.toString()); } } return false; }
Returns true if this network is connected to another network
public DecoWildWheat(int type){ farmtype=type == 0 ? Blocks.potatoes : type == 1 ? Blocks.carrots : Blocks.wheat; }
0 = potatoes, 1 = carrots, 2 = wheat
public void disconnected(){ }
Called when the DDM server disconnects. Can be used to disable periodic transmissions or clean up saved state.
private void parseAndFillEndpoints(NodeList children,EList<Endpoint> endpoints){ for (int i=0; i < children.getLength(); i++) { Node childNode=children.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && !"channel".equals(childNode.getLocalName())) { Endpoint endpoint=createEndpoint(childNode); if (endpoint != null) { endpoints.add(endpoint); if (endpoint instanceof CompositeProcessor) { NodeList compositeChildren=childNode.getChildNodes(); parseAndFillEndpoints(compositeChildren,((CompositeProcessor)endpoint).getOwnedEndpoints()); } } } } }
Parse children NodeList and fill the given endpoint collection.
public static Disjunction or(Criterion... criteria){ return new Disjunction(criteria); }
Return the disjunction of two expressions
private void validateTableMetaData_allNormalTables(String tableNamePattern) throws Exception { Set<String> expectedNormalTables=new HashSet<>(Arrays.asList("TEST_NORMAL_TABLE","test_quoted_normal_table")); Set<String> retrievedTables=new HashSet<>(); Map<TableMetaData,Object> rules=getDefaultValueValidationRules(); rules.put(TableMetaData.TABLE_TYPE,TABLE); try (ResultSet tables=dbmd.getTables(null,null,tableNamePattern,new String[]{TABLE})){ while (tables.next()) { String tableName=tables.getString(TableMetaData.TABLE_NAME.name()); assertTrue("TABLE_NAME is not allowed to be null or empty",tableName != null && tableName.length() > 0); retrievedTables.add(tableName); if ((tableName.startsWith("RDB$") || tableName.startsWith("MON$"))) { fail("Only expect normal tables, not starting with RDB$ or MON$, retrieved " + tableName); } validateRowValues(tables,rules); } assertEquals("getTables() did not return expected tables: ",expectedNormalTables,retrievedTables); } }
Helper method for test methods that retrieve table metadata of all normal tables.
private void goPrinterSetting(){ Intent intent=new Intent(getApplicationContext(),MainActivity_.class); startActivity(intent); this.finish(); }
go printer setting activity
protected boolean doQuery(String queryStr) throws AdeException { System.out.println("Querying the databse"); return super.doQuery(m_dataStore,queryStr); }
Perform Query given a SQL statement
public N4JSNewWizardsActionGroup(final IWorkbenchSite site){ fSite=site; }
Creates a new <code>NewWizardsActionGroup</code>. The group requires that the selection provided by the part's selection provider is of type <code> org.eclipse.jface.viewers.IStructuredSelection</code>.
public static int poisson(double lambda){ if (!(lambda > 0.0)) throw new IllegalArgumentException("Parameter lambda must be positive"); if (Double.isInfinite(lambda)) throw new IllegalArgumentException("Parameter lambda must not be infinite"); int k=0; double p=1.0; double L=Math.exp(-lambda); do { k++; p*=uniform(); } while (p >= L); return k - 1; }
Return an integer with a Poisson distribution with mean lambda.
public boolean isSetId(){ return EncodingUtils.testBit(__isset_bitfield,__ID_ISSET_ID); }
Returns true if field id is set (has been assigned a value) and false otherwise
protected void rehash(){ int oldCapacity=table.length; Entry oldMap[]=table; int newCapacity=oldCapacity * 2 + 1; Entry newMap[]=new Entry[newCapacity]; threshold=(int)(newCapacity * loadFactor); table=newMap; for (int i=oldCapacity; i-- > 0; ) { for (Entry old=oldMap[i]; old != null; ) { Entry e=old; old=old.next; int index=(e.hash & 0x7FFFFFFF) % newCapacity; e.next=newMap[index]; newMap[index]=e; } } }
<p>Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.</p> <p>This method is called automatically when the number of keys in the hashtable exceeds this hashtable's capacity and load factor.</p>
public static boolean startsWithPattern(final byte[] byteArray,final byte[] pattern){ Preconditions.checkNotNull(byteArray); Preconditions.checkNotNull(pattern); if (pattern.length > byteArray.length) { return false; } for (int i=0; i < pattern.length; ++i) { if (byteArray[i] != pattern[i]) { return false; } } return true; }
Checks if byteArray interpreted as sequence of bytes starts with pattern starting at position equal to offset.
public boolean remove(INode n){ return tree.remove(n) != null; }
Remove actual value from the set whose score is the same. <p> The score from the INode passed in is used to locate the desired INode within the set. As such, the behavior of this method may be surprising since you could have two nodes in the tree with the same score and one of them will be removed, though you won't know exactly which one.
@Override public void onAction(){ onAction(ActionType.USE); }
Perform the default action.
public static void connectFromMatlab(String receiverID,int port){ connect(receiverID,port,false); }
Called from MATLAB at launch. Creates the JMI wrapper and then sends it over RMI to the Java program running in a separate JVM.
public T caseFunctionBlockPropertySource(FunctionBlockPropertySource object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Function Block Property Source</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
private StyledString appendTypeParameterList(StyledString buffer,CompletionProposal typeProposal){ char[] signature=SignatureUtil.fix83600(typeProposal.getSignature()); char[][] typeParameters=Signature.getTypeArguments(signature); for (int i=0; i < typeParameters.length; i++) { char[] param=typeParameters[i]; typeParameters[i]=Signature.toCharArray(param); } return appendParameterSignature(buffer,typeParameters,null); }
Appends the type parameter list to <code>buffer</code>.
public static <K,V,E>Map<K,V> collectEntries(E[] self){ return collectEntries(self,Closure.IDENTITY); }
A variant of collectEntries using the identity closure as the transform.
public boolean addGpsDateTimeStampTag(long timestamp){ ExifTag t=buildTag(TAG_GPS_DATE_STAMP,mGPSDateStampFormat.format(timestamp)); if (t == null) { return false; } setTag(t); mGPSTimeStampCalendar.setTimeInMillis(timestamp); t=buildTag(TAG_GPS_TIME_STAMP,new Rational[]{new Rational(mGPSTimeStampCalendar.get(Calendar.HOUR_OF_DAY),1),new Rational(mGPSTimeStampCalendar.get(Calendar.MINUTE),1),new Rational(mGPSTimeStampCalendar.get(Calendar.SECOND),1)}); if (t == null) { return false; } setTag(t); return true; }
Creates and sets the GPS timestamp tag.
public static boolean sm(double a,double b){ return (b - a > SMALL); }
Tests if a is smaller than b.
public void startOrStopPlaying(View view){ if (mPingReceiver != null) { stopPlaying(); } else { int count=Integer.valueOf(mCountEditText.getText().toString()); if (count <= 0) UiUtils.showToast(this,"Please specify a count value that's > 0"); else startPlaying(count); } }
Called by the Android Activity framework when the user clicks the "startOrStopPlaying" button.
public int update(@NotNull @SQL String sql,Object... args){ return update(SqlQuery.query(sql,args)); }
Executes an update against the database and returns the amount of affected rows.
public LineEvent(Line line,Type type,long position){ super(line); this.type=type; this.position=position; }
Constructs a new event of the specified type, originating from the specified line.
public MandatoryUdaMissingException(String message,ApplicationExceptionBean bean,Throwable cause){ super(message,bean,cause); }
Constructs a new exception with the specified detail message, cause, and bean for JAX-WS exception serialization.
public Predicate<ExecutableSequence> createTestOutputPredicate(Set<Sequence> excludeSet,Set<Class<?>> coveredClasses,Pattern includePattern){ Predicate<ExecutableSequence> isOutputTest; if (GenInputsAbstract.dont_output_tests) { isOutputTest=new AlwaysFalse<>(); } else { Predicate<ExecutableSequence> baseTest; baseTest=new ExcludeTestPredicate(excludeSet); if (includePattern != null) { baseTest=baseTest.and(new IncludeTestPredicate(includePattern)); } if (!coveredClasses.isEmpty()) { baseTest=baseTest.and(new IncludeIfCoversPredicate(coveredClasses)); } Predicate<ExecutableSequence> checkTest=new AlwaysFalse<>(); if (!GenInputsAbstract.no_error_revealing_tests) { checkTest=new ErrorTestPredicate(); } if (!GenInputsAbstract.no_regression_tests) { checkTest=checkTest.or(new RegressionTestPredicate()); } isOutputTest=baseTest.and(checkTest); } return isOutputTest; }
Builds the test predicate that determines whether a particular sequence will be included in the output based on command-line arguments.
public final T callbackExecutor(Executor callbackExecutor){ this.callbackExecutor=checkNotNull(callbackExecutor,"callbackExecutor == null"); return self(); }
Sets the executor which will determine the thread on which callback will be invoked.
public int readTag() throws IOException { if (isAtEnd()) { lastTag=0; return 0; } lastTag=readRawVarint32(); if (lastTag == 0) { throw InvalidProtocolBufferNanoException.invalidTag(); } return lastTag; }
Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.
public static String toString(Object value,String defaultValue){ if (value == null) return defaultValue; return toString(value.toString(),defaultValue); }
returns string, if given string is null or lengt 0 return default value
protected boolean oneSameNetwork(MacAddress m1,MacAddress m2){ String net1=macToGuid.get(m1); String net2=macToGuid.get(m2); if (net1 == null) return false; if (net2 == null) return false; return net1.equals(net2); }
Checks to see if two MAC Addresses are on the same network.
public Enumerable<Object> project(final int[] fields){ return backingTable.project(fields); }
Returns an enumerable over a given projection of the fields. Called from generated code.
public TokenRO persistShoppingCart(final HttpServletRequest request,final HttpServletResponse response){ final ShoppingCart cart=getCurrentCart(); shoppingCartPersister.persistShoppingCart(request,response,cart); return new TokenRO(cart.getGuid()); }
Generate token ro for current state of the cart.
@Override public boolean isAllowAll(){ return _mode == RobotRulesMode.ALLOW_ALL; }
Is our ruleset set up to allow all access?
@Override public synchronized void stopAll(){ final Iterator<Map.Entry<Integer,BaseEvent>> it=instances.entrySet().iterator(); if (Cfg.DEBUG) { Check.log(TAG + " (stopAll)"); } while (it.hasNext()) { final Map.Entry<Integer,BaseEvent> pairs=it.next(); int key=pairs.getKey(); stop(key); } if (Cfg.DEBUG) { Check.ensures(threads.size() == 0,"Non empty threads"); } instances.clear(); threads.clear(); if (Cfg.DEBUG) { Check.ensures(instances.size() == 0,"Non empty running"); } }
Stop events.
public TreeViewerBuilder(Composite parent){ this(parent,SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL| SWT.FULL_SELECTION| SWT.BORDER); }
Creates a new TreeViewerBuilder with default SWT styles.
public QueryBuilder groupBy(final Optional<List<String>> groupBy){ checkNotNull(groupBy,"groupBy must not be null"); this.groupBy=pickOptional(this.groupBy,groupBy); return this; }
Specify a group by to use.