code
stringlengths
10
174k
nl
stringlengths
3
129k
public RotationAnimation(View view){ this.view=view; degrees=360; pivot=PIVOT_CENTER; interpolator=new AccelerateDecelerateInterpolator(); duration=DURATION_LONG; listener=null; }
This animation rotates the view by a customizable number of degrees and at a customizable pivot point.
protected void validateClusterHosts(){ if (hostCluster != null) { VcenterDataCenter datacenter=getModelClient().datacenters().findById(datacenterId); Cluster cluster=getModelClient().clusters().findById(hostCluster.getId()); ClusterComputeResource vcenterCluster=vmware.getCluster(datacenter.getLabel(),cluster.getLabel()); if (vcenterCluster == null) { ExecutionUtils.fail("failTask.vmware.cluster.notfound",args(),args(cluster.getLabel())); } Set<String> vCenterHostUuids=Sets.newHashSet(); for ( HostSystem hostSystem : vcenterCluster.getHosts()) { if (hostSystem.getHardware() != null && hostSystem.getHardware().systemInfo != null) { vCenterHostUuids.add(hostSystem.getHardware().systemInfo.uuid); } } List<Host> dbHosts=getModelClient().hosts().findByCluster(hostCluster.getId()); Set<String> dbHostUuids=Sets.newHashSet(); for ( Host host : dbHosts) { if (!DiscoveredDataObject.CompatibilityStatus.COMPATIBLE.toString().equalsIgnoreCase(host.getCompatibilityStatus())) { ExecutionUtils.fail("failTask.vmware.cluster.hostincompatible",args(),args(cluster.getLabel(),host.getLabel())); } else if (DiscoveredDataObject.DataCollectionJobStatus.ERROR.toString().equalsIgnoreCase(host.getDiscoveryStatus())) { ExecutionUtils.fail("failTask.vmware.cluster.hostsdiscoveryfailed",args(),args(cluster.getLabel(),host.getLabel())); } dbHostUuids.add(host.getUuid()); } if (!vCenterHostUuids.equals(dbHostUuids)) { ExecutionUtils.fail("failTask.vmware.cluster.mismatch",args(),args(cluster.getLabel())); } else { info("Hosts in cluster %s matches correctly",cluster.getLabel()); } } }
Validates the vCenter cluster hosts match the same hosts we have in our database for the cluster. If there is a mismatch the check will fail the order.
public PaymentGatewayExt(){ }
Creates a new instance of PaymentGatewayExt
public boolean equals(Object o){ return this == o; }
Equal iff the same instance.
protected Instances headerFromXML() throws Exception { Instances result; Element root; Element node; Vector<Element> list; ArrayList<Attribute> atts; Version version; int[] classIndex; root=m_Document.getDocumentElement(); version=new Version(); if (version.isOlder(root.getAttribute(ATT_VERSION))) { System.out.println("WARNING: loading data of version " + root.getAttribute(ATT_VERSION) + " with version "+ Version.VERSION); } list=getChildTags(root,TAG_HEADER); node=list.get(0); list=getChildTags(node,TAG_ATTRIBUTES); node=list.get(0); classIndex=new int[1]; atts=createAttributes(node,classIndex); result=new Instances(root.getAttribute(ATT_NAME),atts,0); result.setClassIndex(classIndex[0]); return result; }
generates the header from the XML document
public static void validateInput(String field,String message) throws CheckException { validateInputSizeMax(field,message,64); }
Valid classic input.
public boolean verifyKeyedChecksum(byte[] data,int size,byte[] key,byte[] checksum,int usage) throws KrbCryptoException { try { byte[] newCksum=Aes128.calculateChecksum(key,usage,data,0,size); return isChecksumEqual(checksum,newCksum); } catch ( GeneralSecurityException e) { KrbCryptoException ke=new KrbCryptoException(e.getMessage()); ke.initCause(e); throw ke; } }
Verifies keyed checksum.
public static ActionBarBackground fadeOut(AppCompatActivity activity){ ActionBarBackground abColor=new ActionBarBackground(activity); abColor.fadeOut(); return abColor; }
Fade the ActionBar background to zero opacity
public boolean onUpOrCancel(){ boolean state=isPressed(); setPressed(false); return state; }
Set state for an onUpOrCancel event.
protected void storeState(){ }
Additional state information, outside of the sub-model is stored by this call.
public RollingResourceAppender(Layout layout,Resource res,Charset charset,boolean append,RetireListener listener) throws IOException { this(layout,res,charset,append,DEFAULT_MAX_FILE_SIZE,DEFAULT_MAX_BACKUP_INDEX,60,listener); }
Instantiate a RollingFileAppender and open the file designated by <code>filename</code>. The opened filename will become the ouput destination for this appender. <p>If the <code>append</code> parameter is true, the file will be appended to. Otherwise, the file desginated by <code>filename</code> will be truncated before being opened.
public int delete(DatabaseConnection databaseConnection,PreparedDelete<T> preparedDelete) throws SQLException { CompiledStatement stmt=preparedDelete.compile(databaseConnection,StatementType.DELETE); try { return stmt.runUpdate(); } finally { stmt.close(); } }
Delete rows that match the prepared statement.
protected boolean engineVerify(byte[] sigBytes) throws SignatureException { if (sigBytes == null) { throw new NullPointerException("sigBytes == null"); } return checkSignature(sigBytes,0,0); }
Verifies the signature bytes.
public boolean deleteFriendBytes(byte[] key){ SQLiteDatabase db=getWritableDatabase(); if (db == null) return false; if (key == null) { throw new IllegalArgumentException("Null friend deleted through addFriendBytes()"); } return deleteFriend(bytesToBase64(key)); }
Delete the given bytes as a friend.
public void write(String string,Color color){ setForeground(color); write(string); }
Set the foreground to prescribed color and write text to screen
public static void createImageToFileSystem(String url,Component targetList,int targetOffset,String targetKey,String destFile,Image placeholder,byte priority){ createImageToFileSystem(url,targetList,null,targetOffset,targetKey,destFile,null,priority,placeholder,defaultMaintainAspectRatio); }
Constructs an image request that will automatically populate the given list when the response arrives, it will cache the file locally as a file in the file storage. This assumes the GenericListCellRenderer style of list which relies on a map based model approach.
public TypeConstraintItemProvider(AdapterFactory adapterFactory){ super(adapterFactory); }
This constructs an instance from a factory and a notifier. <!-- begin-user-doc --> <!-- end-user-doc -->
public void handleKeepAliveSignal(long platformIdent){ AgentStatusData agentStatusData=agentStatusDataMap.get(platformIdent); if (null != agentStatusData) { agentStatusData.setLastKeepAliveTimestamp(System.currentTimeMillis()); if (agentStatusData.getAgentConnection() == AgentConnection.NO_KEEP_ALIVE) { agentStatusData.setAgentConnection(AgentConnection.CONNECTED); if (log.isInfoEnabled()) { log.info("Platform " + platformIdent + " sending keep-alive signals again."); } } } }
Registers the time when the last keep-alive was received for a given platform ident.
public FutureW<T> future(String key,Executor ex){ return pipes.oneOrErrorAsync(key,ex); }
Asynchronously extract a single data point from the named Queue.
public byte[] decrypt(byte[] cipherText){ int length=cipherText.length; if (length % 8 != 0) { System.out.println("Array must be a multiple of 8"); return null; } byte[] clearText=new byte[length]; int count=length / 8; for (int i=0; i < count; i++) encrypt(cipherText,i * 8,clearText,i * 8); return clearText; }
decrypts an array where the length must be a multiple of 8
public TurnVectors(int normalCount,int totalCount,int ssCount,int jsCount,int wsCount,int dsCount,int scCount,int aeroCount,int evenCount,int min){ this.numEven=evenCount; this.numNormal=normalCount; this.numTotal=totalCount; this.numSS=ssCount; this.numJS=jsCount; this.numWS=wsCount; this.numDS=dsCount; this.numSC=scCount; this.numAero=aeroCount; this.normal_turns=new Vector<ITurnOrdered>(normalCount); this.total_turns=new Vector<ITurnOrdered>(this.numTotal); this.even_turns=new Vector<ITurnOrdered>(evenCount); this.space_station_turns=new Vector<ITurnOrdered>(ssCount); this.jumpship_turns=new Vector<ITurnOrdered>(jsCount); this.warship_turns=new Vector<ITurnOrdered>(wsCount); this.dropship_turns=new Vector<ITurnOrdered>(dsCount); this.small_craft_turns=new Vector<ITurnOrdered>(scCount); this.aero_turns=new Vector<ITurnOrdered>(aeroCount); this.min=min; }
Construct empty <code>Vectors</code> with the given capacities.
private static long calcSize(long size,long skip,long limit){ return size >= 0 ? Math.max(-1,Math.min(size - skip,limit)) : -1; }
Calculates the sliced size given the current size, number of elements skip, and the number of elements to limit.
public void replaceTags(Map<String,String> newTags){ if (newTags == null) { throw new IllegalArgumentException("Replacing the current tags with a null map."); } tags.clear(); for ( Entry<String,String> tag : newTags.entrySet()) { putTag(tag.getKey(),tag.getValue()); } }
Replacing the current tags with the tags contained on the given map.
public void testNextDoubleBounded2(){ SplittableRandom sr=new SplittableRandom(); for (double least=0.0001; least < 1.0e20; least*=8) { for (double bound=least * 1.001; bound < 1.0e20; bound*=16) { double f=sr.nextDouble(least,bound); assertTrue(least <= f && f < bound); int i=0; double j; while (i < NCALLS && (j=sr.nextDouble(least,bound)) == f) { assertTrue(least <= j && j < bound); ++i; } assertTrue(i < NCALLS); } } }
nextDouble(least, bound) returns least <= value < bound; repeated calls produce at least two distinct results
public static Link createLink(Composite parent,String text,Font font,int hspan){ Link l=new Link(parent,SWT.UNDERLINE_LINK); l.setFont(font); l.setText(text); GridData gd=new GridData(GridData.BEGINNING,GridData.VERTICAL_ALIGN_CENTER,true,false,hspan,1); l.setLayoutData(gd); return l; }
Creates a new link widget
public Key min(){ if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; }
Returns a smallest key on this priority queue.
public List<ErrorLogger.ErrorObject> buildPackingList_2007(@Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText annotationText,@Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText issuer,@Nonnull org.smpte_ra.schemas.st0429_8_2007.PKL.UserText creator,@Nonnull List<PackingListBuilderAsset_2007> assets) throws IOException { IMFErrorLogger imfErrorLogger=new IMFErrorLoggerImpl(); org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType packingListType=IMFPKLObjectFieldsFactory.constructPackingListType_2007(); packingListType.setId(UUIDHelper.fromUUID(this.uuid)); packingListType.setAnnotationText(annotationText); packingListType.setIconId(this.iconId); packingListType.setIssueDate(this.issueDate); packingListType.setIssuer(issuer); packingListType.setCreator(creator); packingListType.setGroupId(this.groupId); org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.AssetList assetList=new org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.AssetList(); List<org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType> packingListAssets=assetList.getAsset(); for ( PackingListBuilderAsset_2007 asset : assets) { org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType packingListAssetType=new org.smpte_ra.schemas.st0429_8_2007.PKL.AssetType(); packingListAssetType.setId(asset.getUUID()); packingListAssetType.setAnnotationText(asset.getAnnotationText()); packingListAssetType.setHash(asset.getHash()); packingListAssetType.setSize(asset.getSize()); packingListAssetType.setType(asset.getAssetType().toString()); packingListAssetType.setOriginalFileName(asset.getOriginalFileName()); packingListAssets.add(packingListAssetType); } packingListType.setAssetList(assetList); packingListType.setSigner(null); packingListType.setSignature(null); File outputFile=new File(this.workingDirectory + File.separator + this.pklFileName); boolean formatted=true; ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader(); try (InputStream packingListSchemaAsAStream=contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0429_8_2007/PKL/packingList_schema.xsd");InputStream dsigSchemaAsAStream=contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd");OutputStream outputStream=new FileOutputStream(outputFile)){ try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource[] schemaSources=new StreamSource[2]; schemaSources[0]=new StreamSource(dsigSchemaAsAStream); schemaSources[1]=new StreamSource(packingListSchemaAsAStream); Schema schema=schemaFactory.newSchema(schemaSources); JAXBContext jaxbContext=JAXBContext.newInstance("org.smpte_ra.schemas.st0429_8_2007.PKL"); Marshaller marshaller=jaxbContext.createMarshaller(); ValidationEventHandlerImpl validationEventHandler=new ValidationEventHandlerImpl(true); marshaller.setEventHandler(validationEventHandler); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,formatted); marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/429-8/2007/PKL","PackingList"),org.smpte_ra.schemas.st0429_8_2007.PKL.PackingListType.class,packingListType),outputStream); outputStream.close(); if (validationEventHandler.hasErrors()) { for ( ValidationEventHandlerImpl.ValidationErrorObject validationErrorObject : validationEventHandler.getErrors()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_PKL_ERROR,validationErrorObject.getValidationEventSeverity(),validationErrorObject.getErrorMessage()); } } } catch ( SAXException|JAXBException e) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR,IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,e.getMessage()); } } return imfErrorLogger.getErrors(); }
A method to build a PackingList document compliant with the st0429-8:2007 schema
public static byte[] encodeFloat(Number number){ ByteBuffer fBuf=null; if (number instanceof Float) { fBuf=ByteBuffer.allocate(4); fBuf.putFloat(number.floatValue()); } else { fBuf=ByteBuffer.allocate(8); fBuf.putDouble(number.doubleValue()); } return fBuf.array(); }
Encodes a floating point value.
protected PDFDestination(PDFObject pageObj,int type){ this.pageObj=pageObj; this.type=type; }
Creates a new instance of PDFDestination
public static boolean matchPinyinUnits(final List<PinyinUnit> pinyinUnits,final String baseData,String search,StringBuffer chineseKeyWord){ if ((null == pinyinUnits) || (null == search) || (null == chineseKeyWord)) { return false; } StringBuffer matchSearch=new StringBuffer(); matchSearch.delete(0,matchSearch.length()); chineseKeyWord.delete(0,chineseKeyWord.length()); int pinyinUnitsLength=0; pinyinUnitsLength=pinyinUnits.size(); StringBuffer searchBuffer=new StringBuffer(); for (int i=0; i < pinyinUnitsLength; i++) { int j=0; chineseKeyWord.delete(0,chineseKeyWord.length()); searchBuffer.delete(0,searchBuffer.length()); searchBuffer.append(search); boolean found=findPinyinUnits(pinyinUnits,i,j,baseData,searchBuffer,chineseKeyWord); if (true == found) { return true; } } return false; }
Match Pinyin Units
public boolean isLoaded(){ return m_addressSpace.isLoaded(); }
Returns a flag that indicates whether the address space is loaded.
public void map(Text key,Writable value,OutputCollector<Text,ObjectWritable> output,Reporter reporter) throws IOException { ObjectWritable objWrite=new ObjectWritable(); objWrite.set(value); output.collect(key,objWrite); }
Convert values to ObjectWritable
static LegacyGWTHostPageSelectionTreeItem[] buildTree(Map<String,Set<String>> modulesHostPages){ List<LegacyGWTHostPageSelectionTreeItem> treeItems=new ArrayList<LegacyGWTHostPageSelectionTreeItem>(); for ( String moduleName : modulesHostPages.keySet()) { LegacyGWTHostPageSelectionTreeItem moduleItem=new LegacyGWTHostPageSelectionTreeItem(Path.fromPortableString(moduleName.replace('.','/'))); treeItems.add(moduleItem); for ( String hostPage : modulesHostPages.get(moduleName)) { new LegacyGWTHostPageSelectionTreeItem(Path.fromPortableString(hostPage),moduleItem); } } return treeItems.toArray(new LegacyGWTHostPageSelectionTreeItem[0]); }
Builds the tree nodes for a set of modules and host pages.
private void addTraceHeaders(RoutingContext ctx,ProxyContext pc){ for ( String th : pc.traceHeaders) { ctx.response().headers().add(XOkapiHeaders.TRACE,th); } }
Add the trace headers to the response
public void init(CredentialInfo info,APIAccessCallBack apiAccessCallBack,Context appContext){ IdentityProxy.clientID=info.getClientID(); IdentityProxy.clientSecret=info.getClientSecret(); this.apiAccessCallBack=apiAccessCallBack; context=appContext; SharedPreferences mainPref=context.getSharedPreferences(Constants.APPLICATION_PACKAGE,Context.MODE_PRIVATE); Editor editor=mainPref.edit(); editor.putString(Constants.CLIENT_ID,clientID); editor.putString(Constants.CLIENT_SECRET,clientSecret); editor.putString(Constants.TOKEN_ENDPOINT,info.getTokenEndPoint()); editor.commit(); setAccessTokenURL(info.getTokenEndPoint()); AccessTokenHandler accessTokenHandler=new AccessTokenHandler(info,this); accessTokenHandler.obtainAccessToken(); }
Initializing the IDP plugin and obrtaining the access token.
@Override public boolean acceptSource(final Object source){ return source instanceof GamaCSVFile; }
Method acceptSource()
public boolean isLastChunk(){ if ((this.lastChunk & 0X01) == 0X01) { return true; } return false; }
Answers whether this is the last chunk.
public double convertToAttribX(double scx){ double temp=m_XaxisEnd - m_XaxisStart; double temp2=((scx - m_XaxisStart) * (m_maxX - m_minX)) / temp; temp2=temp2 + m_minX; return temp2; }
convert a Panel x coordinate to a raw x value.
@Override @SuppressWarnings("unchecked") public List<StoragePool> matchStoragePoolsWithAttributeOn(List<StoragePool> pools,Map<String,Object> attributeMap,StringBuffer errorMessage){ List<StoragePool> matchedPools=new ArrayList<StoragePool>(); Set<String> systems=(Set<String>)attributeMap.get(Attributes.storage_system.toString()); Iterator<StoragePool> poolIterator=pools.iterator(); while (poolIterator.hasNext()) { StoragePool pool=poolIterator.next(); if (systems.contains(pool.getStorageDevice().toString())) { matchedPools.add(pool); } } _logger.info("{} pools are matching with systems after matching.",matchedPools.size()); if (CollectionUtils.isEmpty(matchedPools)) { errorMessage.append(String.format("No matching storage pool for the Storage systems : %s. ",systems)); _logger.error(errorMessage.toString()); } return matchedPools; }
Check if the CoS and pools are in the same varray and filter out the pools if they are not in the same varray.
public Boolean isShellAccess(){ return shellAccess; }
Gets the value of the shellAccess property.
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:18.130 -0500",hash_original_method="45431E38A045C0C983A2E1F24B9ACFC3",hash_generated_method="75FF6DCE1A5016BCF3AE6BCA9B4BE9D0") public LayerDrawable(Drawable[] layers){ this(layers,null); }
Create a new layer drawable with the list of specified layers.
public static String guessFormat(String name){ String ext=FileUtil.getFilenameExtension(name); for ( String format : FORMATS) { if (format.equals(ext)) { return ext; } } return null; }
Guess a supported format from the file name. For "auto" format handling.
@SuppressWarnings("TooBroadScope") private void flush(){ Collection<Entry> entries0; rwLock.writeLock().lock(); try { entries0=entries; entries=new ConcurrentLinkedDeque8<>(); } finally { rwLock.writeLock().unlock(); } cnt.set(0); if (!entries0.isEmpty()) { boolean addHdr=!file.exists(); FileOutputStream fos=null; OutputStreamWriter osw=null; BufferedWriter bw=null; try { fos=new FileOutputStream(file,true); osw=new OutputStreamWriter(fos); bw=new BufferedWriter(osw); if (addHdr) bw.write(HDR + U.nl()); for ( Entry entry : entries0) bw.write(entry + U.nl()); } catch ( IOException e) { U.error(null,"Failed to flush logged entries to a disk due to an IO exception.",e); } finally { U.closeQuiet(bw); U.closeQuiet(osw); U.closeQuiet(fos); } } }
Flush buffered entries to disk.
public void testExtractEncodingFromElidedLine(){ String encoding=ExtractXMLEncoding.extractEncoding(elidedLine); assertEquals("iso-8859-1",encoding); }
Some books have no newline after the xml element. My code failed to extract the encoding corectly. This test will help me fix my parsing code and make sure I don't make the mistake in future.
private void handleStartedStage(final State current) throws RpcException { switch (current.taskState.subStage) { case GET_HOST_INFO: this.getHostInfo(current); break; case TRIGGER_SCAN: this.triggerImageScan(current); break; case WAIT_FOR_SCAN_COMPLETION: this.waitForImageScanCompletion(current); break; case TRIGGER_DELETE: this.triggerImageDelete(current); break; case WAIT_FOR_DELETE_COMPLETION: this.waitForImageDeleteCompletion(current); break; default : this.failTask(new RuntimeException(String.format("Un-expected stage: %s",current.taskState.stage))); } }
Process patch requests when service is in STARTED stage.
public boolean isRelevant(final int minimumWords){ return this.dict.size() >= minimumWords; }
a property that is used during the construction of recommendation: if the dictionary is too small, then the non-existence of constructed words is not relevant for the construction of artificially constructed words If this property returns true, all other words must be in the dictionary
public static Date parseDateStrictly(final String str,final Locale locale,final String... parsePatterns) throws ParseException { return parseDateWithLeniency(str,null,parsePatterns,false); }
<p>Parses a string representing a date by trying a variety of different parsers, using the default date format symbols for the given locale..</p> <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p> The parser parses strictly - it does not allow for dates such as "February 942, 1996".
public static void main(String[] args){ junit.textui.TestRunner.run(suite()); }
for running the test from commandline
@Override public void reset(){ editorSite.getActionBars().getStatusLineManager().setErrorMessage(null); }
Sets clears the status line
public static double[][] makeDelayEmbeddingVector(double[][] data,int k,int startKthPoint,int numEmbeddingVectors) throws Exception { if (startKthPoint < k - 1) { throw new Exception("Start point t=" + startKthPoint + " is too early for a "+ k+ " length embedding vector"); } if (numEmbeddingVectors + startKthPoint > data.length) { throw new Exception("Too many embedding vectors " + numEmbeddingVectors + " requested for the given startPoint "+ startKthPoint+ " and time series length "+ data.length); } int columns=data[0].length; double[][] embeddingVectors=new double[numEmbeddingVectors][k * columns]; for (int t=startKthPoint; t < numEmbeddingVectors + startKthPoint; t++) { for (int i=0; i < k; i++) { for (int c=0; c < columns; c++) { embeddingVectors[t - startKthPoint][i * columns + c]=data[t - i][c]; } } } return embeddingVectors; }
Constructs numEmbeddingVectors embedding vectors of k time points for the data, including all multivariate values at each time point. Return only a subset, with the first embedding vector having it's last time point at t=startKthPoint
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener){ mRecycler.addOnItemTouchListener(listener); }
Add the onItemTouchListener for the recycler
protected void rethrow(SQLException cause,String sql,Object[] params) throws SQLException { StringBuilder msg=new StringBuilder(cause.getMessage()); msg.append(" Query: "); msg.append(sql); msg.append(" Parameters: "); if (params == null) { msg.append("[]"); } else { msg.append(Arrays.asList(params)); } SQLException e=new SQLException(msg.toString(),cause.getSQLState(),cause.getErrorCode()); e.setNextException(cause); throw e; }
Throws a new exception with a more informative error message.
public final void yyclose() throws java.io.IOException { zzAtEOF=true; zzEndRead=zzStartRead; if (zzReader != null) zzReader.close(); }
Closes the input stream.
public AlgorithmTerminationException(Algorithm algorithm,String message){ super(algorithm,message); }
Constructs an algorithm termination exception originating from the specified algorithm with the given message.
public static Token newSymbol(String type,int startLine,int startColumn){ return new Token(Types.lookupSymbol(type),type,startLine,startColumn); }
Creates a token that represents a symbol, using a library for the type.
public static Optional<Excerpt> freshBuilder(Block block,Metadata metadata){ if (!metadata.getBuilderFactory().isPresent()) { return Optional.absent(); } Excerpt defaults=block.declare("_defaults","%s _defaults = %s;",metadata.getGeneratedBuilder(),metadata.getBuilderFactory().get().newBuilder(metadata.getBuilder(),TypeInference.INFERRED_TYPES)); return Optional.of(defaults); }
Declares a fresh Builder to copy default property values from.
protected boolean executeInternal(String sql,int fetchSize) throws SQLException { executing=true; QueryException exception=null; lock.lock(); try { executeQueryProlog(); batchResultSet=null; ExecutionResult internalExecutionResult; if (options.allowMultiQueries || options.rewriteBatchedStatements) { internalExecutionResult=new MultiVariableIntExecutionResult(this,1,fetchSize,true); } else { internalExecutionResult=new SingleExecutionResult(this,fetchSize,true,false,true); } protocol.executeQuery(protocol.isMasterConnection(),internalExecutionResult,Utils.nativeSql(sql,connection.noBackslashEscapes),resultSetScrollType); executionResult=internalExecutionResult; return executionResult.getResultSet() != null; } catch ( QueryException e) { exception=e; return false; } finally { lock.unlock(); executeQueryEpilog(exception); executing=false; } }
executes a query.
void fullyUnlock(){ takeLock.unlock(); putLock.unlock(); }
Unlocks to allow both puts and takes.
public static void send(InternalDistributedMember recipient,int processorId,ReplySender dm,boolean result,VersionedObjectList versions,ReplyException ex){ Assert.assertTrue(recipient != null,"RemoveAllReplyMessage NULL reply message"); RemoveAllReplyMessage m=new RemoveAllReplyMessage(processorId,result,versions,ex); m.setRecipient(recipient); dm.putOutgoing(m); }
Send an ack
@Override public synchronized V put(K key,V value){ mbean.puts.incrementAndGet(); CacheEntry<V> entry=newSoftCacheEntry(key,value); CacheEntry<V> oldEntry=cacheEntries.put(key,entry); return safeValue(oldEntry); }
Adds an object to the cache.
public static LatLon locationFromUTMCoord(int zone,String hemisphere,double easting,double northing,Globe globe){ UTMCoord coord=UTMCoord.fromUTM(zone,hemisphere,easting,northing,globe); return new LatLon(coord.getLatitude(),coord.getLongitude()); }
Convenience method for converting a UTM coordinate to a geographic location.
private void verify(final Task<Diff> task,final Diff decodedDiff,final Diff originalDiff) throws SQLConsumerException { String orig=originalDiff.toString(); String deco=decodedDiff.toString(); boolean notEqual=!orig.equals(deco); if (notEqual && MODE_SURROGATES == SurrogateModes.REPLACE) { char[] origDiff=orig.toCharArray(); if (Surrogates.scan(origDiff)) { String repDiff=new String(Surrogates.replace(origDiff)); notEqual=!repDiff.equals(deco); } } if (notEqual) { if (MODE_DEBUG_OUTPUT_ACTIVATED) { try { WikipediaXMLWriter writer=new WikipediaXMLWriter(LOGGING_PATH_DIFFTOOL + LOGGING_PATH_DEBUG + task.getHeader().getArticleName()+ ".dbg"); switch (task.getTaskType()) { case TASK_FULL: case TASK_PARTIAL_FIRST: writer.writeDiff(task); break; case TASK_PARTIAL: case TASK_PARTIAL_LAST: { int revCount=originalDiff.getRevisionCounter(); Diff d; boolean fullRev=false; for (int diffCount=0; !fullRev && diffCount < originalDiff.size(); diffCount++) { d=task.get(diffCount); if (d.getRevisionCounter() <= revCount && d.isFullRevision()) { fullRev=true; writer.writeDiff(task,diffCount); } } if (!fullRev) { writer.writeDiffFile(task); } } break; default : throw new IOException("Unknown TaskType"); } writer.close(); } catch (IOException e) { ConsumerLogMessages.logException(logger,e); } } throw ErrorFactory.createSQLConsumerException(ErrorKeys.DIFFTOOL_SQLCONSUMER_ENCODING_VERIFICATION_FAILED,"Redecoding of " + task.getHeader().getArticleName() + " failed at revision "+ originalDiff.getRevisionCounter()+ "."); } }
Verifies that the decoded diff is identical to the original diff.
private RUtils(){ throw new Error("Do not need instantiate!"); }
Don't let anyone instantiate this class.
public ExamineSslAction(KseFrame kseFrame){ super(kseFrame); putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(res.getString("ExamineSslAction.accelerator").charAt(0),Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.ALT_MASK)); putValue(LONG_DESCRIPTION,res.getString("ExamineSslAction.statusbar")); putValue(NAME,res.getString("ExamineSslAction.text")); putValue(SHORT_DESCRIPTION,res.getString("ExamineSslAction.tooltip")); putValue(SMALL_ICON,new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource(res.getString("ExamineSslAction.image"))))); }
Construct action.
public static String toNullIfEmptyOrWhitespace(String s){ return (StringUtil.isEmptyOrWhitespace(s)) ? null : s; }
Helper function for turning empty or whitespace strings into a null.
public static void play(double sample){ if (Double.isNaN(sample)) throw new IllegalArgumentException("sample is NaN"); if (sample < -1.0) sample=-1.0; if (sample > +1.0) sample=+1.0; short s=(short)(MAX_16_BIT * sample); buffer[bufferSize++]=(byte)s; buffer[bufferSize++]=(byte)(s >> 8); if (bufferSize >= buffer.length) { line.write(buffer,0,buffer.length); bufferSize=0; } }
Writes one sample (between -1.0 and +1.0) to standard audio. If the sample is outside the range, it will be clipped.
public void execute(TransformerImpl transformer) throws TransformerException { }
This is the normal call when xsl:fallback is instantiated. In accordance with the XSLT 1.0 Recommendation, chapter 15, "Normally, instantiating an xsl:fallback element does nothing."
public EaseOut(float overshoot){ this.overshoot=overshoot; }
Easing equation function for a back (overshooting cubic easing: (overshoot+1)*t^3 - overshoot*t^2) easing out: decelerating from zero velocity.
public Swagger2MarkupConfigBuilder withFlatBody(){ config.flatBodyEnabled=true; return this; }
Optionally isolate the body parameter, if any, from other parameters.
public static <T>T newInstance(Class<T> cl,Object contextProvider){ Check.assumeNotNull(contextProvider,"contextProvider not null"); final Properties ctx=getCtx(contextProvider); final String trxName=getTrxName(contextProvider); return create(ctx,cl,trxName); }
Creates a new instance of given object using same context and trxName as <code>contextProvider</code>
public static void printResults(PowerDatacenter datacenter,List<Vm> vms,double lastClock,String experimentName,boolean outputInCsv,String outputFolder){ Log.enable(); List<Host> hosts=datacenter.getHostList(); int numberOfHosts=hosts.size(); int numberOfVms=vms.size(); double totalSimulationTime=lastClock; double energy=datacenter.getPower() / (3600 * 1000); int numberOfMigrations=datacenter.getMigrationCount(); Map<String,Double> slaMetrics=getSlaMetrics(vms); double slaOverall=slaMetrics.get("overall"); double slaAverage=slaMetrics.get("average"); double slaDegradationDueToMigration=slaMetrics.get("underallocated_migration"); double slaTimePerActiveHost=getSlaTimePerActiveHost(hosts); double sla=slaTimePerActiveHost * slaDegradationDueToMigration; List<Double> timeBeforeHostShutdown=getTimesBeforeHostShutdown(hosts); int numberOfHostShutdowns=timeBeforeHostShutdown.size(); double meanTimeBeforeHostShutdown=Double.NaN; double stDevTimeBeforeHostShutdown=Double.NaN; if (!timeBeforeHostShutdown.isEmpty()) { meanTimeBeforeHostShutdown=MathUtil.mean(timeBeforeHostShutdown); stDevTimeBeforeHostShutdown=MathUtil.stDev(timeBeforeHostShutdown); } List<Double> timeBeforeVmMigration=getTimesBeforeVmMigration(vms); double meanTimeBeforeVmMigration=Double.NaN; double stDevTimeBeforeVmMigration=Double.NaN; if (!timeBeforeVmMigration.isEmpty()) { meanTimeBeforeVmMigration=MathUtil.mean(timeBeforeVmMigration); stDevTimeBeforeVmMigration=MathUtil.stDev(timeBeforeVmMigration); } if (outputInCsv) { File folder=new File(outputFolder); if (!folder.exists()) { folder.mkdir(); } File folder1=new File(outputFolder + "/stats"); if (!folder1.exists()) { folder1.mkdir(); } File folder2=new File(outputFolder + "/time_before_host_shutdown"); if (!folder2.exists()) { folder2.mkdir(); } File folder3=new File(outputFolder + "/time_before_vm_migration"); if (!folder3.exists()) { folder3.mkdir(); } File folder4=new File(outputFolder + "/metrics"); if (!folder4.exists()) { folder4.mkdir(); } StringBuilder data=new StringBuilder(); String delimeter=","; data.append(experimentName + delimeter); data.append(parseExperimentName(experimentName)); data.append(String.format("%d",numberOfHosts) + delimeter); data.append(String.format("%d",numberOfVms) + delimeter); data.append(String.format("%.2f",totalSimulationTime) + delimeter); data.append(String.format("%.5f",energy) + delimeter); data.append(String.format("%d",numberOfMigrations) + delimeter); data.append(String.format("%.10f",sla) + delimeter); data.append(String.format("%.10f",slaTimePerActiveHost) + delimeter); data.append(String.format("%.10f",slaDegradationDueToMigration) + delimeter); data.append(String.format("%.10f",slaOverall) + delimeter); data.append(String.format("%.10f",slaAverage) + delimeter); data.append(String.format("%d",numberOfHostShutdowns) + delimeter); data.append(String.format("%.2f",meanTimeBeforeHostShutdown) + delimeter); data.append(String.format("%.2f",stDevTimeBeforeHostShutdown) + delimeter); data.append(String.format("%.2f",meanTimeBeforeVmMigration) + delimeter); data.append(String.format("%.2f",stDevTimeBeforeVmMigration) + delimeter); if (datacenter.getVmAllocationPolicy() instanceof PowerVmAllocationPolicyMigrationAbstract) { PowerVmAllocationPolicyMigrationAbstract vmAllocationPolicy=(PowerVmAllocationPolicyMigrationAbstract)datacenter.getVmAllocationPolicy(); double executionTimeVmSelectionMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryVmSelection()); double executionTimeVmSelectionStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryVmSelection()); double executionTimeHostSelectionMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryHostSelection()); double executionTimeHostSelectionStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryHostSelection()); double executionTimeVmReallocationMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryVmReallocation()); double executionTimeVmReallocationStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryVmReallocation()); double executionTimeTotalMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryTotal()); double executionTimeTotalStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryTotal()); data.append(String.format("%.5f",executionTimeVmSelectionMean) + delimeter); data.append(String.format("%.5f",executionTimeVmSelectionStDev) + delimeter); data.append(String.format("%.5f",executionTimeHostSelectionMean) + delimeter); data.append(String.format("%.5f",executionTimeHostSelectionStDev) + delimeter); data.append(String.format("%.5f",executionTimeVmReallocationMean) + delimeter); data.append(String.format("%.5f",executionTimeVmReallocationStDev) + delimeter); data.append(String.format("%.5f",executionTimeTotalMean) + delimeter); data.append(String.format("%.5f",executionTimeTotalStDev) + delimeter); writeMetricHistory(hosts,vmAllocationPolicy,outputFolder + "/metrics/" + experimentName+ "_metric"); } data.append("\n"); writeDataRow(data.toString(),outputFolder + "/stats/" + experimentName+ "_stats.csv"); writeDataColumn(timeBeforeHostShutdown,outputFolder + "/time_before_host_shutdown/" + experimentName+ "_time_before_host_shutdown.csv"); writeDataColumn(timeBeforeVmMigration,outputFolder + "/time_before_vm_migration/" + experimentName+ "_time_before_vm_migration.csv"); } else { Log.setDisabled(false); Log.printLine(); Log.printLine(String.format("Experiment name: " + experimentName)); Log.printLine(String.format("Number of hosts: " + numberOfHosts)); Log.printLine(String.format("Number of VMs: " + numberOfVms)); Log.printLine(String.format("Total simulation time: %.2f sec",totalSimulationTime)); Log.printLine(String.format("Energy consumption: %.2f kWh",energy)); Log.printLine(String.format("Number of VM migrations: %d",numberOfMigrations)); Log.printLine(String.format("SLA: %.5f%%",sla * 100)); Log.printLine(String.format("SLA perf degradation due to migration: %.2f%%",slaDegradationDueToMigration * 100)); Log.printLine(String.format("SLA time per active host: %.2f%%",slaTimePerActiveHost * 100)); Log.printLine(String.format("Overall SLA violation: %.2f%%",slaOverall * 100)); Log.printLine(String.format("Average SLA violation: %.2f%%",slaAverage * 100)); Log.printLine(String.format("Number of host shutdowns: %d",numberOfHostShutdowns)); Log.printLine(String.format("Mean time before a host shutdown: %.2f sec",meanTimeBeforeHostShutdown)); Log.printLine(String.format("StDev time before a host shutdown: %.2f sec",stDevTimeBeforeHostShutdown)); Log.printLine(String.format("Mean time before a VM migration: %.2f sec",meanTimeBeforeVmMigration)); Log.printLine(String.format("StDev time before a VM migration: %.2f sec",stDevTimeBeforeVmMigration)); if (datacenter.getVmAllocationPolicy() instanceof PowerVmAllocationPolicyMigrationAbstract) { PowerVmAllocationPolicyMigrationAbstract vmAllocationPolicy=(PowerVmAllocationPolicyMigrationAbstract)datacenter.getVmAllocationPolicy(); double executionTimeVmSelectionMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryVmSelection()); double executionTimeVmSelectionStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryVmSelection()); double executionTimeHostSelectionMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryHostSelection()); double executionTimeHostSelectionStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryHostSelection()); double executionTimeVmReallocationMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryVmReallocation()); double executionTimeVmReallocationStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryVmReallocation()); double executionTimeTotalMean=MathUtil.mean(vmAllocationPolicy.getExecutionTimeHistoryTotal()); double executionTimeTotalStDev=MathUtil.stDev(vmAllocationPolicy.getExecutionTimeHistoryTotal()); Log.printLine(String.format("Execution time - VM selection mean: %.5f sec",executionTimeVmSelectionMean)); Log.printLine(String.format("Execution time - VM selection stDev: %.5f sec",executionTimeVmSelectionStDev)); Log.printLine(String.format("Execution time - host selection mean: %.5f sec",executionTimeHostSelectionMean)); Log.printLine(String.format("Execution time - host selection stDev: %.5f sec",executionTimeHostSelectionStDev)); Log.printLine(String.format("Execution time - VM reallocation mean: %.5f sec",executionTimeVmReallocationMean)); Log.printLine(String.format("Execution time - VM reallocation stDev: %.5f sec",executionTimeVmReallocationStDev)); Log.printLine(String.format("Execution time - total mean: %.5f sec",executionTimeTotalMean)); Log.printLine(String.format("Execution time - total stDev: %.5f sec",executionTimeTotalStDev)); } Log.printLine(); } Log.setDisabled(true); }
Prints the results.
public Instance calcPivot(MyIdxList list1,MyIdxList list2,Instances insts){ int classIdx=m_Instances.classIndex(); double[] attrVals=new double[insts.numAttributes()]; Instance temp; for (int i=0; i < list1.length(); i++) { temp=insts.instance(list1.get(i).idx); for (int k=0; k < temp.numValues(); k++) { if (temp.index(k) == classIdx) { continue; } attrVals[k]+=temp.valueSparse(k); } } for (int j=0; j < list2.length(); j++) { temp=insts.instance(list2.get(j).idx); for (int k=0; k < temp.numValues(); k++) { if (temp.index(k) == classIdx) { continue; } attrVals[k]+=temp.valueSparse(k); } } for (int j=0, numInsts=list1.length() + list2.length(); j < attrVals.length; j++) { attrVals[j]/=numInsts; } temp=new DenseInstance(1.0,attrVals); return temp; }
Calculates the centroid pivot of a node based on the list of points that it contains (tbe two lists of its children are provided).
private static void usage(){ int consoleWidth=ConsoleUtil.getConsoleWidth(); if (consoleWidth <= 0) { consoleWidth=80; } System.out.println("java -cp baksmali.jar org.jf.dexlib2.analysis.DumpFields -d path/to/framework/jar/files <dex-file>"); }
Prints the usage message.
public static byte[] decode(char[] in,int iOff,int iLen){ if (iLen % 4 != 0) throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iOff + iLen - 1] == '=') iLen--; int oLen=(iLen * 3) / 4; byte[] out=new byte[oLen]; int ip=iOff; int iEnd=iOff + iLen; int op=0; while (ip < iEnd) { int i0=in[ip++]; int i1=in[ip++]; int i2=ip < iEnd ? in[ip++] : 'A'; int i3=ip < iEnd ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int b0=map2[i0]; int b1=map2[i1]; int b2=map2[i2]; int b3=map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int o0=(b0 << 2) | (b1 >>> 4); int o1=((b1 & 0xf) << 4) | (b2 >>> 2); int o2=((b2 & 3) << 6) | b3; out[op++]=(byte)o0; if (op < oLen) out[op++]=(byte)o1; if (op < oLen) out[op++]=(byte)o2; } return out; }
Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data.
public Stream<? extends SymbolInformation> search(String query){ Stream<SymbolInformation> classes=allSymbols(ElementKind.CLASS); Stream<SymbolInformation> methods=allSymbols(ElementKind.METHOD); return Stream.concat(classes,methods).filter(null); }
Search all indexed symbols
public void cancel(){ cancel=true; }
Calling this method cancels the event
public static ButtonDialog createNewDialog(String uri){ ButtonDialogBuilder builder=new ButtonDialogBuilder("browser_unavailable"); JPanel mainPanel=new JPanel(new GridBagLayout()); GridBagConstraints gbc=new GridBagConstraints(); gbc.insets=new Insets(5,5,5,5); gbc.gridy=0; gbc.gridx=0; JTextField urlTextField=makeTextField(uri); gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; mainPanel.add(urlTextField,gbc); gbc.insets=new Insets(5,0,5,5); JButton copyButton=makeCopyButton(uri); gbc.gridx+=1; gbc.weightx=0.0; gbc.fill=GridBagConstraints.NONE; gbc.ipady=-1; mainPanel.add(copyButton,gbc); ButtonDialog dialog=builder.setContent(mainPanel,ButtonDialog.MESSAGE).setButtons(DefaultButtons.CLOSE_BUTTON).setOwner(KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow()).build(); return dialog; }
Creates a new BrowserUnavailable ButtonDialog
@RequestProcessing(value="/verifycode/remove-expired",method=HTTPRequestMethod.GET) public void removeExpriedVerifycodes(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception { final String key=Symphonys.get("keyOfSymphony"); if (!key.equals(request.getParameter("key"))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } verifycodeMgmtService.removeExpiredVerifycodes(); context.renderJSON().renderTrueResult(); }
Remove expired verifycodes.
private void updateAndRender(float targetProgress){ if (this.fadeTimeMs > 0) { if (targetProgress > 0f && this.progress == 0f) this.fadeIn(); else if (targetProgress < 1f && this.progress == 1f) this.fadeIn(); else if (targetProgress == 0f && this.progress > 0f) this.fadeOut(); else if (targetProgress == 1f && this.progress < 1f) this.fadeOut(); } this.progress=targetProgress; if (Looper.myLooper() == Looper.getMainLooper()) { this.invalidate(); } else { this.postInvalidate(); } }
Set the progress value and render it
public IllegalArgumentException(String message){ super(message); }
Constructs a new exception with the specified detail message. The cause is not initialized.
public String encodeBody(){ return encodeBody(new StringBuffer()).toString(); }
Return canonical header content. (encoded header except headerName:)
public void removeIndex(IIndex index){ if (index != null) { indices.remove(index); } }
Removes the given index.
public void remove(){ purge(cursor); }
Removes the match from the cursor position. This also ensures that the node is removed from the active set so that it is not longer considered a relevant output node.
public double computeSecondCover(boolean leaf){ double max=0.; for ( DistanceEntry<E> e : secondAssignments) { double cover=leaf ? e.getDistance() : (e.getEntry().getCoveringRadius() + e.getDistance()); max=cover > max ? cover : max; } return max; }
Compute the covering radius of the second assignment.
public Random(){ this(System.currentTimeMillis()); }
Creates a new random number generator. Its seed is initialized to a value based on the current time: public Random() { this(System.currentTimeMillis()); } See Also:System.currentTimeMillis()
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; double zConvFactor=1; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader=args[0]; outputHeader=args[1]; zConvFactor=Double.parseDouble(args[2]); if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { int row, col; double z; double[] N=new double[8]; double fx, fy; float slope; float progress=0; int[] Dy={-1,0,1,1,1,0,-1,-1}; int[] Dx={1,1,1,0,-1,-1,-1,0}; final double radToDeg=180 / Math.PI; WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r"); inputFile.isReflectedAtEdges=true; int rows=inputFile.getNumberRows(); int cols=inputFile.getNumberColumns(); double gridRes=inputFile.getCellSizeX(); double eightGridRes=8 * gridRes; double noData=inputFile.getNoDataValue(); if (inputFile.getXYUnits().toLowerCase().contains("deg") || inputFile.getProjection().toLowerCase().contains("geog")) { double midLat=(inputFile.getNorth() - inputFile.getSouth()) / 2.0; if (midLat <= 90 && midLat >= -90) { zConvFactor=1.0 / (113200 * Math.cos(Math.toRadians(midLat))); } } WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); outputFile.setPreferredPalette("spectrum.pal"); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=inputFile.getValue(row,col); if (z != noData) { for (int i=0; i < 8; i++) { N[i]=inputFile.getValue(row + Dy[i],col + Dx[i]); if (N[i] != noData) { N[i]=N[i] * zConvFactor; } else { N[i]=z * zConvFactor; } } fy=(N[6] - N[4] + 2 * (N[7] - N[3]) + N[0] - N[2]) / eightGridRes; fx=(N[2] - N[4] + 2 * (N[1] - N[5]) + N[0] - N[6]) / eightGridRes; slope=(float)(Math.atan(Math.sqrt(fx * fx + fy * fy)) * radToDeg); outputFile.setValue(row,col,slope); } else { outputFile.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputFile.addMetadataEntry("Created on " + new Date()); inputFile.close(); outputFile.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public void draw(Canvas c,Rect bounds){ final RectF arcBounds=mTempBounds; arcBounds.set(bounds); arcBounds.inset(mStrokeInset,mStrokeInset); final float startAngle=(mStartTrim + mRotation) * 360; final float endAngle=(mEndTrim + mRotation) * 360; float sweepAngle=endAngle - startAngle; mPaint.setColor(mColors[mColorIndex]); c.drawArc(arcBounds,startAngle,sweepAngle,false,mPaint); drawTriangle(c,startAngle,sweepAngle,bounds); if (mAlpha < 255) { mCirclePaint.setColor(mBackgroundColor); mCirclePaint.setAlpha(255 - mAlpha); c.drawCircle(bounds.exactCenterX(),bounds.exactCenterY(),bounds.width() / 2,mCirclePaint); } }
Draw the progress spinner
public boolean declaresMethod(String subsignature){ checkLevel(SIGNATURES); return declaresMethod(Scene.v().getSubSigNumberer().findOrAdd(subsignature)); }
Does this class declare a method with the given subsignature?
public static void scrollToVisible(JTable table,int row,int col){ if (!(table.getParent() instanceof JViewport)) return; JViewport viewport=(JViewport)table.getParent(); Rectangle rect=table.getCellRect(row,col,true); Point pt=viewport.getViewPosition(); rect.setLocation(rect.x - pt.x,rect.y - pt.y); viewport.scrollRectToVisible(rect); }
Assumes table is contained in a JScrollPane. Scrolls the cell (rowIndex, vColIndex) so that it is visible within the viewport.
public boolean isCrossFadeEnabled(){ return mCrossFade; }
Indicates whether the cross fade is enabled for this transition.
public static AnnotatedClass construct(Class<?> cls,AnnotationIntrospector aintr,MixInResolver mir){ List<Class<?>> st=ClassUtil.findSuperTypes(cls,null); AnnotatedClass ac=new AnnotatedClass(cls,st,aintr,mir,null); ac.resolveClassAnnotations(); return ac; }
Factory method that instantiates an instance. Returned instance will only be initialized with class annotations, but not with any method information.
private String validateSnmpDirectory(String snmpDir){ return snmpDir; }
SnmpDirectory must be specified if SNMP is enabled. This directory must also exist.
public void swap(String n0,String n1){ if (n0 == null || n1 == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"Can not swap unnamed cores."); } solrCores.swap(n0,n1); coresLocator.swap(this,solrCores.getCoreDescriptor(n0),solrCores.getCoreDescriptor(n1)); log.info("swapped: " + n0 + " with "+ n1); }
Swaps two SolrCore descriptors.
public char next(){ if (_length <= ++_pos) { _pos=_length; return DONE; } else return _string.charAt(_pos); }
reads a character from the cursor
public void searchStopped(){ }
Called when the user presses the cancel search button or presses escape while the search is in focus.
public static double tau_b(ExampleSet eSet,Attribute a,Attribute b,double fuzz) throws OperatorException { ExampleSet e=extract(eSet,a,b); FuzzyComp fc=new FuzzyComp(fuzz); int c=0; int d=0; int ta=0; int tb=0; int n=0; Iterator<Example> i=e.iterator(); while (i.hasNext()) { Example z1=i.next(); n++; double x=z1.getValue(a); double y=z1.getValue(b); if (b.isNominal() && a != null) { String yString=b.getMapping().mapIndex((int)y); y=a.getMapping().getIndex(yString); } Iterator<Example> j=e.iterator(); for (int k=0; k < n; k++) { j.next(); } while (j.hasNext()) { Example z2=j.next(); double xx=z2.getValue(a); double yy=z2.getValue(b); if (b.isNominal() && a != null) { String yyString=b.getMapping().mapIndex((int)yy); yy=a.getMapping().getIndex(yyString); } int xc=fc.compare(x,xx); int yc=fc.compare(y,yy); if (xc == 0) { if (yc == 0) { } else { ta++; } } else if (yc == 0) { tb++; } else if (xc == yc) { c++; } else { d++; } } } double num=c - d; double den=Math.sqrt((c + d + ta) * (c + d + tb)); if (den != 0) { return num / den; } else { return 0; } }
Computes Kendall's tau-b rank correlation statistic, ignoring examples containing missing values, with approximate comparisons.
public final void renameAttributeValue(Attribute att,String val,String name){ int v=att.indexOfValue(val); if (v == -1) throw new IllegalArgumentException(val + " not found"); renameAttributeValue(att.index(),v,name); }
Renames the value of a nominal (or string) attribute value. This change only affects this dataset.
public ElemTemplateElement appendChild(ElemTemplateElement newChild){ int type=((ElemTemplateElement)newChild).getXSLToken(); switch (type) { case Constants.ELEMNAME_TEXTLITERALRESULT: case Constants.ELEMNAME_APPLY_TEMPLATES: case Constants.ELEMNAME_APPLY_IMPORTS: case Constants.ELEMNAME_CALLTEMPLATE: case Constants.ELEMNAME_FOREACH: case Constants.ELEMNAME_VALUEOF: case Constants.ELEMNAME_COPY_OF: case Constants.ELEMNAME_NUMBER: case Constants.ELEMNAME_CHOOSE: case Constants.ELEMNAME_IF: case Constants.ELEMNAME_TEXT: case Constants.ELEMNAME_COPY: case Constants.ELEMNAME_VARIABLE: case Constants.ELEMNAME_MESSAGE: break; default : error(XSLTErrorResources.ER_CANNOT_ADD,new Object[]{newChild.getNodeName(),this.getNodeName()}); } return super.appendChild(newChild); }
Add a child to the child list. <!ELEMENT xsl:attribute %char-template;> <!ATTLIST xsl:attribute name %avt; #REQUIRED namespace %avt; #IMPLIED %space-att; >
public void sendCanMessage(CanMessage m,CanListener reply){ log.debug("TrafficController sendCanMessage() " + m.toString()); sendMessage(m,reply); }
Forward a preformatted message to the actual interface.
public ParsedURLData parseURL(ParsedURL baseURL,String urlStr){ if (urlStr.length() == 0) return baseURL.data; int idx=0, len=urlStr.length(); if (len == 0) return baseURL.data; char ch=urlStr.charAt(idx); while ((ch == '-') || (ch == '+') || (ch == '.')|| ((ch >= 'a') && (ch <= 'z'))|| ((ch >= 'A') && (ch <= 'Z'))) { idx++; if (idx == len) { ch=0; break; } ch=urlStr.charAt(idx); } String protocol=null; if (ch == ':') { protocol=urlStr.substring(0,idx).toLowerCase(); } if (protocol != null) { if (!protocol.equals(baseURL.getProtocol())) return parseURL(urlStr); idx++; if (idx == urlStr.length()) return parseURL(urlStr); if (urlStr.charAt(idx) == '/') return parseURL(urlStr); urlStr=urlStr.substring(idx); } if (urlStr.startsWith("/")) { if ((urlStr.length() > 1) && (urlStr.charAt(1) == '/')) { return parseURL(baseURL.getProtocol() + ":" + urlStr); } return parseURL(baseURL.getPortStr() + urlStr); } if (urlStr.startsWith("#")) { String base=baseURL.getPortStr(); if (baseURL.getPath() != null) base+=baseURL.getPath(); return parseURL(base + urlStr); } String path=baseURL.getPath(); if (path == null) path=""; idx=path.lastIndexOf('/'); if (idx == -1) path=""; else path=path.substring(0,idx + 1); return parseURL(baseURL.getPortStr() + path + urlStr); }
Parses the string as a sub URL of baseURL, and returns the results of parsing in the ParsedURLData object.