code
stringlengths
10
174k
nl
stringlengths
3
129k
public void computeLegend(ChartData<?> data){ List<String> labels=new ArrayList<String>(); List<Integer> colors=new ArrayList<Integer>(); for (int i=0; i < data.getDataSetCount(); i++) { DataSet<? extends Entry> dataSet=data.getDataSetByIndex(i); List<Integer> clrs=dataSet.getColors(); int entryCount=dataSet.getEntryCount(); if (dataSet instanceof BarDataSet && ((BarDataSet)dataSet).isStacked()) { BarDataSet bds=(BarDataSet)dataSet; String[] sLabels=bds.getStackLabels(); for (int j=0; j < clrs.size() && j < bds.getStackSize(); j++) { labels.add(sLabels[j % sLabels.length]); colors.add(clrs.get(j)); } colors.add(-2); labels.add(bds.getLabel()); } else if (dataSet instanceof PieDataSet) { List<String> xVals=data.getXVals(); PieDataSet pds=(PieDataSet)dataSet; for (int j=0; j < clrs.size() && j < entryCount && j < xVals.size(); j++) { labels.add(xVals.get(j)); colors.add(clrs.get(j)); } colors.add(-2); labels.add(pds.getLabel()); } else { for (int j=0; j < clrs.size() && j < entryCount; j++) { if (j < clrs.size() - 1 && j < entryCount - 1) { labels.add(null); } else { String label=data.getDataSetByIndex(i).getLabel(); labels.add(label); } colors.add(clrs.get(j)); } } } mLegend.setColors(colors); mLegend.setLabels(labels); Typeface tf=mLegend.getTypeface(); if (tf != null) mLegendLabelPaint.setTypeface(tf); mLegendLabelPaint.setTextSize(mLegend.getTextSize()); mLegendLabelPaint.setColor(mLegend.getTextColor()); mLegend.calculateDimensions(mLegendLabelPaint); }
Prepares the legend and calculates all needed forms, labels and colors.
public void elementAttributesProcessed(String name,Properties extraAttributes,String systemId,int lineNr) throws Exception { this.delegate.elementAttributesProcessed(name,extraAttributes,systemId,lineNr); }
Indicates that an attribute has been added to the current element.
protected boolean hasOutstandingChanges(){ return (textField1.hasChanged() || textField2.hasChanged() || textField3.hasChanged()|| textField4.hasChanged()); }
Does the parameter panel have outstanding changes that have not been used in a query?
public PBEMSetupPanel(final GameSelectorModel model){ m_gameSelectorModel=model; m_diceServerEditor=new SelectAndViewEditor("Dice Server",""); m_forumPosterEditor=new SelectAndViewEditor("Post to Forum","forumPosters.html"); m_emailSenderEditor=new SelectAndViewEditor("Provider","emailSenders.html"); m_webPosterEditor=new SelectAndViewEditor("Send to Website","websiteSenders.html"); createComponents(); layoutComponents(); setupListeners(); if (m_gameSelectorModel.getGameData() != null) { loadAll(); } setWidgetActivation(); }
Creates a new instance
private List<DiffEntry> calculateBranchDiffs(Git git,String targetRef,String reviewRef) throws IOException, GitAPIException { AbstractTreeIterator oldTreeParser=prepareTreeParser(targetRef); AbstractTreeIterator newTreeParser=prepareTreeParser(reviewRef); return git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call(); }
Gets the diff between heads on two branches. See https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowBranchDiff.java.
private void dumpCert(Certificate cert,PrintStream out) throws IOException, CertificateException { if (rfc) { out.println(X509Factory.BEGIN_CERT); out.println(Base64.getMimeEncoder(64,CRLF).encodeToString(cert.getEncoded())); out.println(X509Factory.END_CERT); } else { out.write(cert.getEncoded()); } }
Writes an X.509 certificate in base64 or binary encoding to an output stream.
public static void dumpGraphToFile(File file,StorageGraph graph,boolean outputByteBuffers){ try { FileWriter out=new FileWriter(file); TreeMap<HGPersistentHandle,Object> sorted=new TreeMap<HGPersistentHandle,Object>(); for ( Pair<HGPersistentHandle,Object> p : graph) sorted.put(p.getFirst(),p.getSecond()); for ( HGPersistentHandle h : sorted.keySet()) { out.write(h.toString() + "=["); Object x=sorted.get(h); if (x instanceof HGPersistentHandle[]) { HGPersistentHandle[] link=(HGPersistentHandle[])x; for (int i=0; i < link.length; i++) { out.write(link[i].toString()); if (i < link.length - 1) out.write(","); } } else { byte[] A=(byte[])x; if (outputByteBuffers) { for (int i=0; i < A.length; i++) { out.write(Byte.toString(A[i])); if (i < A.length - 1) out.write(","); } } else { out.write("byte[]"); } } out.write("]\n"); } out.close(); } catch ( Exception ex) { System.err.println(ex); } }
Debugging method: will write the complete StorageGraph in a File where lines are sorted by the graph's key handles.
private void handleRetrofitError(RetrofitError re){ Response r=re.getResponse(); String msg=""; if (r != null) { msg=r.getStatus() + " " + r.getReason(); if (r.getBody() != null && r.getBody().length() > 0) { try { InputStream in=r.getBody().in(); String body=" - " + IOUtils.toString(in,"UTF-8"); in.close(); LOGGER.trace(body); } catch ( IOException e1) { LOGGER.warn("IOException on Trakt error",e1); } } } else { msg=re.getMessage(); } LOGGER.error("Trakt error (wrong settings?) " + msg); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR,msg,"Settings.trakttv")); }
handles the retrofit errors<br> (which is always thrown when http status != 200)<br> and print some error msg
public Shape unwrap(){ return GeometryUtils.getShape(segments,isDouble); }
Creates a new instance of the wrapped class using the data from the wrapper. This is used for deserialization.
private Type _writeOutEmpty(BytecodeContext bc) throws TransformerException { if (ignoredFirstMember && (scope == Scope.SCOPE_LOCAL || scope == Scope.SCOPE_VAR)) return Types.VOID; GeneratorAdapter adapter=bc.getAdapter(); adapter.loadArg(0); Method m; Type t=Types.PAGE_CONTEXT; if (scope == Scope.SCOPE_ARGUMENTS) { getFactory().TRUE().writeOut(bc,MODE_VALUE); m=TypeScope.METHOD_ARGUMENT_BIND; } else if (scope == Scope.SCOPE_LOCAL) { t=Types.PAGE_CONTEXT; getFactory().TRUE().writeOut(bc,MODE_VALUE); m=TypeScope.METHOD_LOCAL_BIND; } else if (scope == Scope.SCOPE_VAR) { t=Types.PAGE_CONTEXT; getFactory().TRUE().writeOut(bc,MODE_VALUE); m=TypeScope.METHOD_VAR_BIND; } else m=TypeScope.METHODS[scope]; TypeScope.invokeScope(adapter,m,t); return m.getReturnType(); }
outputs a empty Variable, only scope Example: pc.formScope();
public static void transformChar(Reader self,Writer writer,@ClosureParams(value=SimpleType.class,options="java.lang.String") Closure closure) throws IOException { int c; try { char[] chars=new char[1]; while ((c=self.read()) != -1) { chars[0]=(char)c; Object o=closure.call(new String(chars)); if (o != null) { writer.write(o.toString()); } } writer.flush(); Writer temp2=writer; writer=null; temp2.close(); Reader temp1=self; self=null; temp1.close(); } finally { closeWithWarning(self); closeWithWarning(writer); } }
Transforms each character from this reader by passing it to the given closure. The Closure should return each transformed character, which will be passed to the Writer. The reader and writer will both be closed before this method returns.
@Override public Object eInvoke(int operationID,EList<?> arguments) throws InvocationTargetException { switch (operationID) { case TypeRefsPackage.TYPE_TYPE_REF___GET_TYPE_REF_AS_STRING: return getTypeRefAsString(); } return super.eInvoke(operationID,arguments); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void addRequestTags(Span span,URI uri,String method){ addRequestTags(span,uri.toString(),uri.getHost(),uri.getPath(),method); }
Adds tags from the HTTP request to the given Span
private Node enq(final Node node){ for (; ; ) { Node t=tail; if (t == null) { if (compareAndSetHead(new Node())) tail=head; } else { node.prev=t; if (compareAndSetTail(t,node)) { t.next=node; return t; } } } }
Inserts node into queue, initializing if necessary. See picture above.
private ResolvedMigration createTestMigration(final MigrationType aMigrationType,final String aVersion,final String aDescription,final String aScript,final Integer aChecksum){ ResolvedMigration migration=new ResolvedMigration(); migration.setVersion(MigrationVersion.fromVersion(aVersion)); migration.setDescription(aDescription); migration.setScript(aScript); migration.setChecksum(aChecksum); migration.setType(aMigrationType); return migration; }
Creates a migration for our tests.
public void show(PopupVPosition vAlign,PopupHPosition hAlign){ this.show(vAlign,hAlign,0,0); }
show the popup according to the specified position
public static Typeface robotoMedium(Context context){ sRobotoMedium=getFontFromRes(R.raw.roboto_medium,context); return sRobotoMedium; }
Roboto-Medium font face
public static double distanceTo2(double x1,double y1,double z1,double x2,double y2,double z2){ final double a=x1 - x2; final double b=y1 - y2; final double c=z1 - z2; return (a * a + b * b + c * c); }
Computes the squared Euclidean length between two points.
public static void main(String unused[]) throws Exception { CertsInFilesystemDirectoryResolver krs=new CertsInFilesystemDirectoryResolver("data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); for (Iterator<Certificate> i=krs.getIterator(); i.hasNext(); ) { X509Certificate cert=(X509Certificate)i.next(); byte[] ski=com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert); System.out.println(); System.out.println("Base64(SKI())= \"" + Base64.encode(ski) + "\""); System.out.println("cert.getSerialNumber()= \"" + cert.getSerialNumber().toString() + "\""); System.out.println("cert.getSubjectX500Principal().getName()= \"" + cert.getSubjectX500Principal().getName() + "\""); System.out.println("cert.getIssuerX500Principal().getName()= \"" + cert.getIssuerX500Principal().getName() + "\""); } }
Method main
public Object extFunction(String ns,String funcName,Vector argVec,Object methodKey,ExpressionContext exprContext) throws javax.xml.transform.TransformerException { Object result=null; if (null != ns) { ExtensionHandler extNS=(ExtensionHandler)m_extensionFunctionNamespaces.get(ns); if (null != extNS) { try { result=extNS.callFunction(funcName,argVec,methodKey,exprContext); } catch ( javax.xml.transform.TransformerException e) { throw e; } catch ( Exception e) { throw new javax.xml.transform.TransformerException(e); } } else { throw new XPathProcessorException(XSLMessages.createMessage(XSLTErrorResources.ER_EXTENSION_FUNC_UNKNOWN,new Object[]{ns,funcName})); } } return result; }
Handle an extension function.
@SuppressWarnings("OverridableMethodCallInConstructor") public IdTagTableAction(String actionName){ super(actionName); if (InstanceManager.getNullableDefault(IdTagManager.class) == null) { setEnabled(false); } }
Create an action with a specific title. <P> Note that the argument is the Action title, not the title of the resulting frame. Perhaps this should be changed?
public byte[] encrypt(InputStream fileInput) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException { Cipher cipher=getCipher(Cipher.ENCRYPT_MODE); return getEncryptInputStream(fileInput,cipher); }
Encryption Method Wrapper
static public int extractApp(U64 cookie){ return (int)((cookie.getValue() >>> APP_ID_SHIFT) & APP_ID_MASK); }
Extract the application id from a flow cookie. Does <em>not</em> check whether the application id is registered
public void removeParamsIfExists(String pName) throws Exception { if ((pName == null) || pName.isEmpty()) { throw new IllegalArgumentException(); } try { XPath xpath=XPathFactory.newInstance().newXPath(); String exprAcsParm=String.format(Messages.exprAcsPName,pName); Element initParam=(Element)xpath.evaluate(exprAcsParm,doc,XPathConstants.NODE); if (initParam != null) initParam.getParentNode().removeChild(initParam); } catch ( Exception ex) { Activator.getDefault().log(ex.getMessage(),ex); throw new Exception(String.format("%s%s",Messages.acsParamErr,ex.getMessage())); } }
This method removes ACS filter attribute if exists.
private MigrationClient(String cacheXmlFileName,String bindAddressName,int serverPort){ this(bindAddressName,serverPort); this.cacheXmlFile=new File(cacheXmlFileName); if (!this.cacheXmlFile.exists()) { System.err.println("Warning - file not found in local directory: '" + cacheXmlFileName + "'"); } }
this is for use by main()
protected void viewRecordField(DDFField poField){ DDFFieldDefinition poFieldDefn=poField.getFieldDefn(); Debug.output(" Field " + poFieldDefn.getName() + ": "+ poFieldDefn.getDescription()); byte[] pachFieldData=poField.getData(); int nBytesRemaining=poField.getDataSize(); for (int iRepeat=0; iRepeat < poField.getRepeatCount(); iRepeat++) { if (iRepeat > 0) { Debug.output("Repeating (" + iRepeat + ")..."); } for (int iSF=0; iSF < poFieldDefn.getSubfieldCount(); iSF++) { DDFSubfieldDefinition poSFDefn=poFieldDefn.getSubfieldDefn(iSF); int nBytesConsumed=viewSubfield(poSFDefn,pachFieldData,nBytesRemaining); nBytesRemaining-=nBytesConsumed; byte[] tempData=new byte[pachFieldData.length - nBytesConsumed]; System.arraycopy(pachFieldData,nBytesConsumed,tempData,0,tempData.length); pachFieldData=tempData; } } }
Dump the contents of a field instance in a record.
public DefaultColorSliderModel(){ setColorSpace(ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_sRGB)); }
Creates a color slider model with an ICC sRGB color space.
public static void waitTillContainerIsStopped(Container container){ while (container.getState() == State.STARTED) { try { Thread.sleep(SLEEP); } catch ( InterruptedException e) { throw new CargoException("Aborting container wait.",e); } } }
Wait indefinitely till the container is stopped.
public FolderDescription(IFolder folder,URI linkLocation){ super(folder); this.name=folder.getName(); this.location=linkLocation; }
Create a FolderDescription from the specified folder handle. If the folder to be created should be linked to a different location, specify the location.
public void loadData(Table t,String query,String keyField,Object lock){ loadData(t,query,keyField,lock,null); }
Asynchronously executes a query and stores the results in the given table instance. All data processing is done in a separate thread of execution.
public SizedInputStream(InputStream is,long len){ source=is; length=len; lenCnt=0; }
Constructs a new sized input stream.
@Transient public boolean existTradeOrderfill(String execId){ for ( TradeOrderfill tradeOrderfill : this.getTradeOrderfills()) { if (tradeOrderfill.getExecId().equals(execId)) { return true; } } return false; }
Method existTradeOrderfill.
@Override protected void initGUI(){ java.util.List<String> classnames; super.initGUI(); m_TabbedPane=new JTabbedPane(); add(m_TabbedPane,BorderLayout.CENTER); m_Tabs.add(new PreprocessTab()); classnames=AbstractExplorerTab.getTabs(); for ( String classname : classnames) { try { AbstractExplorerTab tab=(AbstractExplorerTab)Class.forName(classname).newInstance(); if (tab instanceof PreprocessTab) continue; if (tab instanceof VisualizeTab) continue; if (tab instanceof LogTab) continue; m_Tabs.add(tab); } catch ( Exception e) { System.err.println("Failed to instantiate Explorer tab: " + classname); e.printStackTrace(); } } m_Tabs.add(new VisualizeTab()); m_LogTab=new LogTab(); m_Tabs.add(m_LogTab); for ( AbstractExplorerTab tab : m_Tabs) { tab.setOwner(this); m_TabbedPane.addTab(tab.getTitle(),tab); } m_StatusBar=new StatusBar(); add(m_StatusBar,BorderLayout.SOUTH); }
Initializes the widgets.
public void dropConstraints(DatabaseSession session,JPAMSchemaManager schemaManager,boolean build){ buildConstraints(schemaManager,build); for ( TableDefinition table : getTableDefinitions()) { try { schemaManager.dropConstraints(table); } catch ( DatabaseException exception) { } } }
Drop the table constraints from the database.
public int evaluate(long v1,long v2){ switch (value) { case EQUAL: return (v1 == v2) ? TRUE : FALSE; case NOT_EQUAL: return (v1 != v2) ? TRUE : FALSE; case GREATER: return (v1 > v2) ? TRUE : FALSE; case LESS: return (v1 < v2) ? TRUE : FALSE; case GREATER_EQUAL: return (v1 >= v2) ? TRUE : FALSE; case LESS_EQUAL: return (v1 <= v2) ? TRUE : FALSE; } throw new OptimizingCompilerException("invalid condition " + this); }
Given two longs, evaluate the condition on them.
private String toPathname(final String... pathElements){ if (pathElements != null) { final StringBuilder buffer=new StringBuilder(); for ( String pathElement : pathElements) { buffer.append(File.separator); buffer.append(pathElement); } return buffer.toString(); } return null; }
Gets a fully-qualified path anchored at root. <p/>
protected CompletableFuture<QueryResponse> queryLocal(QueryEntry entry){ CompletableFuture<QueryResponse> future=new CompletableFuture<>(); sequenceQuery(entry,future); return future; }
Performs a local query.
public final void invert(){ invertGeneral(this); }
Inverts this matrix in place.
protected String method() throws ParseException { try { if (debug) dbg_enter("method"); Token[] tokens=this.lexer.peekNextToken(1); Token token=(Token)tokens[0]; if (token.getTokenType() == INVITE || token.getTokenType() == ACK || token.getTokenType() == OPTIONS || token.getTokenType() == BYE || token.getTokenType() == REGISTER || token.getTokenType() == CANCEL || token.getTokenType() == SUBSCRIBE || token.getTokenType() == NOTIFY || token.getTokenType() == PUBLISH || token.getTokenType() == MESSAGE || token.getTokenType() == ID) { lexer.consume(); return token.getTokenValue(); } else { throw createParseException("Invalid Method"); } } finally { if (Debug.debug) dbg_leave("method"); } }
parses a method. Consumes if a valid method has been found.
public void write(OutputStream out,Integer indent,String xmlVersion) throws TransformerException { write(out,new XCalOutputProperties(indent,xmlVersion)); }
Writes the xCal document to an output stream.
public void endClearSend(long startTime,boolean failed){ long duration=getStatTime() - startTime; endClientOpSend(duration,failed); this.sendStats.incInt(clearSendInProgressId,-1); int endClearSendId; if (failed) { endClearSendId=clearSendFailedId; } else { endClearSendId=clearSendId; } this.sendStats.incInt(endClearSendId,1); this.stats.incLong(clearSendDurationId,duration); }
Records that the send part of the clear has completed
public CharSequence readSource(JavaFileObject filename){ try { inputFiles.add(filename); return filename.getCharContent(false); } catch ( IOException e) { log.error("error.reading.file",filename,JavacFileManager.getMessage(e)); return null; } }
Try to open input stream with given name. Report an error if this fails.
public static void indexReferencePoints(Class globalFeatureClass,int numberOfReferencePoints,int lenghtOfPostingList,File inFile,File outFile) throws IOException, IllegalAccessException, InstantiationException { BufferedReader br=new BufferedReader(new FileReader(inFile)); BufferedWriter bw=new BufferedWriter(new FileWriter(outFile)); String line; LinkedList<String> lines=new LinkedList<>(); System.out.println("Reading input file."); while ((line=br.readLine()) != null) { if (!line.startsWith("#")) { if (line.trim().length() > 1) { lines.add(line); } } } br.close(); System.out.printf("Read %,d lines from the input file. Now selecting reference points.\n",lines.size()); Collections.shuffle(lines); GlobalFeature feature=(GlobalFeature)globalFeatureClass.newInstance(); bw.write(feature.getClass().getName() + "\n"); bw.write(numberOfReferencePoints + "," + lenghtOfPostingList+ "\n"); System.out.print("Indexing "); int i=0; for (Iterator<String> iterator=lines.iterator(); iterator.hasNext() && i < numberOfReferencePoints; ) { String file=iterator.next(); try { FileInputStream fis=new FileInputStream(file); feature.extract(ImageIO.read(fis)); fis.close(); bw.write(Base64.encodeBase64String(feature.getByteArrayRepresentation()) + "\n"); i++; if (i % 100 == 0) System.out.print('.'); } catch ( Exception e) { System.out.printf("Having problem \"%s\" with file %s\n",e.getMessage(),file); } } System.out.println(); bw.close(); }
Index reference points for use with a specific feature. A file (infile) containing one image path per line is read and numberOfReferencePoints are randomly selected to serve for indexing and search. The resulting data points plus configuration are read written to a file (outfile).
public TextEditGroup(String name,TextEdit[] edits){ super(); fDescription=name; fEdits=new ArrayList(Arrays.asList(edits)); }
Creates a new text edit group with the given name and array of edits.
@Override public boolean isCommutative(){ return isBinary(); }
can we switch operands (must be binary)
@Override public void publish(LogRecord record){ super.publish(record); super.flush(); }
Logs a record if necessary. A flush operation will be done afterwards.
@Override protected void onStop(){ super.onStop(); LOG.d(TAG,"Stopped the activity."); if (this.appView == null) { return; } this.appView.handleStop(); }
Called when the activity is no longer visible to the user.
public void stop(){ mediaPlayer.stop(); mState=State.STOPPED; notifyPlayerStopped(); }
Stop music streaming
public static boolean shuffle(Object[] objArray,int shuffleCount){ int length; if (objArray == null || shuffleCount < 0 || (length=objArray.length) < shuffleCount) { return false; } for (int i=1; i <= shuffleCount; i++) { int random=getRandom(length - i); Object temp=objArray[length - i]; objArray[length - i]=objArray[random]; objArray[random]=temp; } return true; }
Shuffling algorithm, Randomly permutes the specified array
public void writeTo(OutputStream os) throws IOException { os.write(getEncoded()); }
Writes the key to an output stream
protected void collapse(ResultNode node){ testTreeViewer.collapseToLevel(node,1); }
Collapse given node.
public void hincrByFloat(String key,String field,double doubleValue){ if (isInTransaction()) { transaction.hincrByFloat(key,field,doubleValue); if (keyExpiryTime != -1) { transaction.expire(key,keyExpiryTime); } } else { jedis.hincrByFloat(key,field,doubleValue); if (keyExpiryTime != -1) { jedis.expire(key,keyExpiryTime); } } }
Calls hincrbyfloat on the redis store.
public boolean isOnlySelected(){ return m_onlySelected; }
Returns whether selected nodes search is enabled or disabled.
public void or(Criteria criteria){ oredCriteria.add(criteria); }
This method was generated by MyBatis Generator. This method corresponds to the database table dependency
public Object read(InputNode node,Object value) throws Exception { if (value != null) { throw new PersistenceException("Can not read existing %s for %s",expect,type); } return read(node); }
This <code>read</code> method will extract the text value from the node and replace any template variables before converting it to a primitive value. This uses the <code>Context</code> object used for this instance of serialization to replace all template variables with values from the context filter.
public MalformedURIException(){ super(); }
Constructs a <code>MalformedURIException</code> with no specified detail message.
protected StoragePort queryRegisteredResource(URI id){ ArgValidator.checkUri(id); StoragePort port=_dbClient.queryObject(StoragePort.class,id); ArgValidator.checkEntity(port,id,isIdEmbeddedInURL(id)); if (!RegistrationStatus.REGISTERED.toString().equalsIgnoreCase(port.getRegistrationStatus())) { throw APIException.badRequests.resourceNotRegistered(StoragePort.class.getSimpleName(),id); } return port; }
Gets the storage port with the passed id from the database.
public ConcurrentContextImpl(ConcurrentContextImpl parent){ this.parent=parent; this.threads=parent.threads; }
Inner implementation.
protected void selectTab(Component tab){ Button b=(Button)tab; b.fireClicked(); b.requestFocus(); }
Invoked to select a specific tab, this method should be overriden for subclasses overriding createTab
static final int roundCapacity(int cap){ int n=cap - 1; n|=n >>> 1; n|=n >>> 2; n|=n >>> 4; n|=n >>> 8; n|=n >>> 16; return (n <= 0) ? 1 : (n >= BUFFER_CAPACITY_LIMIT) ? BUFFER_CAPACITY_LIMIT : n + 1; }
Round capacity to power of 2, at most limit.
public static String arrayToString(Object array){ String result; int dimensions; int i; result=""; dimensions=getArrayDimensions(array); if (dimensions == 0) { result="null"; } else if (dimensions == 1) { for (i=0; i < Array.getLength(array); i++) { if (i > 0) result+=","; if (Array.get(array,i) == null) result+="null"; else result+=Array.get(array,i).toString(); } } else { for (i=0; i < Array.getLength(array); i++) { if (i > 0) result+=","; result+="[" + arrayToString(Array.get(array,i)) + "]"; } } return result; }
Returns the given Array in a string representation. Even though the parameter is of type "Object" one can hand over primitve arrays, e.g. int[3] or double[2][4].
public DeclarationExpression(Expression left,Token operation,Expression right){ super(left,operation,right); check(left); }
Creates a DeclarationExpression for Expressions like "def (x, y) = [1, 2]"
public synchronized ZooKeeperClientBuilder zkc(ZooKeeperClient zkc){ this.cachedClient=zkc; return this; }
Build zookeeper client using existing <i>zkc</i> client.
public static void forceDeleteOnExit(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } }
Schedules a file to be deleted when JVM exits. If file is directory delete it and all sub-directories.
private int chooseMaximalExtendedSplitAxis(List<? extends SpatialComparable> objects){ int dimension=objects.get(0).getDimensionality(); double[] maxExtension=new double[dimension]; double[] minExtension=new double[dimension]; Arrays.fill(minExtension,Double.MAX_VALUE); for ( SpatialComparable object : objects) { for (int d=0; d < dimension; d++) { double min, max; min=object.getMin(d); max=object.getMax(d); if (maxExtension[d] < max) { maxExtension[d]=max; } if (minExtension[d] > min) { minExtension[d]=min; } } } int splitAxis=-1; double max=0; for (int d=0; d < dimension; d++) { double currentExtension=maxExtension[d] - minExtension[d]; if (max < currentExtension) { max=currentExtension; splitAxis=d; } } return splitAxis; }
Computes and returns the best split axis. The best split axis is the split axes with the maximal extension.
public void testCreateConfigurationWithPropertiesFile() throws Exception { Configuration configurationElement=new Configuration(); configurationElement.setImplementation(StandaloneLocalConfigurationStub.class.getName()); Map<String,String> properties=new HashMap<String,String>(); properties.put("someName1","someValue1"); configurationElement.setProperties(properties); org.codehaus.cargo.container.configuration.Configuration configuration; File propertiesFile=File.createTempFile(ConfigurationTest.class.getName(),".properties"); try { OutputStream outputStream=new FileOutputStream(propertiesFile); try { Properties fileProperties=new Properties(); fileProperties.put("someName1","foobar"); fileProperties.put("someName2","someValue2"); fileProperties.store(outputStream,null); } finally { outputStream.close(); } configurationElement.setPropertiesFile(propertiesFile); configuration=configurationElement.createConfiguration("testcontainer",ContainerType.INSTALLED,null,new CargoProject(null,null,null,null,null,Collections.<Artifact>emptySet(),null)); } finally { propertiesFile.delete(); } assertEquals("someValue1",configuration.getPropertyValue("someName1")); assertEquals("someValue2",configuration.getPropertyValue("someName2")); }
Test property file based configuration elements which override static counterparts
public QualityQuery[] readQueries(BufferedReader reader) throws IOException { ArrayList<QualityQuery> res=new ArrayList<>(); String line; try { while (null != (line=reader.readLine())) { line=line.trim(); if (line.startsWith("#")) { continue; } int k=line.indexOf(":"); String id=line.substring(0,k).trim(); String qtext=line.substring(k + 1).trim(); HashMap<String,String> fields=new HashMap<>(); fields.put(name,qtext); QualityQuery topic=new QualityQuery(id,fields); res.add(topic); } } finally { reader.close(); } QualityQuery qq[]=res.toArray(new QualityQuery[0]); Arrays.sort(qq); return qq; }
Read quality queries from trec 1MQ format topics file.
int size(BinarySearchTreeNode<E> node){ if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 1 + this.size(node.left) + this.size(node.right); }
Returns the number of elements in the subtree.
public String permission(){ return permission; }
Returns permission.
public double orElseGet(DoubleSupplier supplier){ return isPresent ? value : supplier.getAsDouble(); }
If a value is present, returns the value, otherwise returns the result produced by the supplying function.
public static int inchAsPixel(double in,Component component){ return in == 0d ? 0 : getUnitConverter().inchAsPixel(in,component); }
Converts Inches and returns pixels using the specified resolution.
private int calculateLeftSeconds(){ return maxProgress - currentProgress; }
Calculate left seconds
public void catchException(final Label start,final Label end,final Type exception){ Label doCatch=new Label(); if (exception == null) { mv.visitTryCatchBlock(start,end,doCatch,null); } else { mv.visitTryCatchBlock(start,end,doCatch,exception.getInternalName()); } mark(doCatch); }
Marks the start of an exception handler.
@Nullable @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){ View rootView=inflater.inflate(R.layout.activity_select_category,container,false); mRecyclerView=(RecyclerView)rootView.findViewById(R.id.recyclerView); float cardWidth=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,300.f,getResources().getDisplayMetrics()); boolean isLandscape=getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; int spans=(int)Math.floor(getResources().getDisplayMetrics().widthPixels / cardWidth); int orientation=isLandscape ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.VERTICAL; StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(spans,orientation); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(new CategoryAdapter(mCategories,mDueChallengeCounts,this)); mRecyclerView.setHasFixedSize(true); return rootView; }
This method is called to create th fragment view
public SipTransactionContext sendSipMessage(SipMessage message,SipTransactionContext.INotifySipProvisionalResponse callback) throws NetworkException, PayloadException { return mSipInterface.sendSipMessageAndWait(message,callback); }
Send a SIP message and create a context to wait a response
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public ShowWorkspaceUpdaterDialog(final SimbrainDesktop desktop){ super("Edit Update Sequence..."); if (desktop == null) { throw new IllegalArgumentException("desktop must not be null"); } putValue(SMALL_ICON,ResourceManager.getImageIcon("Sequence.png")); this.desktop=desktop; }
Construct the show dialog action.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public static <T>ReactiveSeq<T> reactiveSeq(Observable<T> observable){ return ReactiveSeq.fromPublisher(publisher(observable)); }
Convert an Observable to a cyclops-react ReactiveSeq
void addFillComponents(Container panel,int[] cols,int[] rows){ Dimension filler=new Dimension(10,10); boolean filled_cell_11=false; CellConstraints cc=new CellConstraints(); if (cols.length > 0 && rows.length > 0) { if (cols[0] == 1 && rows[0] == 1) { panel.add(Box.createRigidArea(filler),cc.xy(1,1)); filled_cell_11=true; } } for (int index=0; index < cols.length; index++) { if (cols[index] == 1 && filled_cell_11) { continue; } panel.add(Box.createRigidArea(filler),cc.xy(cols[index],1)); } for (int index=0; index < rows.length; index++) { if (rows[index] == 1 && filled_cell_11) { continue; } panel.add(Box.createRigidArea(filler),cc.xy(1,rows[index])); } }
Adds fill components to empty cells in the first row and first column of the grid. This ensures that the grid spacing will be the same as shown in the designer.
protected boolean checkExtModuleOnDelete(final ExtModManifestBean manifest){ return true; }
Checks if the installed external module specified by its manifest can be deleted. <p> This implementation always returns <code>true</code>, it is intended to provide customization for subclasses. </p>
public void schedule(TimerTask task,long delay){ timer.schedule(new TimerTaskWrapper(task),delay); }
Schedules the specified task for execution after the specified delay.
static StringBuilder newStringBuilderForCollection(int size){ checkNonnegative(size,"size"); return new StringBuilder((int)Math.min(size * 8L,Ints.MAX_POWER_OF_TWO)); }
Returns best-effort-sized StringBuilder based on the given collection size.
public Asin(){ super("asin",1); }
The Arcsine value of a single parameter.
public Geo offset(double distance,double azimuth,Geo ret){ Geo m=this.crossNormalize(north,ret); Geo p=Rotation.rotate(m,distance,this,ret); return Rotation.rotate(this,2.0 * Math.PI - azimuth,p,ret); }
Returns a Geo that is distance (radians), and azimuth (radians) away from this. This is undefined at the north pole, at which point "azimuth" is undefined.
public void textValueChanged(TextEvent textEvent){ Integer cpos=Integer.valueOf(TextComponent.this.getCaretPosition()); firePropertyChange(ACCESSIBLE_TEXT_PROPERTY,null,cpos); }
TextListener notification of a text value change.
@Override public boolean swipe(int startX,int startY,int endX,int endY,int steps){ return device.swipe(startX,startY,endX,endY,steps); }
Performs a swipe from one coordinate to another using the number of steps to determine smoothness and speed. Each step execution is throttled to 5ms per step. So for a 100 steps, the swipe will take about 1/2 second to complete.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:00.768 -0500",hash_original_method="8E799345410D5A9E18D25167F32F6404",hash_generated_method="5E5CABB43821B92D3373B636ACA540B2") @DSVerified @DSSafe(DSCat.SAFE_OTHERS) public String toString(){ StringBuffer buffer=new StringBuffer(); Enumeration hosts; buffer.append('<'); hosts=_path.elements(); if (hosts.hasMoreElements()) { buffer.append('@'); buffer.append((String)hosts.nextElement()); while (hosts.hasMoreElements()) { buffer.append(",@"); buffer.append((String)hosts.nextElement()); } buffer.append(':'); } buffer.append(_emailAddress); buffer.append('>'); return buffer.toString(); }
Return the properly formatted string representation of the relay path. <p>
public void initialise() throws Exception { initialise(k,tau,((MutualInfoCalculatorMultiVariateKernel)miCalc).getKernelWidth()); }
Initialises the calculator with the existing values for embedding length k, embedding delay tau and kernel width epsilon
public DateTime toDateTime(Chronology chronology){ return new DateTime(getMillis(),chronology); }
Get this object as a DateTime using the given chronology and its zone.
public boolean isUnderflow(){ return estimateEnum == EstimateEnum.Underflow; }
Return <code>true</code> iff this sample has cardinality underflow (the sample is empty). Cardinality underflow occurs when the sampling process was unable to find any solutions. Underflow is typically addressed by increasing the sample size, but sometimes underflow indicates that an access path (if it has filters) or a join may not have any solutions in the data.
public void read(byte[] b,int off,int len,long pos) throws IOException { if (b == null) { throw new NullPointerException("b == null!"); } if ((off < 0) || (len < 0) || (pos < 0)|| (off + len > b.length)|| (off + len < 0)) { throw new IndexOutOfBoundsException(); } if (pos + len > length) { throw new IndexOutOfBoundsException(); } long index=pos / BUFFER_LENGTH; int offset=(int)pos % BUFFER_LENGTH; while (len > 0) { int nbytes=Math.min(len,BUFFER_LENGTH - offset); byte[] buf=getCacheBlock(index++); System.arraycopy(buf,offset,b,off,nbytes); len-=nbytes; off+=nbytes; offset=0; } }
Copy <code>len</code> bytes from the cache, starting at cache position <code>pos</code>, into the array <code>b</code> at offset <code>off</code>.
public IntArray(int[] data){ this.data=data; size=data.length; }
Create an int array with the given values and size.
public static double cosineFormulaDeg(double lat1,double lon1,double lat2,double lon2){ return cosineFormulaRad(MathUtil.deg2rad(lat1),MathUtil.deg2rad(lon1),MathUtil.deg2rad(lat2),MathUtil.deg2rad(lon2)); }
Compute the approximate great-circle distance of two points using the Haversine formula Complexity: 6 (2 of which emulated) trigonometric functions. Reference: <p> R. W. Sinnott,<br/> Virtues of the Haversine<br /> Sky and telescope, 68-2, 1984 </p>
private void correctTooLow(int childCount){ if (mFirstPosition == 0 && childCount > 0) { final int firstTop=getHighestChildTop(); final int start=getListPaddingTop(); final int end=(getTop() - getBottom()) - getListPaddingBottom(); int topOffset=firstTop - start; final int lastBottom=getLowestChildBottom(); int lastPosition=mFirstPosition + childCount - 1; if (topOffset > 0) { if (lastPosition < mItemCount - 1 || lastBottom > end) { if (lastPosition == mItemCount - 1) { topOffset=Math.min(topOffset,lastBottom - end); } offsetChildrenTopAndBottom(-topOffset); if (lastPosition < mItemCount - 1) { int nextPosition=lastPosition + 1; fillDown(nextPosition,getNextChildDownsTop(nextPosition)); adjustViewsUpOrDown(); } } else if (lastPosition == mItemCount - 1) { adjustViewsUpOrDown(); } } } }
Check if we have dragged the bottom of the list too low (we have pushed the bottom element off the bottom of the screen when we did not need to). Correct by sliding everything back up.
public void registerAboveContentView(View v,LayoutParams params){ if (!mBroadcasting) mViewAbove=v; }
Register the above content view.
boolean deleteSnapshot(String snapshotName){ NaElement elem=new NaElement("snapshot-delete"); elem.addNewChild("volume",name); elem.addNewChild("snapshot",snapshotName); try { server.invokeElem(elem); } catch ( Exception e) { String msg="Failed to delete snapshot: " + snapshotName; log.error(msg,e); throw new NetAppCException(msg,e); } return true; }
Deletes a snapshot given the snapshot name.
public boolean isFinal(){ return Modifier.isFinal(_class.getModifiers()); }
Returns true for a final class
protected void bringActivityToForeground(){ Intent newIntent=Tab.createBringTabToFrontIntent(ChromeTab.this.getId()); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(newIntent); }
Brings chrome's Activity to foreground, if it is not so.
protected void updateNumericScores(double[] predicted,double[] actual,double weight){ double diff; double sumErr=0, sumAbsErr=0, sumSqrErr=0; double sumPriorAbsErr=0, sumPriorSqrErr=0; for (int i=0; i < m_NumClasses; i++) { diff=predicted[i] - actual[i]; sumErr+=diff; sumAbsErr+=Math.abs(diff); sumSqrErr+=diff * diff; diff=(m_ClassPriors[i] / m_ClassPriorsSum) - actual[i]; sumPriorAbsErr+=Math.abs(diff); sumPriorSqrErr+=diff * diff; } m_SumErr+=weight * sumErr / m_NumClasses; m_SumAbsErr+=weight * sumAbsErr / m_NumClasses; m_SumSqrErr+=weight * sumSqrErr / m_NumClasses; m_SumPriorAbsErr+=weight * sumPriorAbsErr / m_NumClasses; m_SumPriorSqrErr+=weight * sumPriorSqrErr / m_NumClasses; }
Update the numeric accuracy measures. For numeric classes, the accuracy is between the actual and predicted class values. For nominal classes, the accuracy is between the actual and predicted class probabilities.