code
stringlengths
10
174k
nl
stringlengths
3
129k
public RemoteObjectInvocationHandler(RemoteRef ref){ super(ref); if (ref == null) { throw new NullPointerException(); } }
Creates a new <code>RemoteObjectInvocationHandler</code> constructed with the specified <code>RemoteRef</code>.
public Categories addCategory(Category category){ super.addElement(Category.KEY,category); return this; }
Adds a new category.
public static void append(File file,byte[] bytes) throws IOException { OutputStream stream=null; try { stream=new FileOutputStream(file,true); stream.write(bytes,0,bytes.length); stream.flush(); OutputStream temp=stream; stream=null; temp.close(); } finally { closeWithWarning(stream); } }
Append bytes to the end of a File. It <strong>will not</strong> be interpreted as text.
public DescriptorImpl(final String description,final String label){ this.description=description; this.label=label; }
Construct descriptor.
@Nullable public synchronized V remove(K key){ V oldValue=mMap.remove(key); mSizeInBytes-=getValueSizeInBytes(oldValue); return oldValue; }
Removes the element from the map.
public MediaConfig createChannelFileAttachment(String file,MediaConfig config){ config.addCredentials(this); String xml=POSTFILE(this.url + "/create-channel-attachment",file,config.name,config.toXML()); Element root=parse(xml); if (root == null) { return null; } try { MediaConfig media=new MediaConfig(); media.parseXML(root); return media; } catch ( Exception exception) { this.exception=SDKException.parseFailure(exception); throw this.exception; } }
Create a new file/image/media attachment for a chat channel.
public static boolean matchUserStatus(String id,User user){ if (id.equals("$mod")) { if (user.isModerator()) { return true; } } else if (id.equals("$sub")) { if (user.isSubscriber()) { return true; } } else if (id.equals("$turbo")) { if (user.hasTurbo()) { return true; } } else if (id.equals("$admin")) { if (user.isAdmin()) { return true; } } else if (id.equals("$broadcaster")) { if (user.isBroadcaster()) { return true; } } else if (id.equals("$staff")) { if (user.isStaff()) { return true; } } else if (id.equals("$bot")) { if (user.isBot()) { return true; } } else if (id.equals("$globalmod")) { if (user.isGlobalMod()) { return true; } } else if (id.equals("$anymod")) { if (user.isAdmin() || user.isBroadcaster() || user.isGlobalMod()|| user.isModerator()|| user.isStaff()) { return true; } } return false; }
Checks if the id matches the given User. The id can be one of: $mod, $sub, $turbo, $admin, $broadcaster, $staff, $bot. If the user has the appropriate user status, this returns true. If the id is unknown or the user doesn't have the required status, this returns false.
public static Selection createFromStartLength(int s,int l){ Assert.isTrue(s >= 0 && l >= 0); Selection result=new Selection(); result.fStart=s; result.fLength=l; result.fExclusiveEnd=s + l; return result; }
Creates a new selection from the given start and length.
public static byte[] hash(InputStream in) throws IOException { if (HASH_DIGEST == null) { throw new EvernoteUtilException(EDAM_HASH_ALGORITHM + " not supported",new NoSuchAlgorithmException(EDAM_HASH_ALGORITHM)); } byte[] buf=new byte[1024]; int n; while ((n=in.read(buf)) != -1) { HASH_DIGEST.update(buf,0,n); } return HASH_DIGEST.digest(); }
Returns an MD5 checksum of the contents of the provided InputStream.
@LayoutlibDelegate static long uptimeMillis(){ return System.currentTimeMillis() - sBootTime; }
Returns milliseconds since boot, not counting time spent in deep sleep. <b>Note:</b> This value may get reset occasionally (before it would otherwise wrap around).
void unregisterDownloadFileChangeListener(OnDownloadFileChangeListener onDownloadFileChangeListener){ mDownloadFileCacher.unregisterDownloadFileChangeListener(onDownloadFileChangeListener); }
unregister an OnDownloadFileChangeListener
public DateParser(){ this(DateFormat.getDateInstance(DateFormat.SHORT)); }
Create a new DateParser.
public ShoppingCartItem(ShoppingCartItem item){ this.delegator=item.getDelegator(); try { this._product=item.getProduct(); } catch ( IllegalStateException e) { this._product=null; } try { this._parentProduct=item.getParentProduct(); } catch ( IllegalStateException e) { this._parentProduct=null; } this.delegatorName=item.delegatorName; this.prodCatalogId=item.getProdCatalogId(); this.productId=item.getProductId(); this.supplierProductId=item.getSupplierProductId(); this.parentProductId=item.getParentProductId(); this.externalId=item.getExternalId(); this.itemType=item.getItemType(); this.itemGroup=item.getItemGroup(); this.productCategoryId=item.getProductCategoryId(); this.itemDescription=item.itemDescription; this.reservStart=item.getReservStart(); this.reservLength=item.getReservLength(); this.reservPersons=item.getReservPersons(); this.accommodationMapId=item.getAccommodationMapId(); this.accommodationSpotId=item.getAccommodationSpotId(); this.quantity=item.getQuantity(); this.setBasePrice(item.getBasePrice()); this.setDisplayPrice(item.getDisplayPrice()); this.setRecurringBasePrice(item.getRecurringBasePrice()); this.setRecurringDisplayPrice(item.getRecurringDisplayPrice()); this.setSpecialPromoPrice(item.getSpecialPromoPrice()); this.reserv2ndPPPerc=item.getReserv2ndPPPerc(); this.reservNthPPPerc=item.getReservNthPPPerc(); this.listPrice=item.getListPrice(); this.setIsModifiedPrice(item.getIsModifiedPrice()); this.selectedAmount=item.getSelectedAmount(); this.requirementId=item.getRequirementId(); this.quoteId=item.getQuoteId(); this.quoteItemSeqId=item.getQuoteItemSeqId(); this.associatedOrderId=item.getAssociatedOrderId(); this.associatedOrderItemSeqId=item.getAssociatedOrderItemSeqId(); this.orderItemAssocTypeId=item.getOrderItemAssocTypeId(); this.setStatusId(item.getStatusId()); if (UtilValidate.isEmpty(item.getOrderItemAttributes())) { this.orderItemAttributes=FastMap.<String,String>newInstance(); this.orderItemAttributes.putAll(item.getOrderItemAttributes()); } this.attributes=item.getAttributes() == null ? new HashMap<String,Object>() : new HashMap<String,Object>(item.getAttributes()); this.setOrderItemSeqId(item.getOrderItemSeqId()); this.locale=item.locale; this.setShipBeforeDate(item.getShipBeforeDate()); this.setShipAfterDate(item.getShipAfterDate()); this.setEstimatedShipDate(item.getEstimatedShipDate()); this.setCancelBackOrderDate(item.getCancelBackOrderDate()); this.contactMechIdsMap=item.getOrderItemContactMechIds() == null ? null : new HashMap<String,String>(item.getOrderItemContactMechIds()); this.orderItemPriceInfos=item.getOrderItemPriceInfos() == null ? null : new LinkedList<GenericValue>(item.getOrderItemPriceInfos()); this.itemAdjustments.addAll(item.getAdjustments()); this.isPromo=item.getIsPromo(); this.promoQuantityUsed=item.promoQuantityUsed; this.quantityUsedPerPromoCandidate=new HashMap<GenericPK,BigDecimal>(item.quantityUsedPerPromoCandidate); this.quantityUsedPerPromoFailed=new HashMap<GenericPK,BigDecimal>(item.quantityUsedPerPromoFailed); this.quantityUsedPerPromoActual=new HashMap<GenericPK,BigDecimal>(item.quantityUsedPerPromoActual); this.additionalProductFeatureAndAppls=item.getAdditionalProductFeatureAndAppls() == null ? null : new HashMap<String,GenericValue>(item.getAdditionalProductFeatureAndAppls()); if (item.getAlternativeOptionProductIds() != null) { List<String> tempAlternativeOptionProductIds=FastList.newInstance(); tempAlternativeOptionProductIds.addAll(item.getAlternativeOptionProductIds()); this.setAlternativeOptionProductIds(tempAlternativeOptionProductIds); } if (item.configWrapper != null) { this.configWrapper=new ProductConfigWrapper(item.configWrapper); } this.featuresForSupplier.addAll(item.featuresForSupplier); }
Clone an item.
public void writeText(char text[],int off,int len) throws IOException { if (text == null) { throw new NullPointerException("Argument Error: One or more parameters are null."); } if (off < 0 || off > text.length || len < 0 || len > text.length) { throw new IndexOutOfBoundsException(); } closeStartIfNecessary(); if (dontEscape) { writer.write(text,off,len); } else { Util.writeText(writer,buffer,text,off,len); } }
<p>Write properly escaped text from a character array. If there is an open element that has been created by a call to <code>startElement()</code>, that element will be closed first.</p> <p/> <p>All angle bracket occurrences in the argument must be escaped using the &amp;gt; &amp;lt; syntax.</p>
public void pleaseStop(){ stopping=true; mc.pleaseStop(); }
Requests that the MCMC chain stop prematurely.
public static boolean checkTransactionLockTime(Transaction transaction,int locktime){ if (Math.abs(transaction.getLockTime() - locktime) > 5 * 60) { System.out.println("Locktime not correct. Should be: " + locktime + " Is: "+ transaction.getLockTime()+ " Diff: "+ Math.abs(transaction.getLockTime() - locktime)); return false; } if (locktime == 0) { return true; } for ( TransactionInput input : transaction.getInputs()) { if (input.getSequenceNumber() == 0) { return true; } } System.out.println("No Sequence Number is 0.."); return false; }
Check transaction lock time.
@Override public void renderLimitLines(Canvas c){ List<LimitLine> limitLines=mXAxis.getLimitLines(); if (limitLines == null || limitLines.size() <= 0) return; float[] pts=new float[2]; Path limitLinePath=new Path(); for (int i=0; i < limitLines.size(); i++) { LimitLine l=limitLines.get(i); mLimitLinePaint.setStyle(Paint.Style.STROKE); mLimitLinePaint.setColor(l.getLineColor()); mLimitLinePaint.setStrokeWidth(l.getLineWidth()); mLimitLinePaint.setPathEffect(l.getDashPathEffect()); pts[1]=l.getLimit(); mTrans.pointValuesToPixel(pts); limitLinePath.moveTo(mViewPortHandler.contentLeft(),pts[1]); limitLinePath.lineTo(mViewPortHandler.contentRight(),pts[1]); c.drawPath(limitLinePath,mLimitLinePaint); limitLinePath.reset(); String label=l.getLabel(); if (label != null && !label.equals("")) { float xOffset=Utils.convertDpToPixel(4f); float yOffset=l.getLineWidth() + Utils.calcTextHeight(mLimitLinePaint,label) / 2f; mLimitLinePaint.setStyle(l.getTextStyle()); mLimitLinePaint.setPathEffect(null); mLimitLinePaint.setColor(l.getTextColor()); mLimitLinePaint.setStrokeWidth(0.5f); mLimitLinePaint.setTextSize(l.getTextSize()); if (l.getLabelPosition() == LimitLine.LimitLabelPosition.POS_RIGHT) { mLimitLinePaint.setTextAlign(Align.RIGHT); c.drawText(label,mViewPortHandler.contentRight() - xOffset,pts[1] - yOffset,mLimitLinePaint); } else { mLimitLinePaint.setTextAlign(Align.LEFT); c.drawText(label,mViewPortHandler.offsetLeft() + xOffset,pts[1] - yOffset,mLimitLinePaint); } } } }
Draws the LimitLines associated with this axis to the screen. This is the standard YAxis renderer using the XAxis limit lines.
public static void showCommandLineOptions(){ showCommandLineOptions(new TextUICommandLine()); }
Print command line options synopses to stdout.
public WordEntry find(final String str){ final WordEntry entry=words.get(trimWord(str)); return entry; }
Find an entry for a given word.
private void registerListener(final String requestUrl,final String target,String[] methods,Integer expireTime,String filter){ registerListener(requestUrl,target,methods,expireTime,filter,null); }
Registers a listener.
public AbstractTestContext(){ super(); }
Constructs a new <code>AbstractTestContext</code> instance.
public final String value(int valIndex){ if (!isNominal() && !isString()) { return ""; } else { Object val=m_Values.elementAt(valIndex); if (val instanceof SerializedObject) { val=((SerializedObject)val).getObject(); } return (String)val; } }
Returns a value of a nominal or string attribute. Returns an empty string if the attribute is neither nominal nor a string attribute.
public static void readSkel(BufferedReader reader) throws IOException { Vector lines=new Vector(); StringBuffer section=new StringBuffer(); String ln; while ((ln=reader.readLine()) != null) { if (ln.startsWith("---")) { lines.addElement(section.toString()); section.setLength(0); } else { section.append(ln); section.append(NL); } } if (section.length() > 0) lines.addElement(section.toString()); if (lines.size() != size) { Out.error(ErrorMessages.WRONG_SKELETON); throw new GeneratorException(); } line=new String[size]; for (int i=0; i < size; i++) line[i]=(String)lines.elementAt(i); }
Reads an external skeleton file from a BufferedReader.
@Override public void finishTerm(BlockTermState _state) throws IOException { IntBlockTermState state=(IntBlockTermState)_state; assert state.docFreq > 0; assert state.docFreq == docCount : state.docFreq + " vs " + docCount; final int singletonDocID; if (state.docFreq == 1) { singletonDocID=docDeltaBuffer[0]; } else { singletonDocID=-1; for (int i=0; i < docBufferUpto; i++) { final int docDelta=docDeltaBuffer[i]; final int freq=freqBuffer[i]; if (!writeFreqs) { docOut.writeVInt(docDelta); } else if (freqBuffer[i] == 1) { docOut.writeVInt((docDelta << 1) | 1); } else { docOut.writeVInt(docDelta << 1); docOut.writeVInt(freq); } } } final long lastPosBlockOffset; if (writePositions) { assert state.totalTermFreq != -1; if (state.totalTermFreq > BLOCK_SIZE) { lastPosBlockOffset=posOut.getFilePointer() - posStartFP; } else { lastPosBlockOffset=-1; } if (posBufferUpto > 0) { int lastPayloadLength=-1; int lastOffsetLength=-1; int payloadBytesReadUpto=0; for (int i=0; i < posBufferUpto; i++) { final int posDelta=posDeltaBuffer[i]; if (writePayloads) { final int payloadLength=payloadLengthBuffer[i]; if (payloadLength != lastPayloadLength) { lastPayloadLength=payloadLength; posOut.writeVInt((posDelta << 1) | 1); posOut.writeVInt(payloadLength); } else { posOut.writeVInt(posDelta << 1); } if (payloadLength != 0) { posOut.writeBytes(payloadBytes,payloadBytesReadUpto,payloadLength); payloadBytesReadUpto+=payloadLength; } } else { posOut.writeVInt(posDelta); } if (writeOffsets) { int delta=offsetStartDeltaBuffer[i]; int length=offsetLengthBuffer[i]; if (length == lastOffsetLength) { posOut.writeVInt(delta << 1); } else { posOut.writeVInt(delta << 1 | 1); posOut.writeVInt(length); lastOffsetLength=length; } } } if (writePayloads) { assert payloadBytesReadUpto == payloadByteUpto; payloadByteUpto=0; } } } else { lastPosBlockOffset=-1; } long skipOffset; if (docCount > BLOCK_SIZE) { skipOffset=skipWriter.writeSkip(docOut) - docStartFP; } else { skipOffset=-1; } state.docStartFP=docStartFP; state.posStartFP=posStartFP; state.payStartFP=payStartFP; state.singletonDocID=singletonDocID; state.skipOffset=skipOffset; state.lastPosBlockOffset=lastPosBlockOffset; docBufferUpto=0; posBufferUpto=0; lastDocID=0; docCount=0; }
Called when we are done adding docs to this term
public ApiException(int code,ObjectNode jsonResponse){ super((jsonResponse.get(ApiMethod.ERROR_NODE) != null) ? JsonUtils.stringFromJsonNode(jsonResponse.get(ApiMethod.ERROR_NODE),"message") : "No message returned"); this.code=code; }
Construct exception from JSON response
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public void testReorderAppDeploymentsAfterConfigurationVersionAndBeforeAdminServerName() throws Exception { WAR war=createWar(); deployer.createElementForDeployableInDomain(war,domain); deployer.reorderAppDeploymentsAfterConfigurationVersion(domain); String xml=this.xmlUtil.toString(domain); int indexOfConfigurationVersion=xml.indexOf("configuration-version"); int indexOfAppDeployment=xml.indexOf("app-deployment"); int indexOfAdminServerName=xml.indexOf("admin-server-name"); assertTrue(indexOfAppDeployment > indexOfConfigurationVersion); assertTrue(indexOfAppDeployment < indexOfAdminServerName); }
Test application deployment reordering.
public static int decode(byte[] data,OutputStream out) throws IOException { int off=0; int length=data.length; int endOffset=off + length; int bytesWritten=0; while (off < endOffset) { byte ch=data[off++]; if (ch == '_') { out.write(' '); } else if (ch == '=') { if (off + 1 >= endOffset) { throw new IOException("Invalid quoted printable encoding; truncated escape sequence"); } byte b1=data[off++]; byte b2=data[off++]; if (b1 == '\r') { if (b2 != '\n') { throw new IOException("Invalid quoted printable encoding; CR must be followed by LF"); } } else { int c1=hexToBinary(b1); int c2=hexToBinary(b2); out.write((c1 << UPPER_NIBBLE_SHIFT) | c2); bytesWritten++; } } else { out.write(ch); bytesWritten++; } } return bytesWritten; }
Decode the encoded byte data writing it to the given output stream.
public boolean isFovVisible(){ return (frustum.getSceneHints().getCullHint() != CullHint.Always); }
Get FOV visibility
public NotificationChain basicSetTypeArg(TypeArgument newTypeArg,NotificationChain msgs){ TypeArgument oldTypeArg=typeArg; typeArg=newTypeArg; if (eNotificationRequired()) { ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,TypeRefsPackage.TYPE_TYPE_REF__TYPE_ARG,oldTypeArg,newTypeArg); if (msgs == null) msgs=notification; else msgs.add(notification); } return msgs; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static String join(String separator,float[] elements){ if (elements == null || elements.length == 0) { return ""; } List<Float> list=new ArrayList<Float>(elements.length); for ( Float element : elements) { list.add(element); } return join(separator,list); }
Returns a string containing all float numbers concatenated by a specified separator.
public Position(int offset){ this(offset,0); }
Creates a new position with the given offset and length 0.
protected void onUnhandledException(WebURL webUrl,Throwable e){ String urlStr=(webUrl == null ? "NULL" : webUrl.getURL()); logger.warn("Unhandled exception while fetching {}: {}",urlStr,e.getMessage()); logger.info("Stacktrace: ",e); }
This function is called when a unhandled exception was encountered during fetching
private void createLdifFilesDirectory() throws FileOperationFailedException { String schemaExportDirName=getSchemaFilesDirectory(); _log.info("Schema ldif files directory {}",schemaExportDirName); File schemaExportDir=new File(schemaExportDirName); if (!schemaExportDir.exists()) { if (!schemaExportDir.mkdirs()) { throw new FileOperationFailedException("create","directory",schemaExportDirName); } } schemaExportDir.deleteOnExit(); String configExportDirName=getConfigFilesDirectory(); _log.info("Config ldif files directory {}",configExportDirName); File configExportDir=new File(configExportDirName); if (!configExportDir.exists()) { if (!configExportDir.mkdirs()) { throw new FileOperationFailedException("create","directory",configExportDirName); } } configExportDir.deleteOnExit(); }
Creates the dummy directory for the ldif files.
public void assertNull(Object object){ TestUtils.assertNull(object); }
This method just invokes the test utils method, it is here for convenience
public static String escapeXml(String s){ initializeEscapeMap(); if (s == null || s.length() == 0) { return s; } char[] sChars=s.toCharArray(); StringBuilder sb=new StringBuilder(); int lastReplacement=0; for (int i=0; i < sChars.length; i++) { if (isInvalidXMLCharacter(sChars[i])) { sb.append(sChars,lastReplacement,i - lastReplacement); sb.append(sChars[i] == 0xFFFE ? "\\ufffe" : xmlLowValueEscapeStrings[sChars[i]]); lastReplacement=i + 1; } } if (lastReplacement < sChars.length) { sb.append(sChars,lastReplacement,sChars.length - lastReplacement); } return StringEscapeUtils.escapeXml(sb.toString()); }
Escape XML entities and illegal characters in the given string. This enhances the functionality of org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping low-valued unprintable characters, which are not permitted by the W3C XML 1.0 specification.
public ButtonGroup(){ }
Creates a new <code>ButtonGroup</code>.
public JSONArray names(){ JSONArray ja=new JSONArray(); Iterator<String> keys=this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; }
Produce a JSONArray containing the names of the elements of this JSONObject.
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 boolean isHasBack(){ FacesContext realContext=FacesContext.getCurrentInstance(), copyContext=createShadowFacesContext(realContext); NavigationHandler nav=copyContext.getApplication().getNavigationHandler(); nav.handleNavigation(copyContext,null,"back"); return compareUIViewRoots(realContext.getViewRoot(),copyContext.getViewRoot()); }
<p>Check to see whether the current page should have a back button</p>
public LongSparseArrayDataRow(int size){ super(size); values=new long[size]; }
Creates a sparse array data row of the given size.
public PropertyAtom(final String id,final String key,final Object val){ super(id); this.key=key; this.val=val; }
Fully construct a property atom.
public void print(final CharSequence text) throws IOException { final int size=text.length(); int pos=0; for (int i=0; i < size; i++) { if (text.charAt(i) == '\n') { write(text.subSequence(pos,size),i - pos + 1); pos=i + 1; atStartOfLine=true; } } write(text.subSequence(pos,size),size - pos); }
Print text to the output stream.
private boolean isClosureProgram2(IStep step){ if (step == null) throw new IllegalArgumentException(); if (step.isRule()) return false; final IProgram program=(IProgram)step; if (program.isClosure()) return true; final Iterator<IStep> itr=program.steps(); while (itr.hasNext()) { if (isClosureProgram2(itr.next())) return true; } return false; }
<code>true</code> iff this program is or contains a closure operation.
public void destroy(){ super.destroy(); }
Destruction of the servlet. <br>
public void expandAll(){ if (!chkExpand.isChecked()) chkExpand.setChecked(true); TreeUtils.expandAll(menuTree); }
expand all node
public static SavedAdStyles run(AdSense adsense,int maxPageSize) throws Exception { System.out.println("================================================================="); System.out.printf("Listing all saved ad styles for default account\n"); System.out.println("================================================================="); String pageToken=null; SavedAdStyles savedAdStyles=null; do { savedAdStyles=adsense.savedadstyles().list().setMaxResults(maxPageSize).setPageToken(pageToken).execute(); if (savedAdStyles.getItems() != null && !savedAdStyles.getItems().isEmpty()) { for ( SavedAdStyle savedAdStyle : savedAdStyles.getItems()) { System.out.printf("Saved ad style with name \"%s\" was found.\n",savedAdStyle.getName()); } } else { System.out.println("No saved ad styles found."); } pageToken=savedAdStyles.getNextPageToken(); } while (pageToken != null); System.out.println(); return savedAdStyles; }
Runs this sample.
public static Border createEtchedLowered(){ Border b=new Border(); b.type=TYPE_ETCHED_LOWERED; b.themeColors=true; return b; }
Creates a lowered etched border with default colors, highlight is derived from the component and shadow is a plain dark color
public void reset(){ m_currentSearchIndex=0; }
Resets the cursor to the beginning.
public static void minimizeApp(Context context){ Intent startMain=new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startMain); }
Minimizes the app
public static void logDeviceInfo(String tag){ Log.d(tag,"Android SDK: " + Build.VERSION.SDK_INT + ", "+ "Release: "+ Build.VERSION.RELEASE+ ", "+ "Brand: "+ Build.BRAND+ ", "+ "Device: "+ Build.DEVICE+ ", "+ "Id: "+ Build.ID+ ", "+ "Hardware: "+ Build.HARDWARE+ ", "+ "Manufacturer: "+ Build.MANUFACTURER+ ", "+ "Model: "+ Build.MODEL+ ", "+ "Product: "+ Build.PRODUCT); }
Information about the current build, taken from system properties.
private void writePostResource(String path,Element postResourceEl){ if (getFileHandler().isDirectory(path)) { writeDirectoryPostResource(postResourceEl,path); } else if (path.toLowerCase().endsWith(".jar")) { writeJarPostResource(postResourceEl,path); } else { writeFilePostResource(postResourceEl,path); } }
Write post Resources using with a PostResources xml element
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToBitmapCacheSequence(Producer<CloseableReference<CloseableImage>> inputProducer){ BitmapMemoryCacheProducer bitmapMemoryCacheProducer=mProducerFactory.newBitmapMemoryCacheProducer(inputProducer); BitmapMemoryCacheKeyMultiplexProducer bitmapKeyMultiplexProducer=mProducerFactory.newBitmapMemoryCacheKeyMultiplexProducer(bitmapMemoryCacheProducer); ThreadHandoffProducer<CloseableReference<CloseableImage>> threadHandoffProducer=mProducerFactory.newBackgroundThreadHandoffProducer(bitmapKeyMultiplexProducer); return mProducerFactory.newBitmapMemoryCacheGetProducer(threadHandoffProducer); }
Bitmap cache get -> thread hand off -> multiplex -> bitmap cache
static Pair<byte[],Long> decomposeName(Column column){ ByteBuffer nameBuffer; if (column.isSetName()) { nameBuffer=column.bufferForName(); } else { nameBuffer=ByteBuffer.wrap(column.getName()); } return decompose(nameBuffer); }
Convenience method to get the name buffer for the specified column and decompose it into the name and timestamp.
public synchronized boolean hasMoreTokens(){ return (this.pos < this.sourceLength); }
Does this tokenizer have more tokens available?
public String sanitizeString(String string){ StringBuilder retval=new StringBuilder(); StringCharacterIterator iterator=new StringCharacterIterator(string); char character=iterator.current(); while (character != java.text.CharacterIterator.DONE) { if (character == '<') { retval.append("&lt;"); } else if (character == '>') { retval.append("&gt;"); } else if (character == '&') { retval.append("&amp;"); } else if (character == '\"') { retval.append("&quot;"); } else if (character == '\t') { addCharEntity(9,retval); } else if (character == '!') { addCharEntity(33,retval); } else if (character == '#') { addCharEntity(35,retval); } else if (character == '$') { addCharEntity(36,retval); } else if (character == '%') { addCharEntity(37,retval); } else if (character == '\'') { addCharEntity(39,retval); } else if (character == '(') { addCharEntity(40,retval); } else if (character == ')') { addCharEntity(41,retval); } else if (character == '*') { addCharEntity(42,retval); } else if (character == '+') { addCharEntity(43,retval); } else if (character == ',') { addCharEntity(44,retval); } else if (character == '-') { addCharEntity(45,retval); } else if (character == '.') { addCharEntity(46,retval); } else if (character == '/') { addCharEntity(47,retval); } else if (character == ':') { addCharEntity(58,retval); } else if (character == ';') { addCharEntity(59,retval); } else if (character == '=') { addCharEntity(61,retval); } else if (character == '?') { addCharEntity(63,retval); } else if (character == '@') { addCharEntity(64,retval); } else if (character == '[') { addCharEntity(91,retval); } else if (character == '\\') { addCharEntity(92,retval); } else if (character == ']') { addCharEntity(93,retval); } else if (character == '^') { addCharEntity(94,retval); } else if (character == '_') { addCharEntity(95,retval); } else if (character == '`') { addCharEntity(96,retval); } else if (character == '{') { addCharEntity(123,retval); } else if (character == '|') { addCharEntity(124,retval); } else if (character == '}') { addCharEntity(125,retval); } else if (character == '~') { addCharEntity(126,retval); } else { retval.append(character); } character=iterator.next(); } return retval.toString(); }
Sanitize strings for output. Copy from anet_java_sdk_sample_app\common\helper.jsp
public void install(RSyntaxTextArea textArea){ if (this.textArea != null) { uninstall(); } this.textArea=textArea; textArea.addCaretListener(this); }
Installs this listener on a text area. If it is already installed on another text area, it is uninstalled first.
public static int schemaInitialId(){ return FNV1_OFFSET_BASIS; }
Schema initial ID.
public long remainder(long instant){ throw unsupported(); }
Always throws UnsupportedOperationException
public Vertex randomSynthesize(Vertex source){ log("random synthesize",Level.FINE); return synthesizeResponse(null,null,null,true,null,source.getNetwork()); }
Self API for synthesizing a new response.
public final void testGetEncryptedData03() throws IOException { boolean performed=false; for (int i=0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { AlgorithmParameters ap=AlgorithmParameters.getInstance(EncryptedPrivateKeyInfoData.algName0[i][0]); ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding(EncryptedPrivateKeyInfoData.algName0[i][0])); EncryptedPrivateKeyInfo epki=new EncryptedPrivateKeyInfo(ap,EncryptedPrivateKeyInfoData.encryptedData); assertTrue(Arrays.equals(EncryptedPrivateKeyInfoData.encryptedData,epki.getEncryptedData())); performed=true; } catch ( NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed",performed); }
Test #3 for <code>getEncryptedData()</code> method <br> Assertion: returns the encrypted data <br> Test preconditions: test object created using ctor which takes algorithm parameters and encrypted data as a parameters <br> Expected: the equivalent encrypted data must be returned
@HLEFunction(nid=0x7D2F3D7F,version=271) public int sceJpegFinishMJpeg(){ return 0; }
Finishes the MJpeg library
@Override public void save(){ if (hasItem()) { EventLogConfiguration config=getItem().getEventLogConfiguration(); config.clear(); if (mBinaryLogger.isSelected()) { config.addLogger(EventLogType.BINARY_MESSAGE); } if (mDecodedLogger.isSelected()) { config.addLogger(EventLogType.DECODED_MESSAGE); } if (mCallEventLogger.isSelected()) { config.addLogger(EventLogType.CALL_EVENT); } } setModified(false); }
Saves the current configuration as the stored configuration
public static VOPricedParameter toVOPricedParameter(PricedParameter pricedParam,LocalizerFacade facade){ Parameter parameter=pricedParam.getParameter(); VOParameterDefinition paraDef=ParameterDefinitionAssembler.toVOParameterDefinition(parameter.getParameterDefinition(),facade); VOPricedParameter result=new VOPricedParameter(paraDef); result.setPricePerUser(pricedParam.getPricePerUser()); result.setPricePerSubscription(pricedParam.getPricePerSubscription()); result.setPricedOptions(ParameterOptionAssembler.toVOPricedOptions(pricedParam,facade)); result.setParameterKey(parameter.getKey()); result.setRoleSpecificUserPrices(PricedProductRoleAssembler.toVOPricedProductRoles(pricedParam.getRoleSpecificUserPrices(),facade)); result.setSteppedPrices(SteppedPriceAssembler.toVOSteppedPrices(pricedParam.getSteppedPrices())); updateValueObject(result,pricedParam); return result; }
Converts a priced parameter to the appropriate value object.
boolean isSimulation(){ return this.simulation; }
Returns true if this is a simulation.
public boolean easyConfig(String ssid,String password,boolean isVersion2){ JsonObject initJsonObjectParams=broadlinkStandardParams(BroadlinkConstants.CMD_EASY_CONFIG_ID,BroadlinkConstants.CMD_EASY_CONFIG); initJsonObjectParams.addProperty("ssid",ssid); initJsonObjectParams.addProperty("password",password); initJsonObjectParams.addProperty("broadlinkv2",isVersion2 ? 1 : 0); JsonObject out=broadlinkExecuteCommand(initJsonObjectParams); int code=out.get(BroadlinkConstants.CODE).getAsInt(); return code == 0; }
Magic config
public Object newInstance(String owner) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return itemCtor.newInstance(owner); }
Called by the APIProviderImpl to construct the API wrapper passed to it on its construction.
public static boolean canWrite(String fileName){ return FilePath.get(fileName).canWrite(); }
Check if the file is writable. This method is similar to Java 7 <code>java.nio.file.Path.checkAccess(AccessMode.WRITE)</code>
public boolean implies(Permission p){ return true; }
Checks if the specified permission is "implied" by this object. This method always returns true.
@DSComment("Utility function") @DSSafe(DSCat.UTIL_FUNCTION) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:27:51.466 -0500",hash_original_method="A988E80FBF926E38476CB13622AE0017",hash_generated_method="7C5E5705B6EC3452A5193A1A55FAF86A") public static boolean isWellFormedSmsAddress(String address){ String networkPortion=PhoneNumberUtils.extractNetworkPortion(address); return (!(networkPortion.equals("+") || TextUtils.isEmpty(networkPortion))) && isDialable(networkPortion); }
Return true iff the network portion of <code>address</code> is, as far as we can tell on the device, suitable for use as an SMS destination address.
public List<Map<String,Object>> query(final String indexName,final String q,final Operator operator,final int offset,final int count){ assert count > 1; SearchRequestBuilder request=elasticsearchClient.prepareSearch(indexName).setQuery(QueryBuilders.multiMatchQuery(q,"_all").operator(operator).zeroTermsQuery(ZeroTermsQuery.ALL)).setFrom(offset).setSize(count); SearchResponse response=request.execute().actionGet(); SearchHit[] hits=response.getHits().getHits(); ArrayList<Map<String,Object>> result=new ArrayList<Map<String,Object>>(); for ( SearchHit hit : hits) { Map<String,Object> map=hit.getSource(); result.add(map); } return result; }
Query with a string and boundaries. The string is supposed to be something that the user types in without a technical syntax. The mapping of the search terms into the index can be different according to a search type. Please see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html. A better way to do this would be the usage of a cursor. See the delete method to find out how cursors work.
public static boolean isPattern(String pattern){ return pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1; }
Returns <code>true</code> if the specified pattern string contains wildcard characters.
public static void sort(int[] array,int start,int end){ DualPivotQuicksort.sort(array,start,end); }
Sorts the specified range in the array in ascending numerical order.
public static void main(String[] args) throws Exception { int timeout=Integer.MIN_VALUE; int maxContentLength=Integer.MIN_VALUE; String logLevel="info"; boolean followTalk=false; boolean keepConnection=false; boolean dumpContent=false; String urlString=null; String usage="Usage: Ftp [-logLevel level] [-followTalk] [-keepConnection] [-timeout N] [-maxContentLength L] [-dumpContent] url"; if (args.length == 0) { System.err.println(usage); System.exit(-1); } for (int i=0; i < args.length; i++) { if (args[i].equals("-logLevel")) { logLevel=args[++i]; } else if (args[i].equals("-followTalk")) { followTalk=true; } else if (args[i].equals("-keepConnection")) { keepConnection=true; } else if (args[i].equals("-timeout")) { timeout=Integer.parseInt(args[++i]) * 1000; } else if (args[i].equals("-maxContentLength")) { maxContentLength=Integer.parseInt(args[++i]); } else if (args[i].equals("-dumpContent")) { dumpContent=true; } else if (i != args.length - 1) { System.err.println(usage); System.exit(-1); } else { urlString=args[i]; } } Ftp ftp=new Ftp(); ftp.setFollowTalk(followTalk); ftp.setKeepConnection(keepConnection); if (timeout != Integer.MIN_VALUE) ftp.setTimeout(timeout); if (maxContentLength != Integer.MIN_VALUE) ftp.setMaxContentLength(maxContentLength); Content content=ftp.getProtocolOutput(urlString,WebPage.newBuilder().build()).getContent(); System.err.println("Content-Type: " + content.getContentType()); System.err.println("Content-Length: " + content.getMetadata().get(Response.CONTENT_LENGTH)); System.err.println("Last-Modified: " + content.getMetadata().get(Response.LAST_MODIFIED)); if (dumpContent) { System.out.print(new String(content.getContent())); } ftp=null; }
For debugging.
public void write(ArrayList data){ data.add(xCoord); data.add(yCoord); data.add(zCoord); data.add(dimensionId); }
Writes this Coord4D's data to an ArrayList for packet transfer.
public String toString(){ if (_name != null) return "Lifecycle[" + _name + ", "+ getStateName()+ "]"; else return "Lifecycle[" + getStateName() + "]"; }
Debug string value.
public SVG12DOMImplementation(){ factories=svg12Factories; registerFeature("CSS","2.0"); registerFeature("StyleSheets","2.0"); registerFeature("SVG",new String[]{"1.0","1.1","1.2"}); registerFeature("SVGEvents",new String[]{"1.0","1.1","1.2"}); }
Creates a new SVGDOMImplementation object.
private static <T>T attemptLoad(final Class<T> ofClass,final String className){ if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Attempting service load: " + className); } Level level; Exception thrown; try { Class clazz=Class.forName(className); if (!ofClass.isAssignableFrom(clazz)) { if (LOG.isLoggable(Level.WARNING)) { LOG.warning(clazz.getName() + " is not assignable to " + ofClass.getName()); } return null; } return ofClass.cast(clazz.newInstance()); } catch ( ClassNotFoundException ex) { level=Level.FINEST; thrown=ex; } catch ( InstantiationException ex) { level=Level.WARNING; thrown=ex; } catch ( IllegalAccessException ex) { level=Level.WARNING; thrown=ex; } LOG.log(level,"Could not load " + ofClass.getSimpleName() + " instance: "+ className,thrown); return null; }
Attempts to load the specified implementation class. Attempts will fail if - for example - the implementation depends on a class not found on the classpath.
@Override public void write(byte b[]) throws IOException { write(b,0,b.length); }
Write <code>b.length</code> bytes from the specified byte array to our output stream.
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public int countTestCases(){ return 1; }
Counts the number of test cases executed by run(TestResult result).
public void overwriteSetSelectedText(String str){ if (!overwrite || selectionStart != selectionEnd) { setSelectedText(str); return; } int caret=getCaretPosition(); int caretLineEnd=getLineEndOffset(getCaretLine()); if (caretLineEnd - caret <= str.length()) { setSelectedText(str); return; } document.beginCompoundEdit(); try { document.remove(caret,str.length()); document.insertString(caret,str,null); } catch ( BadLocationException bl) { bl.printStackTrace(); } finally { document.endCompoundEdit(); } }
Similar to <code>setSelectedText()</code>, but overstrikes the appropriate number of characters if overwrite mode is enabled.
public void runTest() throws Throwable { Document doc; NodeList elementList; Element testEmployee; Attr domesticAttr; doc=(Document)load("hc_staff",true); elementList=doc.getElementsByTagName("acronym"); testEmployee=(Element)elementList.item(0); domesticAttr=testEmployee.getAttributeNode("invalidAttribute"); assertNull("elementGetAttributeNodeNullAssert",domesticAttr); }
Runs the test case.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:30:30.339 -0500",hash_original_method="72982976B71B01DF2412198462460DF0",hash_generated_method="3FC970F17DE45AAF7F1BC31C989BC4E0") final public boolean isVisible(){ return isAdded() && !isHidden() && mView != null && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE; }
Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.
public boolean checkError(){ Writer delegate=out; if (delegate == null) { return ioError; } flush(); return ioError || delegate.checkError(); }
Flushes this writer and returns the value of the error flag.
private boolean showHelpOnFirstLaunch(){ try { PackageInfo info=getPackageManager().getPackageInfo(PACKAGE_NAME,0); int currentVersion=info.versionCode; SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); int lastVersion=prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN,0); if (currentVersion > lastVersion) { prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN,currentVersion).commit(); Intent intent=new Intent(this,HelpActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); String page=lastVersion == 0 ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE; intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY,page); startActivity(intent); return true; } } catch ( PackageManager.NameNotFoundException e) { Log.w(TAG,e); } return false; }
We want the help screen to be shown automatically the first time a new version of the app is run. The easiest way to do this is to check android:versionCode from the manifest, and compare it to a value stored as a preference.
public boolean isReviewer(ReviewDb db,@Nullable ChangeData cd) throws OrmException { if (getUser().isIdentifiedUser()) { Collection<Account.Id> results=changeData(db,cd).reviewers().all(); return results.contains(getUser().getAccountId()); } return false; }
Is this user a reviewer for the change?
public CLocalEdgeCommentWrapper(final INaviEdge edge){ m_edge=edge; }
Creates a new wrapper object.
public void reverse(){ long tmp; int limit=size / 2; int j=size - 1; long[] theElements=elements; for (int i=0; i < limit; ) { tmp=theElements[i]; theElements[i++]=theElements[j]; theElements[j--]=tmp; } }
Reverses the elements of the receiver. Last becomes first, second last becomes second first, and so on.
@Override public Boolean visitArray_Array(final AnnotatedArrayType type1,final AnnotatedArrayType type2,final VisitHistory visited){ if (!arePrimeAnnosEqual(type1,type2)) { return false; } return areEqual(type1.getComponentType(),type2.getComponentType(),visited); }
Two arrays are equal if: 1) Their sets of primary annotations are equal 2) Their component types are equal
private void addRoleBasedRecuringCharges(PriceConverter formatter,RDOUserFees userFee,List<RDORole> roles){ for ( RDORole role : roles) { RDORole existingRole=userFee.getRole(role.getRoleId()); if (existingRole == null) { userFee.getRoles().add(role); } else { existingRole.setBasePrice(role.getBasePrice()); existingRole.setFactor(ValueRounder.roundValue(new BigDecimal(role.getFactor()),formatter.getActiveLocale(),ValueRounder.SCALING_FACTORS)); existingRole.setPrice(role.getPrice()); } } }
Merge the given RDORoles into the given RDOUserFees
public StreamStatusWriter(String path,TwitchApi api){ this.path=path; this.api=api; }
Creates a new instance.
private static void addWeaponQuirk(List<QuirkEntry> quirkEntries,@Nullable Mounted m,int loc,int slot,String unitId,Entity entity){ if (m == null) { return; } if (m.countQuirks() > 0) { WeaponQuirks weapQuirks=m.getQuirks(); Enumeration<IOptionGroup> quirksGroup=weapQuirks.getGroups(); Enumeration<IOption> quirkOptions; while (quirksGroup.hasMoreElements()) { IOptionGroup group=quirksGroup.nextElement(); quirkOptions=group.getSortedOptions(); while (quirkOptions.hasMoreElements()) { IOption option=quirkOptions.nextElement(); if (!option.booleanValue()) { continue; } QuirkEntry qe=new QuirkEntry(option.getName(),entity.getLocationAbbr(loc),slot,m.getType().getInternalName(),unitId); quirkEntries.add(qe); } } } }
Convenience method for adding a weapon quirk to the quirk entries list.
public static void toggleFavorite(){ try { if (musicPlaybackService != null) { musicPlaybackService.toggleFavorite(); } } catch ( final RemoteException ignored) { } }
Toggles the current song as a favorite.
public void onSwapRemove(int cnt){ swapRemoves.addAndGet(cnt); if (delegate != null) delegate.onSwapRemove(cnt); }
Swap remove callback.
private final void nextToken(){ if (m_queueMark < m_ops.getTokenQueueSize()) { m_token=(String)m_ops.m_tokenQueue.elementAt(m_queueMark++); m_tokenChar=m_token.charAt(0); } else { m_token=null; m_tokenChar=0; } }
Retrieve the next token from the command and store it in m_token string.
public static int dp2px(Context context,float dp){ float px=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics()); return Math.round(px); }
Convert a dp float value to pixels
@Override public void run(){ amIActive=true; String inputFile; String outputFile; int progress; int i, n; int numFeatures; int oneHundredthTotal; ShapeType shapeType, outputShapeType; GeometryFactory factory=new GeometryFactory(); double distTolerance=10; boolean loseNoFeatures=false; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputFile=args[0]; outputFile=args[1]; distTolerance=Double.parseDouble(args[2]); loseNoFeatures=Boolean.parseBoolean(args[3]); if ((inputFile == null) || (outputFile == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { ShapeFile input=new ShapeFile(inputFile); shapeType=input.getShapeType(); if (shapeType.getBaseType() != ShapeType.POLYGON && shapeType.getBaseType() != ShapeType.POLYLINE) { showFeedback("This tool only works with shapefiles of a polygon or line base shape type."); return; } if (shapeType.getBaseType() == ShapeType.POLYGON) { outputShapeType=ShapeType.POLYGON; } else if (shapeType.getBaseType() == ShapeType.POLYLINE) { outputShapeType=ShapeType.POLYLINE; } else { showFeedback("This tool only works with shapefiles of a polygon or line base shape type."); return; } int numOutputFields=input.getAttributeTable().getFieldCount() + 1; int numInputFields=input.getAttributeTable().getFieldCount(); DBFField[] inputFields=input.getAttributeTable().getAllFields(); DBFField fields[]=new DBFField[numOutputFields]; fields[0]=new DBFField(); fields[0].setName("PARENT_ID"); fields[0].setDataType(DBFField.DBFDataType.NUMERIC); fields[0].setFieldLength(10); fields[0].setDecimalCount(0); System.arraycopy(inputFields,0,fields,1,numInputFields); ShapeFile output=new ShapeFile(outputFile,outputShapeType,fields); output.setProjectionStringFromOtherShapefile(input); numFeatures=input.getNumberOfRecords(); oneHundredthTotal=numFeatures / 100; n=0; progress=0; com.vividsolutions.jts.geom.Geometry[] recJTS=null; int recordNum; for ( ShapeFileRecord record : input.records) { recordNum=record.getRecordNumber(); Object[] attData=input.getAttributeTable().getRecord(recordNum - 1); recJTS=record.getGeometry().getJTSGeometries(); ArrayList<com.vividsolutions.jts.geom.Geometry> geomList=new ArrayList<>(); for (int a=0; a < recJTS.length; a++) { geomList.add(recJTS[a]); } DouglasPeuckerSimplifier dps=new DouglasPeuckerSimplifier(factory.buildGeometry(geomList)); dps.setDistanceTolerance(distTolerance); com.vividsolutions.jts.geom.Geometry outputGeom=dps.getResultGeometry(); if (outputGeom.isEmpty() && loseNoFeatures) { outputGeom=factory.buildGeometry(geomList); } if (!outputGeom.isEmpty()) { for (int a=0; a < outputGeom.getNumGeometries(); a++) { com.vividsolutions.jts.geom.Geometry g=outputGeom.getGeometryN(a); if (g instanceof com.vividsolutions.jts.geom.Polygon && !g.isEmpty()) { com.vividsolutions.jts.geom.Polygon p=(com.vividsolutions.jts.geom.Polygon)g; ArrayList<ShapefilePoint> pnts=new ArrayList<>(); int[] parts=new int[p.getNumInteriorRing() + 1]; Coordinate[] buffCoords=p.getExteriorRing().getCoordinates(); if (!Topology.isLineClosed(buffCoords)) { System.out.println("Exterior ring not closed."); } if (Topology.isClockwisePolygon(buffCoords)) { for (i=0; i < buffCoords.length; i++) { pnts.add(new ShapefilePoint(buffCoords[i].x,buffCoords[i].y)); } } else { for (i=buffCoords.length - 1; i >= 0; i--) { pnts.add(new ShapefilePoint(buffCoords[i].x,buffCoords[i].y)); } } for (int b=0; b < p.getNumInteriorRing(); b++) { parts[b + 1]=pnts.size(); buffCoords=p.getInteriorRingN(b).getCoordinates(); if (!Topology.isLineClosed(buffCoords)) { System.out.println("Interior ring not closed."); } if (Topology.isClockwisePolygon(buffCoords)) { for (i=buffCoords.length - 1; i >= 0; i--) { pnts.add(new ShapefilePoint(buffCoords[i].x,buffCoords[i].y)); } } else { for (i=0; i < buffCoords.length; i++) { pnts.add(new ShapefilePoint(buffCoords[i].x,buffCoords[i].y)); } } } PointsList pl=new PointsList(pnts); whitebox.geospatialfiles.shapefile.Polygon wbPoly=new whitebox.geospatialfiles.shapefile.Polygon(parts,pl.getPointsArray()); Object[] rowData=new Object[numOutputFields]; rowData[0]=new Double(recordNum - 1); System.arraycopy(attData,0,rowData,1,numInputFields); output.addRecord(wbPoly,rowData); } else if (g instanceof com.vividsolutions.jts.geom.LineString && !g.isEmpty()) { LineString ls=(LineString)g; ArrayList<ShapefilePoint> pnts=new ArrayList<>(); int[] parts={0}; Coordinate[] coords=ls.getCoordinates(); for (i=0; i < coords.length; i++) { pnts.add(new ShapefilePoint(coords[i].x,coords[i].y)); } PointsList pl=new PointsList(pnts); whitebox.geospatialfiles.shapefile.PolyLine wbGeometry=new whitebox.geospatialfiles.shapefile.PolyLine(parts,pl.getPointsArray()); Object[] rowData=new Object[numOutputFields]; rowData[0]=new Double(recordNum - 1); System.arraycopy(attData,0,rowData,1,numInputFields); output.addRecord(wbGeometry,rowData); } } } n++; if (n >= oneHundredthTotal) { n=0; if (cancelOp) { cancelOperation(); return; } progress++; updateProgress(progress); } } output.write(); updateProgress("Displaying vector: ",0); returnData(outputFile); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
private boolean isIdentifier(String token){ int size=token.length(); for (int i=0; i < size; i++) { char c=token.charAt(i); if (isOperator(c)) return false; } if (token.startsWith("'") && token.endsWith("'")) return false; else { try { new BigDecimal(token); return false; } catch ( NumberFormatException e) { } } if (isSQLFunctions(token)) return false; return true; }
Check if token is a valid sql identifier
@Override public void run(){ amIActive=true; String inputHeader; String outputHeader; int row, col; int progress=0; double z, w, wN; int i, n; int[] dX={1,1,1,0,-1,-1,-1,0}; int[] dY={-1,0,1,1,1,0,-1,-1}; double largeValue=Float.MAX_VALUE; double smallValue=0.0001; boolean somethingDone; int loopNum=1; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader=args[0]; outputHeader=args[1]; smallValue=Double.parseDouble(args[2]); if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster DEM=new WhiteboxRaster(inputHeader,"r"); int rows=DEM.getNumberRows(); int cols=DEM.getNumberColumns(); double noData=DEM.getNoDataValue(); double noDataOutput=-32768.0; WhiteboxRaster output; if (smallValue < 0.01 && smallValue > 0) { output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.DOUBLE,largeValue); } else { output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,largeValue); } output.setNoDataValue(noDataOutput); double[] data=null; for (row=0; row < rows; row++) { data=DEM.getRowValues(row); if (row == 0 || row == (rows - 1)) { for (col=0; col < cols; col++) { if (data[col] != noData) { output.setValue(row,col,data[col]); } else { output.setValue(row,col,noDataOutput); } } } else { for (col=0; col < cols; col++) { z=data[col]; if (z == noData) { output.setValue(row,col,noDataOutput); } else { output.setValue(row,col,z); break; } } for (col=cols - 1; col >= 0; col--) { z=data[col]; if (z == noData) { output.setValue(row,col,noDataOutput); } else { output.setValue(row,col,z); break; } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 1:",progress); } i=0; do { loopNum++; somethingDone=false; switch (i) { case 0: for (row=1; row < (rows - 1); row++) { for (col=1; col < (cols - 1); col++) { z=DEM.getValue(row,col); w=output.getValue(row,col); if (w > z) { for (n=0; n < 8; n++) { wN=output.getValue(row + dY[n],col + dX[n]) + smallValue; if (z == noData && wN == noDataOutput) { w=noDataOutput; output.setValue(row,col,w); } if (wN < w) { if (wN > z) { output.setValue(row,col,wN); w=wN; } else { output.setValue(row,col,z); break; } somethingDone=true; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } break; case 1: for (row=(rows - 2); row >= 1; row--) { for (col=(cols - 2); col >= 1; col--) { z=DEM.getValue(row,col); w=output.getValue(row,col); if (w > z) { for (n=0; n < 8; n++) { wN=output.getValue(row + dY[n],col + dX[n]) + smallValue; if (z == noData && wN == noDataOutput) { w=noDataOutput; output.setValue(row,col,w); } if (wN < w) { if (wN > z) { output.setValue(row,col,wN); w=wN; } else { output.setValue(row,col,z); break; } somethingDone=true; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * (rows - row) / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } break; case 2: for (row=1; row < (rows - 1); row++) { for (col=(cols - 2); col >= 1; col--) { z=DEM.getValue(row,col); w=output.getValue(row,col); if (w > z) { for (n=0; n < 8; n++) { wN=output.getValue(row + dY[n],col + dX[n]) + smallValue; if (z == noData && wN == noDataOutput) { w=noDataOutput; output.setValue(row,col,w); } if (wN < w) { if (wN > z) { output.setValue(row,col,wN); w=wN; } else { output.setValue(row,col,z); break; } somethingDone=true; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } break; case 3: for (row=(rows - 2); row >= 1; row--) { for (col=1; col < (cols - 1); col++) { z=DEM.getValue(row,col); w=output.getValue(row,col); if (w > z) { for (n=0; n < 8; n++) { wN=output.getValue(row + dY[n],col + dX[n]) + smallValue; if (z == noData && wN == noDataOutput) { w=noDataOutput; output.setValue(row,col,w); } if (wN < w) { if (wN > z) { output.setValue(row,col,wN); w=wN; } else { output.setValue(row,col,z); break; } somethingDone=true; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * (rows - row) / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } break; } i++; if (i > 3) { i=0; } } while (somethingDone); loopNum++; double zN; dX=new int[]{-1,0,1,1,-1}; dY=new int[]{-1,-1,-1,0,0}; for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=DEM.getValue(row,col); if (z == noData && output.getValue(row,col) != noDataOutput) { for (i=0; i < 5; i++) { zN=output.getValue(row + dY[i],col + dX[i]); if (zN == noDataOutput) { output.setValue(row,col,noDataOutput); break; } } } } for (col=cols - 1; col >= 0; col--) { z=DEM.getValue(row,col); if (z == noData && output.getValue(row,col) != noDataOutput) { for (i=0; i < 5; i++) { zN=output.getValue(row + dY[i],col + dX[i]); if (zN == noDataOutput) { output.setValue(row,col,noDataOutput); break; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } loopNum++; dX=new int[]{-1,0,1,1,-1}; dY=new int[]{1,1,1,0,0}; for (row=rows - 1; row >= 0; row--) { for (col=0; col < cols; col++) { z=DEM.getValue(row,col); if (z == noData && output.getValue(row,col) != noDataOutput) { for (i=0; i < 5; i++) { zN=output.getValue(row + dY[i],col + dX[i]); if (zN == noDataOutput) { output.setValue(row,col,noDataOutput); break; } } } } for (col=cols - 1; col >= 0; col--) { z=DEM.getValue(row,col); if (z == noData && output.getValue(row,col) != noDataOutput) { for (i=0; i < 5; i++) { zN=output.getValue(row + dY[i],col + dX[i]); if (zN == noDataOutput) { output.setValue(row,col,noDataOutput); break; } } } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * (rows - row) / (rows - 1)); updateProgress("Loop " + loopNum + ":",progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); DEM.close(); output.flush(); output.findMinAndMaxVals(); output.close(); returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.