code
stringlengths
10
174k
nl
stringlengths
3
129k
private static Map<AnchorURL,String> allReflinks(final Collection<?> links){ final Map<AnchorURL,String> v=new HashMap<AnchorURL,String>(); final Iterator<?> i=links.iterator(); Object o; AnchorURL url=null; String u; int pos; loop: while (i.hasNext()) try { url=null; o=i.next(); if (o instanceof AnchorURL) url=(AnchorURL)o; else if (o instanceof String) url=new AnchorURL((String)o); else if (o instanceof ImageEntry) url=new AnchorURL(((ImageEntry)o).url()); else if (o instanceof IconEntry) url=new AnchorURL(((IconEntry)o).getUrl()); else { assert false; continue loop; } u=url.toNormalform(true); if ((pos=u.toLowerCase().indexOf("http://",7)) > 0) { i.remove(); u=u.substring(pos); while ((pos=u.toLowerCase().indexOf("http://",7)) > 0) u=u.substring(pos); url=new AnchorURL(u); if (!(v.containsKey(url))) v.put(url,"ref"); continue loop; } if ((pos=u.toLowerCase().indexOf("https://",7)) > 0) { i.remove(); u=u.substring(pos); while ((pos=u.toLowerCase().indexOf("https://",7)) > 0) u=u.substring(pos); url=new AnchorURL(u); if (!(v.containsKey(url))) v.put(url,"ref"); continue loop; } if ((pos=u.toLowerCase().indexOf("/www.",11)) > 0) { i.remove(); u=url.getProtocol() + ":/" + u.substring(pos); while ((pos=u.toLowerCase().indexOf("/www.",11)) > 0) u=url.getProtocol() + ":/" + u.substring(pos); AnchorURL addurl=new AnchorURL(u); if (!(v.containsKey(addurl))) v.put(addurl,"ref"); continue loop; } } catch ( final MalformedURLException e) { } return v; }
We find all links that are part of a reference inside a url
public Task<Boolean> contains(final CacheKey key){ if (containsSync(key)) { return Task.forResult(true); } return containsAsync(key); }
Performs a key-value look up in the disk cache. If no value is found in the staging area, then disk cache checks are scheduled on a background thread. Any error manifests itself as a cache miss, i.e. the returned Task resolves to false.
public void dec(){ dec(1); }
Convenience method to decrement atomic numeric types.
@Override public String toString(){ try { return getSummary(); } catch ( SchedulerException se) { return "SchedulerMetaData: undeterminable."; } }
<p> Return a simple string representation of this object. </p>
private boolean cleanSomeSlots(int i,int n){ boolean removed=false; Entry[] tab=table; int len=tab.length; do { i=nextIndex(i,len); Entry e=tab[i]; if (e != null && e.get() == null) { n=len; removed=true; i=expungeStaleEntry(i); } } while ((n>>>=1) != 0); return removed; }
Heuristically scan some cells looking for stale entries. This is invoked when either a new element is added, or another stale one has been expunged. It performs a logarithmic number of scans, as a balance between no scanning (fast but retains garbage) and a number of scans proportional to number of elements, that would find all garbage but would cause some insertions to take O(n) time.
public void testSimple() throws IOException { fetch("www.fortify.net",443,true,"/sslcheck.html",1,1,0,60); fetch("mail.google.com",443,true,"/mail/",1,1,0,60); fetch("www.paypal.com",443,true,"/",1,1,0,60); fetch("www.yellownet.ch",443,true,"/",1,1,0,60); }
Does a single request for each of the hosts. Consumes the response.
public FloatConverter(final Object defaultValue){ super(true,defaultValue); }
Construct a <b>java.lang.Float</b> <i>Converter</i> that returns a default value if an error occurs.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case UmplePackage.MULTIPLE_IS_A__EXTENDS_NAME_1: return getExtendsName_1(); case UmplePackage.MULTIPLE_IS_A__ANONYMOUS_MULTIPLE_IS_A11: return getAnonymous_multipleIsA_1_1(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
CloseableIteration<? extends Statement,SailException> createStatementIterator(Resource subj,IRI pred,Value obj,boolean explicit,Resource... contexts) throws IOException { int subjID=NativeValue.UNKNOWN_ID; if (subj != null) { subjID=valueStore.getID(subj); if (subjID == NativeValue.UNKNOWN_ID) { return new EmptyIteration<Statement,SailException>(); } } int predID=NativeValue.UNKNOWN_ID; if (pred != null) { predID=valueStore.getID(pred); if (predID == NativeValue.UNKNOWN_ID) { return new EmptyIteration<Statement,SailException>(); } } int objID=NativeValue.UNKNOWN_ID; if (obj != null) { objID=valueStore.getID(obj); if (objID == NativeValue.UNKNOWN_ID) { return new EmptyIteration<Statement,SailException>(); } } List<Integer> contextIDList=new ArrayList<Integer>(contexts.length); if (contexts.length == 0) { contextIDList.add(NativeValue.UNKNOWN_ID); } else { for ( Resource context : contexts) { if (context == null) { contextIDList.add(0); } else { int contextID=valueStore.getID(context); if (contextID != NativeValue.UNKNOWN_ID) { contextIDList.add(contextID); } } } } ArrayList<NativeStatementIterator> perContextIterList=new ArrayList<NativeStatementIterator>(contextIDList.size()); for ( int contextID : contextIDList) { RecordIterator btreeIter=tripleStore.getTriples(subjID,predID,objID,contextID,explicit,false); perContextIterList.add(new NativeStatementIterator(btreeIter,valueStore)); } if (perContextIterList.size() == 1) { return perContextIterList.get(0); } else { return new UnionIteration<Statement,SailException>(perContextIterList); } }
Creates a statement iterator based on the supplied pattern.
public static Random createRandom(){ return createRandom(0L); }
create a new instance of Random using default fixed seed
public void removeResultListener(ResultListener listener){ getHierarchy().removeResultListener(listener); }
Remove a result listener.
private static boolean less(Comparable v,Comparable w){ return v.compareTo(w) < 0; }
Helper sorting function.
public static <T>MonoTSeq<T> monoT(Publisher<Mono<T>> nested){ return MonoT.fromPublisher(Flux.from(nested)); }
Construct a MonoT from a Publisher containing Monos.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public STGroupFile(URL url,String encoding,char delimiterStartChar,char delimiterStopChar){ super(delimiterStartChar,delimiterStopChar); this.url=url; this.encoding=encoding; this.fileName=null; }
Pass in a URL with the location of a group file. E.g., STGroup g = new STGroupFile(loader.getResource("org/foo/templates/g.stg"), "UTF-8", '<', '>');
public StringLiteral newStringLiteral(){ return new StringLiteral(this); }
Creates and returns a new unparented string literal node for the empty string literal.
private int[] skipScan(int numVals,int rl,int[] astart){ int[] apos=new int[numVals]; if (rl > 0) { for (int k=0; k < numVals; k++) { int boff=_ptr[k]; int blen=len(k); int bix=0; int start=0; while (bix < blen) { int lstart=_data[boff + bix]; int llen=_data[boff + bix + 1]; if (start + lstart + llen >= rl) break; start+=lstart + llen; bix+=2; } apos[k]=bix; astart[k]=start; } } return apos; }
Scans to given row_lower position by scanning run length fields. Returns array of positions for all values and modifies given array of start positions for all values too.
protected void updateProgressBar(long currentSize,long totalSize){ mStatusView.setText(Utils.getProgressLabel(currentSize,totalSize)); double position=((double)currentSize / (double)totalSize) * 100.0; mProgressBar.setProgress((int)position); }
Show the transfer progress
public void testTermInDisguise() throws Exception { Query expected=new TermQuery(new Term("field","st*ar\\*")); assertEquals(expected,parse("sT*Ar\\\\\\*")); }
not a prefix query! the prefix operator is escaped
default Builder withHostname(String hostname){ return with(HOSTNAME,hostname); }
Use the given host in the resulting configuration.
public static void branchWithCommit(GitRepository repository,String name,String file,String content,boolean returnToMaster){ GitExecutor.cd(repository); GitExecutor.git("checkout -b " + name); Executor.touch(file,content); GitExecutor.git("add " + file); GitExecutor.git("commit -m branch_content"); if (returnToMaster) { GitExecutor.git("checkout master"); } }
Create a branch with a commit and return back to master.
private void remeasure(){ measure(MeasureSpec.makeMeasureSpec(getWidth(),MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(getHeight(),MeasureSpec.EXACTLY)); }
Convenience for calling own measure method.
private boolean hasNextProxy(){ return nextProxyIndex < proxies.size(); }
Returns true if there's another proxy to try.
public DiskDistributedNoAckAsyncOverflowRegionDUnitTest(){ super(); }
Creates a new instance of DiskDistributedNoAckSyncOverflowRegionTest
protected ConcurrentPhase(String name,int atomicScheduledPhase){ super(name,null); this.atomicScheduledPhase=atomicScheduledPhase; if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getSchedule(this.atomicScheduledPhase) != SCHEDULE_CONCURRENT); }
Construct a complex phase from an array of phase IDs.
public WARArchiveImpl(Archive<?> delegate){ super(WARArchive.class,delegate); setDefaultContextRoot(); addFaviconExceptionHandler(); }
Create a new JAXRS Archive with any type storage engine as backing.
public static String encode(byte[] data){ try { return encode(data,0,data.length); } catch ( ArrayIndexOutOfBoundsException aiobe) { return aiobe.toString(); } }
Description of the Method
public PropertyPanel(PropertyEditor pe,boolean ignoreCustomPanel){ m_Editor=pe; if (!ignoreCustomPanel && m_Editor instanceof CustomPanelSupplier) { setLayout(new BorderLayout()); m_CustomPanel=((CustomPanelSupplier)m_Editor).getCustomPanel(); add(m_CustomPanel,BorderLayout.CENTER); m_HasCustomPanel=true; } else { createDefaultPanel(); } }
Create the panel with the supplied property editor, optionally ignoring any custom panel the editor can provide.
@Override public void run(){ if (mState == State.MISSION_LOADED || mState == State.MISSION_RUNNING) { update(); } mUpdateHandler.postDelayed(this,DELAY_MILLIS); }
This is the main game loop. Whenever it is done, it adds itself back to the handler.
public ST(String template){ this(STGroup.defaultGroup,template); }
Used to make templates inline in code for simple things like SQL or log records. No formal arguments are set and there is no enclosing instance.
public EdgeGlow(Drawable edge,Drawable glow){ mEdge=edge; mGlow=glow; mInterpolator=new DecelerateInterpolator(); }
Instantiates a new edge glow.
public static boolean cs_print(Dcs A,boolean brief){ int p, j, m, n, nzmax, nz, Ap[], Ai[]; double Ax[]; if (A == null) { System.out.print("(null)\n"); return (false); } m=A.m; n=A.n; Ap=A.p; Ai=A.i; Ax=A.x; nzmax=A.nzmax; nz=A.nz; System.out.print(String.format("CSparseJ Version %d.%d.%d, %s. %s\n",Dcs_common.CS_VER,Dcs_common.CS_SUBVER,Dcs_common.CS_SUBSUB,Dcs_common.CS_DATE,Dcs_common.CS_COPYRIGHT)); if (nz < 0) { System.out.print(String.format("%d-by-%d, nzmax: %d nnz: %d, 1-norm: %g\n",m,n,nzmax,Ap[n],Dcs_norm.cs_norm(A))); for (j=0; j < n; j++) { System.out.print(String.format(" col %d : locations %d to %d\n",j,Ap[j],Ap[j + 1] - 1)); for (p=Ap[j]; p < Ap[j + 1]; p++) { System.out.print(String.format(" %d : %g\n",Ai[p],Ax != null ? Ax[p] : 1)); if (brief && p > 20) { System.out.print(" ...\n"); return (true); } } } } else { System.out.print(String.format("triplet: %d-by-%d, nzmax: %d nnz: %d\n",m,n,nzmax,nz)); for (p=0; p < nz; p++) { System.out.print(String.format(" %d %d : %g\n",Ai[p],Ap[p],Ax != null ? Ax[p] : 1)); if (brief && p > 20) { System.out.print(" ...\n"); return (true); } } } return (true); }
Prints a sparse matrix.
private boolean updateSelectedExporter(){ m_exporter=ExporterSelection.BinExport; return checkExporterInstall(getParent()); }
Updates the selected exporter depending on the state of the selection box.
void initForYuvFrame(int width,int height,int yStride,int uvStride,int colorspace){ this.width=width; this.height=height; this.colorspace=colorspace; int yLength=yStride * height; int uvLength=uvStride * ((height + 1) / 2); int minimumYuvSize=yLength + (uvLength * 2); if (data == null || data.capacity() < minimumYuvSize) { data=ByteBuffer.allocateDirect(minimumYuvSize); } data.limit(minimumYuvSize); if (yuvPlanes == null) { yuvPlanes=new ByteBuffer[3]; } data.position(0); yuvPlanes[0]=data.slice(); yuvPlanes[0].limit(yLength); data.position(yLength); yuvPlanes[1]=data.slice(); yuvPlanes[1].limit(uvLength); data.position(yLength + uvLength); yuvPlanes[2]=data.slice(); yuvPlanes[2].limit(uvLength); if (yuvStrides == null) { yuvStrides=new int[3]; } yuvStrides[0]=yStride; yuvStrides[1]=uvStride; yuvStrides[2]=uvStride; }
Resizes the buffer based on the given stride. Called via JNI after decoding completes.
public void deleteLabel(Serializable projectId,String name) throws IOException { Query query=new Query(); query.append("name",name); String tailUrl=GitlabProject.URL + "/" + projectId+ GitlabLabel.URL+ query.toString(); retrieve().method("DELETE").to(tailUrl,Void.class); }
Deletes an existing label.
public static void quickSort(double[] a,int fromIndex,int toIndex,DoubleComparator c){ rangeCheck(a.length,fromIndex,toIndex); quickSort1(a,fromIndex,toIndex - fromIndex,c); }
Sorts the specified range of the specified array of elements according to the order induced by the specified comparator. All elements in the range must be <i>mutually comparable</i> by the specified comparator (that is, <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt> for any elements <tt>e1</tt> and <tt>e2</tt> in the range).<p> The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException { return visitor.visit(this,data); }
Accept the visitor.
public BatchUpdateException(String reason,String SQLState,int vendorCode,int[] updateCounts,Throwable cause){ super(reason,SQLState,vendorCode,cause); this.updateCounts=(updateCounts == null) ? null : Arrays.copyOf(updateCounts,updateCounts.length); this.longUpdateCounts=(updateCounts == null) ? null : copyUpdateCount(updateCounts); }
Constructs a <code>BatchUpdateException</code> object initialized with a given <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> <code>cause</code> and <code>updateCounts</code>.
public static boolean isSqlType(Class<?> cls){ cls=U.box(cls); return SQL_TYPES.contains(cls) || isGeometryClass(cls); }
Checks if the given class can be mapped to a simple SQL type.
@POST @Path("{noteId}/paragraph") @ZeppelinApi public Response insertParagraph(@PathParam("noteId") String noteId,String message) throws IOException { LOG.info("insert paragraph {} {}",noteId,message); Note note=notebook.getNote(noteId); if (note == null) { return new JsonResponse<>(Status.NOT_FOUND,"note not found.").build(); } NewParagraphRequest request=gson.fromJson(message,NewParagraphRequest.class); Paragraph p; Double indexDouble=request.getIndex(); if (indexDouble == null) { p=note.addParagraph(); } else { p=note.insertParagraph(indexDouble.intValue()); } p.setTitle(request.getTitle()); p.setText(request.getText()); AuthenticationInfo subject=new AuthenticationInfo(SecurityUtils.getPrincipal()); note.persist(subject); notebookServer.broadcastNote(note); return new JsonResponse<>(Status.CREATED,"",p.getId()).build(); }
Insert paragraph REST API
public void registerSpecialTileEntities(){ GameRegistry.registerTileEntity(TileEntityAdvancedSolarGenerator.class,"AdvancedSolarGenerator"); GameRegistry.registerTileEntity(TileEntitySolarGenerator.class,"SolarGenerator"); GameRegistry.registerTileEntity(TileEntityBioGenerator.class,"BioGenerator"); GameRegistry.registerTileEntity(TileEntityHeatGenerator.class,"HeatGenerator"); GameRegistry.registerTileEntity(TileEntityGasGenerator.class,"GasGenerator"); GameRegistry.registerTileEntity(TileEntityWindTurbine.class,"WindTurbine"); GameRegistry.registerTileEntity(TileEntityReactorController.class,"ReactorController"); }
Register tile entities that have special models. Overwritten in client to register TESRs.
public String toString(){ return getValue() ? "true" : "false"; }
Obtains the string representation of this object.
public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); }
Append either the value <code>true</code> or the value <code>false</code>.
private void validateQuietZone(BitArray row,int startPattern) throws NotFoundException { int quietCount=this.narrowLineWidth * 10; quietCount=quietCount < startPattern ? quietCount : startPattern; for (int i=startPattern - 1; quietCount > 0 && i >= 0; i--) { if (row.get(i)) { break; } quietCount--; } if (quietCount != 0) { throw NotFoundException.getNotFoundInstance(); } }
The start & end patterns must be pre/post fixed by a quiet zone. This zone must be at least 10 times the width of a narrow line. Scan back until we either get to the start of the barcode or match the necessary number of quiet zone pixels. Note: Its assumed the row is reversed when using this method to find quiet zone after the end pattern. ref: http://www.barcode-1.net/i25code.html
public FloatMatrix put(int i,float v){ data[i]=v; return this; }
Set a matrix element (linear indexing).
public void startCDATA() throws SAXException { m_handler.startCDATA(); }
Pass the call on to the underlying handler
public List<Recommendation> scheduleStorageForMirror(VirtualArray srcVarray,VirtualPool srcVpool,VirtualPool mirrorVpool,VirtualPoolCapabilityValuesWrapper capabilities,URI vplexStorageSystemURI,URI excludeStorageSystem,String cluster){ _log.info("Executing VPlex Mirror placement strategy"); List<Recommendation> recommendations=new ArrayList<Recommendation>(); _log.info("Getting placement recommendations for srcVarray {}",srcVarray.getId()); Map<String,Object> attributeMap=new HashMap<String,Object>(); List<StoragePool> allMatchingPools=getMatchingPools(srcVarray,null,excludeStorageSystem,mirrorVpool,capabilities,attributeMap); _log.info("Found {} Matching pools for VirtualArray for the Mirror",allMatchingPools.size()); StringBuffer errorMessage=(StringBuffer)attributeMap.get(AttributeMatcher.ERROR_MESSAGE); if ((CollectionUtils.isEmpty(allMatchingPools)) && (errorMessage != null) && (errorMessage.length() != 0)) { throw APIException.badRequests.noStoragePools(srcVarray.getLabel(),srcVpool.getLabel(),errorMessage.toString()); } Map<String,List<StoragePool>> vplexPoolMapForSrcVarray=sortPoolsByVPlexStorageSystem(allMatchingPools,srcVarray.getId().toString(),cluster); Iterator<Entry<String,List<StoragePool>>> it=vplexPoolMapForSrcVarray.entrySet().iterator(); if (vplexStorageSystemURI != null) { while (it.hasNext()) { Entry<String,List<StoragePool>> entry=it.next(); String vplexKey=entry.getKey(); URI vplexURI=null; try { vplexURI=URI.create(vplexKey); } catch ( IllegalArgumentException ex) { _log.error("Bad VPLEX URI: " + vplexURI); continue; } if (false == vplexStorageSystemURI.equals(vplexURI)) { it.remove(); } } } if (vplexPoolMapForSrcVarray.isEmpty()) { _log.info("No matching pools on storage systems connected to a VPlex"); return recommendations; } Set<String> vplexStorageSystemIds=vplexPoolMapForSrcVarray.keySet(); vplexStorageSystemIds=vplexPoolMapForSrcVarray.keySet(); _log.info("{} VPlex storage systems have matching pools",vplexStorageSystemIds.size()); Iterator<String> vplexSystemIdsIter=vplexStorageSystemIds.iterator(); while ((vplexSystemIdsIter.hasNext()) && (recommendations.isEmpty())) { String vplexStorageSystemId=vplexSystemIdsIter.next(); _log.info("Check matching pools for VPlex {}",vplexStorageSystemId); if (VirtualPool.ProvisioningType.Thin.toString().equalsIgnoreCase(mirrorVpool.getSupportedProvisioningType())) { capabilities.put(VirtualPoolCapabilityValuesWrapper.THIN_PROVISIONING,Boolean.TRUE); } List<Recommendation> recommendationsForMirrorVarray=_blockScheduler.getRecommendationsForPools(srcVarray.getId().toString(),vplexPoolMapForSrcVarray.get(vplexStorageSystemId),capabilities); if (recommendationsForMirrorVarray.isEmpty()) { _log.info("Matching pools insufficient for placement"); continue; } _log.info("Matching pools sufficient for placement"); recommendations.addAll(createVPlexRecommendations(vplexStorageSystemId,srcVarray,srcVpool,recommendationsForMirrorVarray)); continue; } return recommendations; }
Get recommendations for resource placement based on the passed parameters.
protected void fireOptionSelected(JOptionPane pane){ Object value=pane.getValue(); int option; if (value == null) { option=JOptionPane.CLOSED_OPTION; } else { if (pane.getOptions() == null) { if (value instanceof Integer) { option=((Integer)value).intValue(); } else { option=JOptionPane.CLOSED_OPTION; } } else { option=JOptionPane.CLOSED_OPTION; Object[] options=pane.getOptions(); for (int i=0, n=options.length; i < n; i++) { if (options[i].equals(value)) { option=i; break; } } if (option == JOptionPane.CLOSED_OPTION) { value=null; } } } fireOptionSelected(pane,option,value,pane.getInputValue()); }
Notify all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
protected void downloadUsingMaven(String target,String group,String artifact,String version,String sha1Checksum){ String repoDir="http://repo1.maven.org/maven2"; File targetFile=new File(target); if (targetFile.exists()) { return; } String repoFile=group.replace('.','/') + "/" + artifact+ "/"+ version+ "/"+ artifact+ "-"+ version+ ".jar"; mkdirs(targetFile.getAbsoluteFile().getParentFile()); String localMavenDir=getLocalMavenDir(); if (new File(localMavenDir).exists()) { File f=new File(localMavenDir,repoFile); if (!f.exists()) { try { execScript("mvn",args("org.apache.maven.plugins:maven-dependency-plugin:2.1:get","-D" + "repoUrl=" + repoDir,"-D" + "artifact=" + group + ":"+ artifact+ ":"+ version)); } catch ( RuntimeException e) { println("Could not download using Maven: " + e.toString()); } } if (f.exists()) { byte[] data=readFile(f); String got=getSHA1(data); if (sha1Checksum == null) { println("SHA1 checksum: " + got); } else { if (!got.equals(sha1Checksum)) { throw new RuntimeException("SHA1 checksum mismatch; got: " + got + " expected: "+ sha1Checksum+ " for file "+ f.getAbsolutePath()); } } writeFile(targetFile,data); return; } } String fileURL=repoDir + "/" + repoFile; download(target,fileURL,sha1Checksum); }
Download a file if it does not yet exist. Maven is used if installed, so that the file is first downloaded to the local repository and then copied from there.
public LabeledIntent(Intent origIntent,String sourcePackage,int labelRes,int icon){ super(origIntent); mSourcePackage=sourcePackage; mLabelRes=labelRes; mNonLocalizedLabel=null; mIcon=icon; }
Create a labeled intent from the given intent, supplying the label and icon resources for it.
@Override protected void installDefaults(){ super.installDefaults(); table.setRowHeight(25); table.setShowVerticalLines(false); table.setIntercellSpacing(new Dimension(0,1)); }
Initialize JTable properties, e.g. font, foreground, and background. The font, foreground, and background properties are only set if their current value is either null or a UIResource, other properties are set if the current value is null.
private void generateXmlFile(int w,int h){ StringBuffer sbForWidth=new StringBuffer(); sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); sbForWidth.append("<resources>\n"); float cellw=((w * 1.0f / baseW)); System.out.println("width : " + w + ","+ baseW+ ","+ cellw); for (int i=1; i < baseW; i++) { sbForWidth.append(WTemplate.replace("{0}",i + "").replace("{1}",change(cellw * i) + "")); } sbForWidth.append(WTemplate.replace("{0}",baseW + "").replace("{1}",w + "")); sbForWidth.append("</resources>"); StringBuffer sbForHeight=new StringBuffer(); sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); sbForHeight.append("<resources>"); float cellh=h * 1.0f / baseH; System.out.println("height : " + h + ","+ baseH+ ","+ cellh); for (int i=1; i < baseH; i++) { sbForHeight.append(HTemplate.replace("{0}",i + "").replace("{1}",change(cellh * i) + "")); } sbForHeight.append(HTemplate.replace("{0}",baseH + "").replace("{1}",h + "")); sbForHeight.append("</resources>"); File fileDir=new File(dirStr + File.separator + VALUE_TEMPLATE.replace("{0}",w + "").replace("{1}",h + "")); fileDir.mkdir(); File layxFile=new File(fileDir.getAbsolutePath(),"w_dimens.xml"); File layyFile=new File(fileDir.getAbsolutePath(),"h_dimens.xml"); try { PrintWriter pw=new PrintWriter(new FileOutputStream(layxFile)); pw.print(sbForWidth.toString()); pw.close(); pw=new PrintWriter(new FileOutputStream(layyFile)); pw.print(sbForHeight.toString()); pw.close(); } catch ( FileNotFoundException e) { e.printStackTrace(); } }
xml 2
protected TransactionID sendRequest(Request request,boolean firstRequest,TransactionID transactionID) throws StunException { if (!firstRequest && (longTermCredentialSession != null)) longTermCredentialSession.addAttributes(request); StunStack stunStack=harvester.getStunStack(); TransportAddress stunServer=harvester.stunServer; TransportAddress hostCandidateTransportAddress=hostCandidate.getTransportAddress(); if (transactionID == null) { byte[] transactionIDAsBytes=request.getTransactionID(); transactionID=(transactionIDAsBytes == null) ? TransactionID.createNewTransactionID() : TransactionID.createTransactionID(harvester.getStunStack(),transactionIDAsBytes); } synchronized (requests) { try { transactionID=stunStack.sendRequest(request,stunServer,hostCandidateTransportAddress,this,transactionID); } catch ( IllegalArgumentException iaex) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO,"Failed to send " + request + " through "+ hostCandidateTransportAddress+ " to "+ stunServer,iaex); } throw new StunException(StunException.ILLEGAL_ARGUMENT,iaex.getMessage(),iaex); } catch ( IOException ioex) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO,"Failed to send " + request + " through "+ hostCandidateTransportAddress+ " to "+ stunServer,ioex); } throw new StunException(StunException.NETWORK_ERROR,ioex.getMessage(),ioex); } requests.put(transactionID,request); } return transactionID; }
Sends a specific <tt>Request</tt> to the STUN server associated with this <tt>StunCandidateHarvest</tt>.
public void paint(Graphics a,JComponent b){ for (int i=0; i < uis.size(); i++) { ((ComponentUI)(uis.elementAt(i))).paint(a,b); } }
Invokes the <code>paint</code> method on each UI handled by this object.
private static void registerRJRLauncher(ILaunchConfiguration configuration,ILaunch launch) throws CoreException { String port=configuration.getAttribute(Plugin.ATTR_PORT,""); String sslPort=configuration.getAttribute(Plugin.ATTR_SSL_PORT,""); boolean enableSSL=configuration.getAttribute(Plugin.ATTR_ENABLE_SSL,false); if (!"".equals(port)) launcher.put(port,launch); if (enableSSL && !"".equals(sslPort)) launcher.put(sslPort,launch); }
register a port for RJR Launcher
protected Size2D arrangeRR(BlockContainer container,Graphics2D g2,RectangleConstraint constraint){ Size2D s1=arrangeNN(container,g2); if (constraint.getWidthRange().contains(s1.width)) { return s1; } else { RectangleConstraint c=constraint.toFixedWidth(constraint.getWidthRange().getUpperBound()); return arrangeFR(container,g2,c); } }
Arranges the blocks with the overall width and height to fit within specified ranges.
public TradeOrderfill findById(Integer id){ try { EntityManager entityManager=EntityManagerHelper.getEntityManager(); entityManager.getTransaction().begin(); TradeOrderfill instance=entityManager.find(TradeOrderfill.class,id); entityManager.getTransaction().commit(); return instance; } catch ( Exception re) { EntityManagerHelper.rollback(); throw re; } finally { EntityManagerHelper.close(); } }
Method findById.
public static final double[][] random(final int m,final int n){ final double[][] A=new double[m][n]; for (int i=0; i < m; i++) { for (int j=0; j < n; j++) { A[i][j]=Math.random(); } } return A; }
Generate matrix with random elements
public void pageBreak(){ synchronized (this.lock) { if (isPreview) { pageImages.addElement(previewImage); } if (page != null) { page.dispose(); } page=null; newpage(); } }
End the current page. Subsequent output will be on a new page
public int hashCode(){ int retval=0; for (int i=1; i < this.key.length; i++) { retval+=this.key[i] * i; } return (retval^=getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode()); }
Calculates a hash code value for the object. Objects that are equal will also have the same hashcode.
public void applyEffects(Player player,Object... objects){ if (evaluate(objects).toBoolean()) { if (isType(ApplyType.VELOCITY)) { player.applyImpulse(velocity); } else if (kit != null) { kit.apply(player,false); } } }
Applies the effects in this region (kits or velocity) to a player if the filter allows it.
private static int GetMethodID(JNIEnvironment env,int classJREF,Address methodNameAddress,Address methodSigAddress){ if (traceJNI) VM.sysWrite("JNI called: GetMethodID \n"); RuntimeEntrypoints.checkJNICountDownToGC(); try { String methodString=JNIGenericHelpers.createStringFromC(methodNameAddress); Atom methodName=Atom.findOrCreateAsciiAtom(methodString); String sigString=JNIGenericHelpers.createStringFromC(methodSigAddress); Atom sigName=Atom.findOrCreateAsciiAtom(sigString); Class<?> jcls=(Class<?>)env.getJNIRef(classJREF); RVMType type=java.lang.JikesRVMSupport.getTypeForClass(jcls); if (!type.isClassType()) { env.recordException(new NoSuchMethodError()); return 0; } RVMClass klass=type.asClass(); if (!klass.isInitialized()) { RuntimeEntrypoints.initializeClassForDynamicLink(klass); } final RVMMethod meth; if (methodString.equals("<init>")) { meth=klass.findInitializerMethod(sigName); } else { meth=klass.findVirtualMethod(methodName,sigName); } if (meth == null) { env.recordException(new NoSuchMethodError(klass + ": " + methodName+ " "+ sigName)); return 0; } if (traceJNI) VM.sysWrite("got method " + meth + "\n"); return meth.getId(); } catch ( Throwable unexpected) { if (traceJNI) unexpected.printStackTrace(System.err); env.recordException(unexpected); return 0; } }
GetMethodID: get the virtual method ID given the name and the signature
private static String hextetsToIPv6String(int[] hextets){ StringBuilder buf=new StringBuilder(39); boolean lastWasNumber=false; for (int i=0; i < hextets.length; i++) { boolean thisIsNumber=hextets[i] >= 0; if (thisIsNumber) { if (lastWasNumber) { buf.append(':'); } buf.append(Integer.toHexString(hextets[i])); } else { if (i == 0 || lastWasNumber) { buf.append("::"); } } lastWasNumber=thisIsNumber; } return buf.toString(); }
Convert a list of hextets into a human-readable IPv6 address. <p>In order for "::" compression to work, the input should contain negative sentinel values in place of the elided zeroes.
public DcwVariableLengthIndexFile(BinaryFile inputstream,boolean msbfirst) throws FormatException { try { inputstream.byteOrder(msbfirst); recordCount=inputstream.readInteger(); inputstream.readInteger(); offsettable=new int[recordCount * 2]; inputstream.readIntegerArray(offsettable,0,recordCount * 2); endOfFileOffset=offsettable[offsettable.length - 2] + offsettable[offsettable.length - 1]; inputstream.close(); } catch ( IOException i) { throw new FormatException("IOException with " + inputstream.getName() + ": "+ i.getMessage()); } }
Construct a new index file.
static public byte[] ascii2binary(String str){ if (str == null) return null; String val=str.substring(2); int size=val.length(); byte[] buf=new byte[size / 2]; byte[] p=val.getBytes(); for (int i=0; i < (size / 2); i++) { int j=i * 2; byte v=0; if (p[j] >= '0' && p[j] <= '9') { v=(byte)((p[j] - '0') << 4); } else if (p[j] >= 'a' && p[j] <= 'f') { v=(byte)((p[j] - 'a' + 10) << 4); } else if (p[j] >= 'A' && p[j] <= 'F') { v=(byte)((p[j] - 'A' + 10) << 4); } else throw new Error("BAD format :" + str); if (p[j + 1] >= '0' && p[j + 1] <= '9') { v+=(p[j + 1] - '0'); } else if (p[j + 1] >= 'a' && p[j + 1] <= 'f') { v+=(p[j + 1] - 'a' + 10); } else if (p[j + 1] >= 'A' && p[j + 1] <= 'F') { v+=(p[j + 1] - 'A' + 10); } else throw new Error("BAD format :" + str); buf[i]=v; } return buf; }
Translates a stringified representation in a binary one. The passed string is an hexadecimal one starting with 0x.
public final void test_write$BII_2() throws IOException { assertEquals(0,MY_MESSAGE_LEN % CHUNK_SIZE); for (int k=0; k < algorithmName.length; k++) { try { ByteArrayOutputStream bos=new ByteArrayOutputStream(MY_MESSAGE_LEN); MessageDigest md=MessageDigest.getInstance(algorithmName[k]); DigestOutputStream dos=new DigestOutputStream(bos,md); for (int i=0; i < MY_MESSAGE_LEN / CHUNK_SIZE; i++) { dos.write(myMessage,i * CHUNK_SIZE,CHUNK_SIZE); } assertTrue("write",Arrays.equals(myMessage,bos.toByteArray())); assertTrue("update",Arrays.equals(dos.getMessageDigest().digest(),MDGoldenData.getDigest(algorithmName[k]))); return; } catch ( NoSuchAlgorithmException e) { } } fail(getName() + ": no MessageDigest algorithms available - test not performed"); }
Test #2 for <code>write(byte[],int,int)</code> method<br> Assertion: put bytes into output stream<br> Assertion: updates associated digest<br>
public void rollbackChildWorkflow(URI parentURI,String childOrchestrationTaskId,String stepId){ Workflow parentWorkflow=loadWorkflowFromUri(parentURI); if (parentWorkflow == null) { _log.info("Could not locate parent workflow %s (%s), possibly it was already deleted"); ServiceCoded coded=WorkflowException.exceptions.workflowNotFound(parentURI.toString()); WorkflowStepCompleter.stepFailed(stepId,coded); } for ( URI childURI : parentWorkflow._childWorkflows) { Workflow childWorkflow=loadWorkflowFromUri(childURI); if (childWorkflow == null) { _log.info("Could not locate child workflow %s (%s), possibly it was already deleted"); WorkflowStepCompleter.stepSucceded(stepId); return; } if (!NullColumnValueGetter.isNullValue(childWorkflow.getOrchTaskId()) && childWorkflow.getOrchTaskId().equals(childOrchestrationTaskId)) { rollbackInnerWorkflow(childWorkflow,stepId); return; } } WorkflowStepCompleter.stepSucceded(stepId); }
This call will rollback a child workflow given the parent's workflow URI and the step-id of the parent step which is the child workflow's orchestration task id. <p> The idea is that if step of a parent workflow creates a child workflow, which completes successfully, but then a later step in the parent workflow fails, initiating rollback, we need an easy way to rollback the entire child workflow in the rollback method of the step that created the child workflow. <p> So this method should only be called from a parent workflow's rollback method for the step that initiated the child workflow. In order to be eligible to be rolled back, the child workflow must have completed successfully. It will be completely rolled back (i.e. all steps in the child workflow) will be rolled back.
public static void onEvent(final Context context,final String event_id,final String label){ onEvent(context,event_id,label,1); }
log the event
private final ArrayList<Integer> findChildren(int index){ ArrayList<Integer> ret=new ArrayList<Integer>(); StartEntry se=new StartEntry(); EndEntry ee=new EndEntry(); int child=index + 1; while ((child >= 0) && (child < numEntries)) { boolean haveEE=readEntries(child,se,ee); if (se.parentIndex == index) ret.add(child); if (!haveEE) break; if (child != ee.startIndex) break; child=se.endIndex + 1; } return ret; }
Find all children of a node.
public JoinStateData(StateHolder<S,E> state,Guard<S,E> guard){ Assert.notNull(state,"Holder must be set"); this.state=state; this.guard=guard; }
Instantiates a new join state data.
public double nextDouble(){ return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); }
A bug fix for versions of JDK 1.1 and below. JDK 1.2 fixes this for us, but what the heck.
public int writeCRT(ByteBuffer databuf,Position.LineMap lineMap,Log log){ int crtEntries=0; new SourceComputer().csp(methodTree); for (List<CRTEntry> l=entries.toList(); l.nonEmpty(); l=l.tail) { CRTEntry entry=l.head; if (entry.startPc == entry.endPc) continue; SourceRange pos=positions.get(entry.tree); Assert.checkNonNull(pos,"CRT: tree source positions are undefined"); if ((pos.startPos == Position.NOPOS) || (pos.endPos == Position.NOPOS)) continue; if (crtDebug) { System.out.println("Tree: " + entry.tree + ", type:"+ getTypes(entry.flags)); System.out.print("Start: pos = " + pos.startPos + ", pc = "+ entry.startPc); } int startPos=encodePosition(pos.startPos,lineMap,log); if (startPos == Position.NOPOS) continue; if (crtDebug) { System.out.print("End: pos = " + pos.endPos + ", pc = "+ (entry.endPc - 1)); } int endPos=encodePosition(pos.endPos,lineMap,log); if (endPos == Position.NOPOS) continue; databuf.appendChar(entry.startPc); databuf.appendChar(entry.endPc - 1); databuf.appendInt(startPos); databuf.appendInt(endPos); databuf.appendChar(entry.flags); crtEntries++; } return crtEntries; }
Compute source positions and write CRT to the databuf.
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client,Path out_tmp,String url) throws IOException, InterruptedException { try (FileChannel output=FileChannel.open(out_tmp,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){ HttpResponse response=http_client.interruptibleGet(url,output); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Formatter ff=new Formatter(); ff.format("Synchronizer#%d cannot download product at %s," + " remote dhus returned message '%s' (HTTP%d)",getId(),url,response.getStatusLine().getReasonPhrase(),response.getStatusLine().getStatusCode()); throw new IOException(ff.out().toString()); } Pattern pat=Pattern.compile("filename=\"(.+?)\"",Pattern.CASE_INSENSITIVE); String contdis=response.getFirstHeader("Content-Disposition").getValue(); Matcher m=pat.matcher(contdis); if (!m.find()) { throw new IOException("Synchronizer#" + getId() + " Missing HTTP header field `Content-Disposition` that determines the filename"); } String filename=m.group(1); if (filename == null || filename.isEmpty()) { throw new IOException("Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`"); } output.close(); Path dest=out_tmp.getParent().resolve(filename); Files.move(out_tmp,dest,StandardCopyOption.ATOMIC_MOVE); DownloadResult res=new DownloadResult(dest,response.getEntity().getContentType().getValue(),response.getEntity().getContentLength()); return res; } finally { if (Files.exists(out_tmp)) { Files.delete(out_tmp); } } }
Uses the given `http_client` to download `url` into `out_tmp`. Renames `out_tmp` to the value of the filename param of the Content-Disposition header field. Returns a path to the renamed file.
public static String byteArrayToBase64(byte[] a){ return byteArrayToBase64(a,false); }
Translates the specified byte array into a Base64 string as per Preferences.put(byte[]).
public Burner(String devName){ this.devName=devName; }
Creates a new instance of Burner
public ServerBuilder idleTimeoutMillis(long idleTimeoutMillis){ return idleTimeout(Duration.ofMillis(idleTimeoutMillis)); }
Sets the idle timeout of a connection in milliseconds.
protected void assertSigningDateInCertificateValidityRange(final SP parameters){ if (parameters.isSignWithExpiredCertificate()) { return; } final CertificateToken signingCertificate=parameters.getSigningCertificate(); final Date notAfter=signingCertificate.getNotAfter(); final Date notBefore=signingCertificate.getNotBefore(); final Date signingDate=parameters.bLevel().getSigningDate(); if (signingDate.after(notAfter) || signingDate.before(notBefore)) { throw new DSSException(String.format("Signing Date (%s) is not in certificate validity range (%s, %s).",signingDate.toString(),notBefore.toString(),notAfter.toString())); } }
This method raises an exception if the signing rules forbid the use on an expired certificate.
public void initProviderConnection(XBeeConnection connection) throws XBeeException { if (this.isConnected()) { throw new IllegalStateException("Cannot open new connection -- existing connection is still open. Please close first"); } initConnection(connection); }
Allows a protocol specific implementation of XBeeConnection to be used instead of the default RXTX connection. The connection must already be established as the interface has no means to do so.
static synchronized void registerSpecialVersion(SpecializedMethod spMethod){ RVMMethod source=spMethod.getMethod(); MethodSet<RVMMethod> s=findOrCreateMethodSet(specialVersionsHash,source); s.add(spMethod); deferredMethods.add(spMethod); }
Records a new specialized method in this database. Also remember that this method will need to be compiled later, at the next call to <code> doDeferredSpecializations() </code>
public static void assignScheduleModesToLinks(TransitSchedule schedule,Network network){ log.info("... Assigning schedule transport mode to network"); Map<Id<Link>,Set<String>> transitLinkNetworkModes=new HashMap<>(); for ( TransitLine line : schedule.getTransitLines().values()) { for ( TransitRoute route : line.getRoutes().values()) { if (route.getRoute() != null) { for ( Id<Link> linkId : getTransitRouteLinkIds(route)) { MapUtils.getSet(linkId,transitLinkNetworkModes).add(route.getTransportMode()); } } } } for ( Link link : network.getLinks().values()) { if (transitLinkNetworkModes.containsKey(link.getId())) { Set<String> modes=new HashSet<>(); Set<String> linkModes=transitLinkNetworkModes.get(link.getId()); linkModes.addAll(link.getAllowedModes()); for ( String m : linkModes) { modes.add(m); } link.setAllowedModes(modes); } } }
Adds mode the schedule transport mode to links. Removes all network modes elsewhere. Adds mode "artificial" to artificial links. Used for debugging and visualization since networkModes should be combined to pt anyway.
public boolean add(WorkListItem item){ if (DEBUG) { System.out.println("Adding " + item.getURL().toString()); } if (!addedSet.add(item.getURL().toString())) { if (DEBUG) { System.out.println("\t==> Already processed"); } return false; } itemList.add(item); return true; }
Add a worklist item.
private void startSampleHost() throws Throwable { this.sampleHost=new SampleHost(); String bindAddress="127.0.0.1"; String hostId=UUID.randomUUID().toString(); String[] args={"--port=0","--bindAddress=" + bindAddress,"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),"--id=" + hostId}; this.sampleHost.initialize(args); this.sampleHost.start(); assertEquals(bindAddress,this.sampleHost.getPreferredAddress()); assertEquals(bindAddress,this.sampleHost.getUri().getHost()); assertEquals(hostId,this.sampleHost.getId()); assertEquals(this.sampleHost.getUri(),this.sampleHost.getPublicUri()); }
Starts the sample host and does some validation that it started correctly.
public void addFileTransferInvitationRejected(ContactId remoteContact,MmContent content,MmContent fileIcon,FileTransfer.ReasonCode reasonCode,long timestamp,long timestampSent){ mFileTransferService.addFileTransferInvitationRejected(remoteContact,content,fileIcon,reasonCode,timestamp,timestampSent); }
Handle the case of rejected file transfer
public void testSubmitQuery() throws Throwable { Connection connection=mock(Connection.class); when(connection.send(any(QueryRequest.class))).thenReturn(CompletableFuture.completedFuture(QueryResponse.builder().withStatus(Response.Status.OK).withIndex(10).withResult("Hello world!").build())); ClientSessionState state=new ClientSessionState(UUID.randomUUID()).setSessionId(1).setState(Session.State.OPEN); Executor executor=new MockExecutor(); ThreadContext context=mock(ThreadContext.class); when(context.executor()).thenReturn(executor); ClientSessionSubmitter submitter=new ClientSessionSubmitter(connection,state,new ClientSequencer(state),context); assertEquals(submitter.submit(new TestQuery()).get(),"Hello world!"); assertEquals(state.getResponseIndex(),10); }
Tests submitting a query to the cluster.
private boolean isAuthor(ProductReview reviewToBeRemoved){ if (getLoggedInUser().equals(reviewToBeRemoved.getPlatformUser())) { return true; } else return false; }
checks if the currently logged in user is the author of the review to be removed.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:08.677 -0500",hash_original_method="32932F147EA25CC7B7BC47F740C6BF91",hash_generated_method="0DC811C156890046C4A2AB310C83BF76") public boolean isHeaderList(){ return true; }
Return true if this is a header list (overrides the base class method which returns false).
public void header(int version,long length,int twipsWidth,int twipsHeight,int frameRate,int frameCount) throws IOException { tagtypes.header(version,length,twipsWidth,twipsHeight,frameRate,frameCount); }
Interface SWFTags
@Override public void generateCode(BlockScope currentScope,boolean valueRequired){ }
MessageSendDotClass code generation
public static void subOverflow(final long offset,final ITranslationEnvironment environment,final IInstruction instruction,final List<ReilInstruction> instructions,final OperandSize firstOperandSize,final String firstOperand,final OperandSize secondOperandSize,final String secondOperand,final OperandSize resultOperandSize,final String resultOperand,final String overflow,final long size){ final OperandSize bt=OperandSize.BYTE; final OperandSize wd=OperandSize.WORD; final String msbVara=environment.getNextVariableString(); final String msbVarb=environment.getNextVariableString(); final String msbVarr=environment.getNextVariableString(); final String tmpVar3=environment.getNextVariableString(); final String tmpVar4=environment.getNextVariableString(); final String shiftVal="-" + String.valueOf(size - 1); long baseOffset=offset; instructions.add(ReilHelpers.createBsh(baseOffset++,firstOperandSize,firstOperand,wd,shiftVal,bt,msbVara)); instructions.add(ReilHelpers.createBsh(baseOffset++,secondOperandSize,secondOperand,wd,shiftVal,bt,msbVarb)); instructions.add(ReilHelpers.createBsh(baseOffset++,resultOperandSize,resultOperand,wd,shiftVal,bt,msbVarr)); instructions.add(ReilHelpers.createAnd(baseOffset++,bt,msbVara,bt,String.valueOf(1),bt,msbVara)); instructions.add(ReilHelpers.createAnd(baseOffset++,bt,msbVarb,bt,String.valueOf(1),bt,msbVarb)); instructions.add(ReilHelpers.createAnd(baseOffset++,bt,msbVarr,bt,String.valueOf(1),bt,msbVarr)); instructions.add(ReilHelpers.createXor(baseOffset++,bt,msbVara,bt,msbVarb,bt,tmpVar4)); instructions.add(ReilHelpers.createXor(baseOffset++,bt,msbVara,bt,msbVarr,bt,tmpVar3)); instructions.add(ReilHelpers.createAnd(baseOffset++,bt,tmpVar4,bt,tmpVar3,bt,overflow)); }
overflow condition if operation was a subtraction
void insertExceptionalPrologue(){ if (VM.VerifyAssertions) { VM._assert((frameSize & (STACKFRAME_ALIGNMENT - 1)) == 0,"Stack frame alignment error"); } if (frameSize >= 0x7ff0) { throw new OptimizingCompilerException("Stackframe size exceeded!"); } PhysicalRegisterSet phys=ir.regpool.getPhysicalRegisterSet().asPPC(); Register FP=phys.getFP(); Register TR=phys.getTR(); Register TSR=phys.getTSR(); Register R0=phys.getTemp(); Register S1=phys.getGPR(LAST_SCRATCH_GPR); boolean interruptible=ir.method.isInterruptible(); boolean stackOverflow=interruptible; boolean yp=hasPrologueYieldpoint(); Instruction ptr=ir.firstInstructionInCodeOrder().nextInstructionInCodeOrder(); if (VM.VerifyAssertions) VM._assert(ptr.getOpcode() == IR_PROLOGUE_opcode); if (stackOverflow) { ptr.insertBefore(MIR_Store.create(PPC_STAddr,A(S1),A(FP),IC(STACKFRAME_RETURN_ADDRESS_OFFSET.toInt()))); Offset offset=Entrypoints.stackLimitField.getOffset(); if (VM.VerifyAssertions) VM._assert(fits(offset,16)); ptr.insertBefore(MIR_Load.create(PPC_LAddr,A(S1),A(phys.getTR()),IC(PPCMaskLower16(offset)))); ptr.insertBefore(MIR_Binary.create(PPC_ADDI,A(R0),A(S1),IC(frameSize))); ptr.insertBefore(MIR_Load.create(PPC_LAddr,A(S1),A(FP),IC(STACKFRAME_RETURN_ADDRESS_OFFSET.toInt()))); MIR_Trap.mutate(ptr,PPC_TAddr,PowerPCTrapOperand.LESS(),A(FP),A(R0),TrapCodeOperand.StackOverflow()); ptr=ptr.nextInstructionInCodeOrder(); } else { Instruction next=ptr.nextInstructionInCodeOrder(); ptr.remove(); ptr=next; } ptr.insertBefore(MIR_Move.create(PPC_MFSPR,A(R0),A(phys.getLR()))); ptr.insertBefore(MIR_StoreUpdate.create(PPC_STAddrU,A(FP),A(FP),IC(-frameSize))); ptr.insertBefore(MIR_Store.create(PPC_STAddr,A(R0),A(FP),IC(frameSize + STACKFRAME_RETURN_ADDRESS_OFFSET.toInt()))); int cmid=ir.compiledMethod.getId(); if (cmid <= 0x7fff) { ptr.insertBefore(MIR_Unary.create(PPC_LDI,I(R0),IC(cmid))); } else { ptr.insertBefore(MIR_Unary.create(PPC_LDIS,I(R0),IC(cmid >>> 16))); ptr.insertBefore(MIR_Binary.create(PPC_ORI,I(R0),I(R0),IC(cmid & 0xffff))); } ptr.insertBefore(MIR_Store.create(PPC_STW,I(R0),A(FP),IC(STACKFRAME_METHOD_ID_OFFSET.toInt()))); if (ir.compiledMethod.isSaveVolatile()) { saveVolatiles(ptr); } saveNonVolatiles(ptr); if (yp) { Offset offset=Entrypoints.takeYieldpointField.getOffset(); if (VM.VerifyAssertions) VM._assert(fits(offset,16)); ptr.insertBefore(MIR_Load.create(PPC_LInt,I(R0),A(TR),IC(PPCMaskLower16(offset)))); ptr.insertBefore(MIR_Binary.create(PPC_CMPI,I(TSR),I(R0),IC(0))); } }
prologue for the exceptional case. (1) R0 is the only available scratch register. (2) stack overflow check has to come first.
protected int findClosest(Color c){ if (colorTab == null) return -1; int r=c.getRed(); int g=c.getGreen(); int b=c.getBlue(); int minpos=0; int dmin=256 * 256 * 256; int len=colorTab.length; for (int i=0; i < len; ) { int dr=r - (colorTab[i++] & 0xff); int dg=g - (colorTab[i++] & 0xff); int db=b - (colorTab[i] & 0xff); int d=dr * dr + dg * dg + db * db; int index=i / 3; if (usedEntry[index] && (d < dmin)) { dmin=d; minpos=index; } i++; } return minpos; }
Returns index of palette color closest to c
private void writeToFile(StringBuffer sb,String fileName){ try { File out=new File(fileName); Writer fw=new OutputStreamWriter(new FileOutputStream(out,false),"UTF-8"); for (int i=0; i < sb.length(); i++) { char c=sb.charAt(i); if (c == ';' || c == '}') { fw.write(c); if (sb.substring(i + 1).startsWith("//")) { } else { } } else if (c == '{') { fw.write(c); } else fw.write(c); } fw.flush(); fw.close(); float size=out.length(); size/=1024; log.info(out.getAbsolutePath() + " - " + size+ " kB"); } catch ( Exception ex) { log.log(Level.SEVERE,fileName,ex); throw new RuntimeException(ex); } }
Write to file
private Workflow.Method createForgetVolumesMethod(URI vplexSystemURI,List<VolumeInfo> volumeInfo){ return new Workflow.Method(FORGET_VOLUMES_METHOD_NAME,vplexSystemURI,volumeInfo); }
Creates the workflow execute method for forgetting storage volumes.
public boolean hasItem(final String item){ return priceCalculator.hasItem(item); }
Checks whether the NPC deals with the specified item.
public void traverseSubgraphLeftToRight(SalsaNodeVisitor.NodeVisitor nodeVisitor){ int currentEdgeArrayIndex=0; double weightResetToQueryNode=0; for (int i=0; i < numLeftNodesAdded; i++) { long leftNode=subgraphLeftNodes[i]; int degree=subgraphLeftNodeDegree[i]; double weightPerEdge=(double)currentLeftNodes.get(leftNode) / (double)degree; weightResetToQueryNode+=currentLeftNodes.get(leftNode) * salsaRequest.getResetProbability(); for (int j=0; j < degree; j++) { long rightNode=subgraphEdgesArray[currentEdgeArrayIndex]; byte edgeType=subgraphEdgeTypesArray[currentEdgeArrayIndex]; currentEdgeArrayIndex++; int numVisits=visitRightNode(nodeVisitor,leftNode,rightNode,edgeType,weightPerEdge); salsaStats.updateVisitStatsPerRightNode(numVisits); } } salsaStats.addToNumRHSVisits(currentEdgeArrayIndex); resetCurrentLeftNodes(salsaRequest.getQueryNode(),(int)weightResetToQueryNode); }
Traverses the contructed subgraph from left to right
public static boolean hasGingerbread(){ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; }
Checks if the user has at least API level 9
public boolean canHaveInsufficientEnergy(){ return true; }
If this Machine can have the Insufficient Energy Line Problem
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
private List<SubscriptionHistory> loadSubscriptions(BillingDataRetrievalServiceLocal bdr){ if (unitKeys == null) { return bdr.loadSubscriptionsForCustomer(organizationKey,periodStart,periodEnd,-1); } else { return bdr.loadSubscriptionsForCustomer(organizationKey,unitKeys,periodStart,periodEnd,-1); } }
All subscriptions within the start and end period must be loaded. However, a termination or upgrade of a subscription might have been happened before and not yet billed, because the time unit and the billing period are overlapping. So, in order to include those subscription we add a little bit more than one month (a precise starting date is not important, because the billing will filter all non relevant data anyway).
private int rank(Key key,Node x){ if (x == null) return 0; int cmp=key.compareTo(x.key); if (cmp < 0) return rank(key,x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key,x.right); else return size(x.left); }
Returns the number of keys in the subtree less than key.