code
stringlengths
10
174k
nl
stringlengths
3
129k
public void testBoundedLongs(){ AtomicInteger fails=new AtomicInteger(0); SplittableRandom r=new SplittableRandom(); long size=123L; for (long least=-86028121; least < MAX_LONG_BOUND; least+=1982451653L) { for (long bound=least + 2; bound > least && bound < MAX_LONG_BOUND; bound+=Math.abs(bound * 7919)) { final long lo=least, hi=bound; r.longs(size,lo,hi).parallel().forEach(null); } } assertEquals(fails.get(),0); }
Each of a parallel sized stream of bounded longs is within bounds
public void fireLayer(int type,Layer[] layers){ if (logger.isLoggable(Level.FINE)) { logger.fine("calling setLayers on " + size() + " objects"); } if (isEmpty()) return; LayerEvent evt=new LayerEvent(source,type,layers); for ( LayerListener listener : this) { listener.setLayers(evt); } }
Send a layer event to all registered listeners.
public SVGOMMetadataElement(String prefix,AbstractDocument owner){ super(prefix,owner); }
Creates a new SVGOMMetadataElement object.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static PnSignalingParams defaultInstance(){ MediaConstraints pcConstraints=PnSignalingParams.defaultPcConstraints(); MediaConstraints videoConstraints=PnSignalingParams.defaultVideoConstraints(); MediaConstraints audioConstraints=PnSignalingParams.defaultAudioConstraints(); List<PeerConnection.IceServer> iceServers=PnSignalingParams.defaultIceServers(); return new PnSignalingParams(iceServers,pcConstraints,videoConstraints,audioConstraints); }
The default parameters for media constraints. Might have to tweak in future.
private GF2Polynomial lower(int k){ GF2Polynomial result=new GF2Polynomial(k << 5); System.arraycopy(value,0,result.value,0,Math.min(k,blocks)); return result; }
Returns a new GF2Polynomial containing the lower <i>k</i> bytes of this GF2Polynomial.
public boolean isEmpty(){ return empty; }
Checks whether the statement is still empty.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public boolean equals(Object other){ if (this == other) { return true; } if (!(other instanceof EllipticCurve)) { return false; } EllipticCurve otherEc=(EllipticCurve)other; return this.field.equals(otherEc.field) && this.a.equals(otherEc.a) && this.b.equals(otherEc.b)&& Arrays.equals(this.seed,otherEc.seed); }
Returns whether the specified object equals to this elliptic curve.
@Override public void accumulate(Object value){ this.distinct.addAll((Set)value); }
The input data is the Set of values(distinct) receieved from each of the bucket nodes.
public OnlineLDAsvi(int K,int D,int W){ setK(K); setD(D); setVocabSize(W); }
Creates a new Online LDA learner that is ready for online updates
public double computeLogLiGradient(double[] lambda,double[] gradLogLi,int numIter,PrintWriter fout){ double logLi=0.0; int ii, i; for (i=0; i < numFeatures; i++) { gradLogLi[i]=-1 * lambda[i] / model.option.sigmaSquare; logLi-=(lambda[i] * lambda[i]) / (2 * model.option.sigmaSquare); } for (ii=0; ii < model.data.trnData.size(); ii++) { Observation obsr=(Observation)model.data.trnData.get(ii); for (i=0; i < numLabels; i++) { temp[i]=0.0; } double obsrLogLi=0.0; model.feaGen.startScanFeatures(obsr); while (model.feaGen.hasNextFeature()) { Feature f=model.feaGen.nextFeature(); if (f.label == obsr.humanLabel) { gradLogLi[f.idx]+=f.val; obsrLogLi+=lambda[f.idx] * f.val; } temp[f.label]+=lambda[f.idx] * f.val; } double Zx=0.0; for (i=0; i < numLabels; i++) { Zx+=Math.exp(temp[i]); } model.feaGen.scanReset(); while (model.feaGen.hasNextFeature()) { Feature f=model.feaGen.nextFeature(); gradLogLi[f.idx]-=f.val * Math.exp(temp[f.label]) / Zx; } obsrLogLi-=Math.log(Zx); logLi+=obsrLogLi; } System.out.println(); System.out.println("Iteration: " + Integer.toString(numIter)); System.out.println("\tLog-likelihood = " + Double.toString(logLi)); double gradLogLiNorm=Train.norm(gradLogLi); System.out.println("\tNorm (log-likelihood gradient) = " + Double.toString(gradLogLiNorm)); double lambdaNorm=Train.norm(lambda); System.out.println("\tNorm (lambda) = " + Double.toString(lambdaNorm)); if (model.option.isLogging) { fout.println(); fout.println("Iteration: " + Integer.toString(numIter)); fout.println("\tLog-likelihood = " + Double.toString(logLi)); fout.println("\tNorm (log-likelihood gradient) = " + Double.toString(gradLogLiNorm)); fout.println("\tNorm (lambda) = " + Double.toString(lambdaNorm)); } return logLi; }
Compute log li gradient.
public String toString(){ int iMax=length() - 1; if (iMax == -1) { return "[]"; } StringBuilder b=new StringBuilder((17 + 2) * (iMax + 1)); b.append('['); for (int i=0; ; i++) { b.append(longBitsToDouble(longs.get(i))); if (i == iMax) { return b.append(']').toString(); } b.append(',').append(' '); } }
Returns the String representation of the current values of array.
@DSSink({DSSinkKind.FILE}) @DSSpec(DSCat.IO) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:52.209 -0400",hash_original_method="4007BD37B56F652F2DD863D7816336D0",hash_generated_method="2024B0D60D55840B17528B87EB493ED5") @Override public void write(char[] chr,int st,int end) throws IOException { out.write(chr,st,end); }
Write the specified characters from an array.
public static Map<String,Double> calculate(CombinedSmallContingencyTable cSCTable,int numberOfSmallContingencyTables,boolean softEvaluation){ double tp=cSCTable.getTruePositives(); double fp=cSCTable.getFalsePositives(); double fn=cSCTable.getFalseNegatives(); double tn=cSCTable.getTrueNegatives(); Double accuracy=0.0; double n=(Double)(tp + fp + fn+ tn) / numberOfSmallContingencyTables; if (n != 0.0) { accuracy=(Double)tp / n; } else if (!softEvaluation) { accuracy=Double.NaN; } Map<String,Double> results=new HashMap<String,Double>(); results.put(Accuracy.class.getSimpleName(),accuracy); return results; }
take just true positives of each class: diagonal of the large confusion matrix and divide it by the total number of instances in the large confusion matrix
public void connect(final BluetoothDevice device){ if (mConnected) return; synchronized (mLock) { if (mBluetoothGatt != null) { mBluetoothGatt.close(); mBluetoothGatt=null; } else { mContext.registerReceiver(mBluetoothStateBroadcastReceiver,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); mContext.registerReceiver(mBondingBroadcastReceiver,new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); } } final boolean autoConnect=shouldAutoConnect(); mUserDisconnected=!autoConnect; mBluetoothDevice=device; mConnectionState=BluetoothGatt.STATE_CONNECTING; mBluetoothGatt=device.connectGatt(mContext,autoConnect,mGattCallback=new BleManagerGattCallback()); }
Connects to the Bluetooth Smart device.
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:25.371 -0500",hash_original_method="8603CA8C8DA2F2A8742D0D3D57F85A73",hash_generated_method="8603CA8C8DA2F2A8742D0D3D57F85A73") Values(){ initializeTable(INITIAL_SIZE); this.size=0; this.tombstones=0; }
Constructs a new, empty instance.
public FtHttpResumeDownload(Uri downloadServerAddress,Uri file,Uri fileIcon,MmContent content,ContactId contact,String chatId,String filetransferId,boolean isGroup,long timestamp,long timestampSent,long fileExpiration,long iconExpiration,boolean accepted,String remoteSipInstance){ super(Direction.INCOMING,file,content.getName(),content.getEncoding(),content.getSize(),fileIcon,contact,chatId,filetransferId,isGroup,timestamp,timestampSent); mServerAddress=downloadServerAddress; mFileExpiration=fileExpiration; mIconExpiration=iconExpiration; mAccepted=accepted; mRemoteSipInstance=remoteSipInstance; if (downloadServerAddress == null || filetransferId == null) throw new IllegalArgumentException("Invalid argument"); }
Creates a FT HTTP resume download data object
public boolean isInitialized(){ return getNative().isInitialized(); }
Check whether this module has been initialized.
public UserDTO(){ super(); }
Instantiates a new user dto.
public boolean belongs(IPackageFragment fragment){ if (fragment == null) return false; if (fJavaProject.equals(fragment.getJavaProject())) { return fName.equals(fragment.getElementName()); } return false; }
Returns true if the given fragment has the same name and resides inside the same project as the other fragments in the LogicalPackage.
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 List<PoiType> loadPoiTypesFromStream(InputStreamReader inputStreamReader){ try { H2GeoDto h2GeoDto=gson.fromJson(inputStreamReader,H2GeoDto.class); sharedPreferences.edit().putString(application.getString(R.string.shared_prefs_h2geo_version),h2GeoDto.getVersion()).putString(application.getString(R.string.shared_prefs_h2geo_date),h2GeoDto.getLastUpdate()).apply(); return loadPoiTypesFromH2GeoDto(h2GeoDto); } catch ( Exception e) { Timber.e(e,"Error while loading POI Types from assets"); throw new RuntimeException(e); } finally { CloseableUtils.closeQuietly(inputStreamReader); } }
Load the PoiTypes from the poitypes.json file located in the assets directory.
public SelectionInputDialog(Window owner,String key,T[] selectionValues,T initialSelectionValue,Object... keyArguments){ this(owner,key,selectionValues,initialSelectionValue,null,keyArguments); }
Create a SelectionInputDIalog.
private void zzDoEOF(){ if (!zzEOFDone) { zzEOFDone=true; } }
Contains user EOF-code, which will be executed exactly once, when the end of file is reached
private String validateInputs(){ if (jarRadio.getSelection()) { File f=new File(jarPath.getText()); if (!f.exists()) { return "Jar file doesn't exists"; } if (!f.canRead()) { return "Can't read Jar file directory"; } } else { File f=new File(dirPath.getText()); if (!f.exists()) { return "Base Path directory doesn't exists"; } if (!f.canRead()) { return "Can't read Base Path directory"; } } return null; }
Determine if the current set of analysis inputs are valid. If not, provide an error message that describes the problem.
private void addSynapseGroupBidirectional(SynapseGroup sg1,SynapseGroup sg2){ SynapseGroupNodeBidirectional synGBD=SynapseGroupNodeBidirectional.createBidirectionalSynapseGN(this,sg1,sg2); canvas.getLayer().addChild(synGBD); objectNodeMap.put(sg1,synGBD); objectNodeMap.put(sg2,synGBD); NeuronGroupNode srcNode=(NeuronGroupNode)objectNodeMap.get(sg1.getSourceNeuronGroup()); if (srcNode != null) { srcNode.addPropertyChangeListener(PNode.PROPERTY_FULL_BOUNDS,synGBD); } NeuronGroupNode tarNode=(NeuronGroupNode)objectNodeMap.get(sg1.getTargetNeuronGroup()); if (tarNode != null) { tarNode.addPropertyChangeListener(PNode.PROPERTY_FULL_BOUNDS,synGBD); } }
Add a bidirectional synapse group representation. This is not logically different than two simple synapse groups, but the case is represented by a different PNode object.
public static boolean validateTypeSize(final JTextField size){ try { if (size.getText().isEmpty() || Integer.parseInt(size.getText()) < 0) { return false; } } catch ( final NumberFormatException exception) { return false; } return true; }
Only validate the type size without showing an error message.
public static XMLObjectWriter newInstance(OutputStream out) throws XMLStreamException { XMLObjectWriter writer=new XMLObjectWriter(); writer.setOutput(out); return writer; }
Returns a XML object writer (potentially recycled) having the specified output stream as output.
public static ToleratedUpdateError parseMetadataIfToleratedUpdateError(String metadataKey,String metadataVal){ if (!metadataKey.startsWith(META_PRE)) { return null; } final int typeEnd=metadataKey.indexOf(':',META_PRE_LEN); if (typeEnd < 0) { return null; } return new ToleratedUpdateError(CmdType.valueOf(metadataKey.substring(META_PRE_LEN,typeEnd)),metadataKey.substring(typeEnd + 1),metadataVal); }
returns a ToleratedUpdateError instance if this metadataKey is one we care about, else null
protected boolean startsWithOpenBracket(Word w){ return w.form.startsWith("(") || w.form.startsWith("{") || w.form.startsWith("[")|| w.form.startsWith("-LBR-"); }
Determines whether the argument starts with any of the following varieties of open bracket: ( { [ -LBR- .
protected TypeHierarchy createTypeHierarchy(){ return new DefaultTypeHierarchy(checker,getQualifierHierarchy(),checker.getOption("ignoreRawTypeArguments","true").equals("true"),checker.hasOption("invariantArrays")); }
Creates the type subtyping checker using the current type qualifier hierarchy. <p> Subclasses may override this method to specify new type-checking rules beyond the typical java subtyping rules.
public void buildPathPart(Appendable buffer,String url) throws WebAppConfigurationException, IOException { if (servletPath == null) { throw new IllegalStateException("Servlet path is unknown"); } buffer.append(servletPath); if (!url.startsWith("/")) { buffer.append("/"); } buffer.append(url); }
Builds a partial URL - including the servlet path and resource, but not the scheme or host.
private void resetSourceParameters(){ resetVendor(s_isSource,null); resetHost(s_isSource,null); resetPort(s_isSource,null); resetUser(s_isSource,null); resetPassword(s_isSource,null); resetSystemUser(s_isSource,null); resetSystemPassword(s_isSource,null); resetSystemUserStatus(s_isSource); resetName(s_isSource,null); resetURL(s_isSource,null); resetCatalog(s_isSource,null); resetSchema(s_isSource,null); resetVersion(s_isSource); }
reset source parameter fields from application parameters
@After public void tearDown(){ test=null; }
Removes references to shared objects so they can be garbage collected.
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 void removeSubdirectory(String directory){ LinkedList<String> entriesToRemove=new LinkedList<String>(); for ( Entry<String,JarEntry> JarEntry : jarEntries.entrySet()) { if (JarEntry.getKey().startsWith(directory)) { entriesToRemove.add(JarEntry.getKey()); } } for ( String entryToRemove : entriesToRemove) { jarEntries.remove(entryToRemove); } }
Removes any entries with the matching file name prefix
public void refreshOwner(){ if (model.isNoSubscriptionOwner()) { User owner=model.getSelectedOwner(); if (owner != null) { owner.setOwnerSelected(false); } model.setSelectedOwner(null); } else { model.setSelectedOwner(model.getStoredOwner()); } refreshSelectedOwnerName(model.getSelectedOwner()); }
Refresh subscription owner when radio is clicked
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:44.079 -0500",hash_original_method="3CB53268EE03367F93FB62614B11BBE8",hash_generated_method="62695132D3996D94203F0867318C9D15") public boolean canContain(ElementType other){ return (theModel & other.theMemberOf) != 0; }
Returns true if this element type can contain another element type. That is, if any of the models in this element's model vector match any of the models in the other element type's member-of vector.
private void centerBitmap(){ RectF rect=new RectF(0,0,imageW,imageH); matrix.mapRect(rect); float height=rect.height(); float width=rect.width(); float deltaX=0, deltaY=0; deltaX=(viewW - width - leftMargins * 2) / 2; deltaY=-(viewH - height - topBottomMargins) / 2; matrix.postTranslate(deltaX,deltaY); }
make the image bitmap center
private void updateParentContainerStructureFrom(CollectionElementVariable2 elemVar,ConstraintVariable2 v1){ ConstraintVariable2 elemContainer=elemVar.getParentConstraintVariable(); ParametricStructure elemContainerStructure=elemStructure(elemContainer); if (elemContainerStructure == ParametricStructure.NONE) return; if (elemContainerStructure == null) { elemContainerStructure=newParametricType(elemContainer.getType()); setStructureAndPush(elemContainer,elemContainerStructure); } ParametricStructure v1Structure=elemStructure(v1); int parmIdx=elemVar.getDeclarationTypeVariableIndex(); if (parmIdx == CollectionElementVariable2.NOT_DECLARED_TYPE_VARIABLE_INDEX) return; if (elemContainerStructure == v1Structure || containsSubStructure(v1Structure,elemContainerStructure)) { if (!(elemStructure(elemVar) == ParametricStructure.NONE)) setStructureAndPush(elemVar,ParametricStructure.NONE); if (elemContainerStructure.getParameters()[parmIdx] == null) { elemContainerStructure.getParameters()[parmIdx]=ParametricStructure.NONE; fWorkList2.push(elemContainer); } } else if (updateStructureOfIthParamFrom(elemContainerStructure,parmIdx,v1Structure)) { setStructureAndPush(elemVar,elemContainerStructure.getParameters()[parmIdx]); fWorkList2.push(elemContainer); if (DEBUG_INITIALIZATION) System.out.println(" updated structure of " + elemContainer + " to "+ elemContainerStructure); } }
Updates the structure of the parent container variable of the given CollectionElementVariable2 from the structure of 'v1'.
public void showMessage(String title,String message,T data){ Notification n=new Notification(title,message,listener,expireTime); n.setHideMethod(hideMethod); n.setFallbackTimeout(maxDisplayTime); n.setActivityTime(activityTime); if (displayed.size() < maxItems) { showNotification(n); } else { queue.add(n); checkQueueSize(); } notificationData.put(n,data); }
Create a notification with the given message and either show or queue it.
public static Vector<?> create(Vector<String> markerNames,String prefix,Properties properties,ProgressSupport progressSupport,boolean matchInOutVectorSize){ return getInstance()._create(markerNames,prefix,properties,progressSupport,matchInOutVectorSize); }
Given a Vector of marker name Strings, and a Properties object, look in the Properties object for the markerName.class property to get a class name to create each object. Then, if the new objects are PropertyConsumers, use the marker name as a property prefix to get properties for that object out of the Properties.
@Deprecated public JPASubscription(){ }
Used by JPA
public FastAdapterBottomSheetDialog<Item> add(int position,Item item){ mFastItemAdapter.add(position,item); return this; }
add an item at the given position within the existing icons
private void updateProgress(int progress){ if (myHost != null) { myHost.updateProgress(progress); } else { System.out.println("Progress: " + progress + "%"); } }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static double normalCdf(double x,double mu,double sigma) throws Exception { if (sigma < 0) { throw new Exception("Standard deviation cannot be < 0"); } double erfArg=(x - mu) / Math.sqrt(2.0 * sigma * sigma); double cdf=0.5 * (1 + erf(erfArg)); return cdf; }
Compute the cumulative density function (CDF) of an observation x, given the mean mu, and the standard deviation sigma, given that the observations follow a univariate normal distribution.
public synchronized boolean remove(Node obj){ ArrayList<Node> newList=new ArrayList<Node>(this.list); boolean ret=newList.remove(obj); if (ret) { this.list=Collections.unmodifiableList(newList); incrementVersion(); } return ret; }
Removes obj from the list. Removal is done by making a copy of the existing list and then removing the obj from the new list. If the object was removed, the list is assigning to the new unmodifiable list. This is to ensure that the iterator of the list doesn't get ConcurrentModificationException.
static public Locator southWest(boolean isTransform){ return new RelativeLocator(0.0,1.0,isTransform); }
South West.
public ValidationInfo(@NotNull String message){ this(message,null); }
Creates a validation error message not associated with a specific component.
public void removeScrollingListener(OnWheelScrollListener listener){ scrollingListeners.remove(listener); }
Removes wheel scrolling listener
public void removeStatementEventListener(StatementEventListener listener){ synchronized (this.statementEventListeners) { this.statementEventListeners.remove(listener); } }
Removes the specified <code>StatementEventListener</code> from the list of components that will be notified when the driver detects that a <code>PreparedStatement</code> has been closed or is invalid.
public void reply(CanReply m){ }
Don't pay attention to replies
public DeletionConstraintException(String message,DeletionConstraintExceptionBean bean,Throwable cause){ super(message,bean,cause); this.bean=bean; }
Constructs a new exception with the specified detail message, cause, and bean for JAX-WS exception serialization.
@Override public void respond(String response){ getChannel().send().message(getUser(),response); }
Respond with a channel message in <code>user: message</code> format to the <i>user that preformed the kick</i>
public static void disableTotalKeySizeTracking(){ factory.disableTotalKeySizeTracking(); }
Call this method if you want to disable key size tracking.
public BogusRegExLiteralException(String message,INode node,String value){ super(message,node,value,null); }
Create a new exception for the given node with the recovered value.
public int hashCode(){ return name.hashCode(); }
Computes the hash code for this principal.
public Color mixColors(final Color... colors){ int totalRed=this.getRed(); int totalGreen=this.getGreen(); int totalBlue=this.getBlue(); int totalMax=Math.max(Math.max(totalRed,totalGreen),totalBlue); for ( final Color color : colors) { totalRed+=color.getRed(); totalGreen+=color.getGreen(); totalBlue+=color.getBlue(); totalMax+=Math.max(Math.max(color.getRed(),color.getGreen()),color.getBlue()); } final float averageRed=totalRed / (colors.length + 1); final float averageGreen=totalGreen / (colors.length + 1); final float averageBlue=totalBlue / (colors.length + 1); final float averageMax=totalMax / (colors.length + 1); final float maximumOfAverages=Math.max(Math.max(averageRed,averageGreen),averageBlue); final float gainFactor=averageMax / maximumOfAverages; return Color.fromRGB((int)(averageRed * gainFactor),(int)(averageGreen * gainFactor),(int)(averageBlue * gainFactor)); }
Creates a new color with its RGB components changed as if it was dyed with the colors passed in, replicating vanilla workbench dyeing (average colors of all arguments)
public PrintfFormat(String fmtArg) throws IllegalArgumentException { this(Locale.getDefault(),fmtArg); }
Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings. Control strings begin with unpaired percent signs. A pair of successive percent signs designates a single percent sign in the format.
public void cancel(){ try { bluetoothSSocket.close(); } catch ( IOException e) { Log.e(TAG,"Unable to close bluetooth socket.",e); } }
Cancels this thread.
private void resizeWidgetIfNeeded(boolean onDismiss){ int xThreshold=mCellLayout.getCellWidth() + mCellLayout.getWidthGap(); int yThreshold=mCellLayout.getCellHeight() + mCellLayout.getHeightGap(); int deltaX=mDeltaX + mDeltaXAddOn; int deltaY=mDeltaY + mDeltaYAddOn; float hSpanIncF=1.0f * deltaX / xThreshold - mRunningHInc; float vSpanIncF=1.0f * deltaY / yThreshold - mRunningVInc; int hSpanInc=0; int vSpanInc=0; int cellXInc=0; int cellYInc=0; int countX=mCellLayout.getCountX(); int countY=mCellLayout.getCountY(); if (Math.abs(hSpanIncF) > RESIZE_THRESHOLD) { hSpanInc=Math.round(hSpanIncF); } if (Math.abs(vSpanIncF) > RESIZE_THRESHOLD) { vSpanInc=Math.round(vSpanIncF); } if (!onDismiss && (hSpanInc == 0 && vSpanInc == 0)) return; CellLayout.LayoutParams lp=(CellLayout.LayoutParams)mWidgetView.getLayoutParams(); int spanX=lp.cellHSpan; int spanY=lp.cellVSpan; int cellX=lp.useTmpCoords ? lp.tmpCellX : lp.cellX; int cellY=lp.useTmpCoords ? lp.tmpCellY : lp.cellY; int hSpanDelta=0; int vSpanDelta=0; if (mLeftBorderActive) { cellXInc=Math.max(-cellX,hSpanInc); cellXInc=Math.min(lp.cellHSpan - mMinHSpan,cellXInc); hSpanInc*=-1; hSpanInc=Math.min(cellX,hSpanInc); hSpanInc=Math.max(-(lp.cellHSpan - mMinHSpan),hSpanInc); hSpanDelta=-hSpanInc; } else if (mRightBorderActive) { hSpanInc=Math.min(countX - (cellX + spanX),hSpanInc); hSpanInc=Math.max(-(lp.cellHSpan - mMinHSpan),hSpanInc); hSpanDelta=hSpanInc; } if (mTopBorderActive) { cellYInc=Math.max(-cellY,vSpanInc); cellYInc=Math.min(lp.cellVSpan - mMinVSpan,cellYInc); vSpanInc*=-1; vSpanInc=Math.min(cellY,vSpanInc); vSpanInc=Math.max(-(lp.cellVSpan - mMinVSpan),vSpanInc); vSpanDelta=-vSpanInc; } else if (mBottomBorderActive) { vSpanInc=Math.min(countY - (cellY + spanY),vSpanInc); vSpanInc=Math.max(-(lp.cellVSpan - mMinVSpan),vSpanInc); vSpanDelta=vSpanInc; } mDirectionVector[0]=0; mDirectionVector[1]=0; if (mLeftBorderActive || mRightBorderActive) { spanX+=hSpanInc; cellX+=cellXInc; if (hSpanDelta != 0) { mDirectionVector[0]=mLeftBorderActive ? -1 : 1; } } if (mTopBorderActive || mBottomBorderActive) { spanY+=vSpanInc; cellY+=cellYInc; if (vSpanDelta != 0) { mDirectionVector[1]=mTopBorderActive ? -1 : 1; } } if (!onDismiss && vSpanDelta == 0 && hSpanDelta == 0) return; if (onDismiss) { mDirectionVector[0]=mLastDirectionVector[0]; mDirectionVector[1]=mLastDirectionVector[1]; } else { mLastDirectionVector[0]=mDirectionVector[0]; mLastDirectionVector[1]=mDirectionVector[1]; } if (mCellLayout.createAreaForResize(cellX,cellY,spanX,spanY,mWidgetView,mDirectionVector,onDismiss)) { lp.tmpCellX=cellX; lp.tmpCellY=cellY; lp.cellHSpan=spanX; lp.cellVSpan=spanY; mRunningVInc+=vSpanDelta; mRunningHInc+=hSpanDelta; if (!onDismiss) { updateWidgetSizeRanges(mWidgetView,mLauncher,spanX,spanY); } } mWidgetView.requestLayout(); }
Based on the current deltas, we determine if and how to resize the widget.
public static Uri.Builder appendId(Uri.Builder builder,long id){ return builder.appendEncodedPath(String.valueOf(id)); }
Appends the given ID to the end of the path.
public final void reset(){ cursor=Address.zero(); limit=Address.zero(); internalLimit=Address.zero(); initialRegion=Address.zero(); region=Address.zero(); }
Reset the allocator. Note that this does not reset the space. This is must be done by the caller.
public String toString(){ StringBuilder buffer=new StringBuilder(); buffer.append(Constants.INDENT); buffer.append("ulMacSizeInBits: "); buffer.append(ulMacSizeInBits); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("ulKeySizeInBits: "); buffer.append(ulKeySizeInBits); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("ulIVSizeInBits: "); buffer.append(ulIVSizeInBits); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("bIsExport: "); buffer.append(bIsExport); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("RandomInfo: "); buffer.append(RandomInfo); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("pReturnedKeyMaterial: "); buffer.append(pReturnedKeyMaterial); return buffer.toString(); }
Returns the string representation of CK_SSL3_KEY_MAT_PARAMS.
synchronized int addTrack(final MediaFormat format){ if (mIsStarted) throw new IllegalStateException("muxer already started"); final int trackIx=mMediaMuxer.addTrack(format); if (DEBUG) Log.i(TAG,"addTrack:trackNum=" + mEncoderCount + ",trackIx="+ trackIx+ ",format="+ format); return trackIx; }
assign encoder to muxer
public void removeElements(final int from,final int to){ CharArrays.ensureFromTo(size,from,to); System.arraycopy(a,to,a,from,size - to); size-=(to - from); }
Removes elements of this type-specific list using optimized system calls.
public IconOverlay(IGeoPoint position,Drawable icon){ super(); set(position,icon); }
save to be called in non-gui-thread
@Override public boolean isStopped(){ if (mIsTaskStop) { if (!mFileDownloadTaskImpl.isStopped()) { stopInternalImpl(); } } return mIsTaskStop; }
whether the download task is stopped
public StatementInfoProcessor(final AbstractFbStatement statement,final FbDatabase database){ this.statement=statement; this.database=database; }
Creates an instance of this class.
public static Number extractNumber(Object value){ NumberFormat numberFormat=NumberFormat.getInstance(); if (value instanceof Number) { return (Number)value; } else if (value == null) { return new Long(0); } else { try { return numberFormat.parse(value.toString()); } catch ( ParseException ex) { DTThrowable.rethrow(ex); } } return new Long(0); }
returns the number value of the supplied object
final V remove(Object key,int hash,Object value){ if (!tryLock()) scanAndLock(key,hash); V oldValue=null; try { HashEntry<K,V>[] tab=table; int index=(tab.length - 1) & hash; HashEntry<K,V> e=entryAt(tab,index); HashEntry<K,V> pred=null; while (e != null) { K k; HashEntry<K,V> next=e.next; if ((k=e.key) == key || (e.hash == hash && key.equals(k))) { V v=e.value; if (value == null || value == v || value.equals(v)) { if (pred == null) setEntryAt(tab,index,next); else pred.setNext(next); ++modCount; --count; oldValue=v; } break; } pred=e; e=next; } } finally { unlock(); } return oldValue; }
Remove; match on key only if value null, else match both.
public boolean isMaxYSet(int scale){ return mMaxY[scale] != -MathHelper.NULL_VALUE; }
Returns if the maximum Y value was set.
@Override public void registerNode(jmri.jmrix.AbstractNode node){ if (node instanceof XBeeNode) { super.registerNode(node); XBeeNode xbnode=(XBeeNode)node; xbnode.setTrafficController(this); } else { throw new java.lang.IllegalArgumentException("Attempt to register node of incorrect type for this connection"); } }
Public method to register a node
public boolean isLeaderNode(){ String myNodeId=coordinator.getInetAddessLookupMap().getNodeId(); String localZkMode=getCoordinatorMode(myNodeId); return isLeaderNode(localZkMode); }
Determine if the current node is a ZK leader/standalone
private boolean readHeader() throws IOException { if (consecutiveLineBreaks > 1) { consecutiveLineBreaks=0; return false; } readName(); consecutiveLineBreaks=0; readValue(); return consecutiveLineBreaks > 0; }
Read a single line from the manifest buffer.
@Override public boolean equals(Object obj){ if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Diff other=(Diff)obj; if (operation != other.operation) { return false; } if (text == null) { if (other.text != null) { return false; } } else if (!text.equals(other.text)) { return false; } return true; }
Is this Diff equivalent to another Diff?
public static void main(String[] args){ Scanner input=new Scanner(System.in); System.out.print("Enter two integers: "); int m=Integer.parseInt(input.next()); int n=Integer.parseInt(input.next()); System.out.println("The greatest common divisor of " + m + " and "+ n+ " is "+ gcd(m,n)); }
Main method
public static void throwTargetException(InvocationTargetException itex) throws Exception { throw extractTargetException(itex); }
Throws target of <code>InvocationTargetException</code> if it is exception.
private boolean cleanUp(Reference<?> reference){ Method finalizeReferentMethod=getFinalizeReferentMethod(); if (finalizeReferentMethod == null) { return false; } do { reference.clear(); if (reference == frqReference) { return false; } try { finalizeReferentMethod.invoke(reference); } catch ( Throwable t) { logger.log(Level.SEVERE,"Error cleaning up after reference.",t); } } while ((reference=queue.poll()) != null); return true; }
Cleans up a single reference. Catches and logs all throwables.
private void addTagListener(final CTag tag){ if (!m_cachedTagListeners.containsKey(tag)) { m_cachedTagListeners.put(tag,0); tag.addListener(m_internalTagListener); } m_cachedTagListeners.put(tag,m_cachedTagListeners.get(tag) + 1); }
Adds a new listener to a tag if the given node requires it.
private LogPolicy addPolicy(String propertyName,boolean defaultValue){ String flag=LogManager.getLogManager().getProperty(propertyName); if (flag != null) { policy.put(propertyName,Boolean.parseBoolean(flag)); } else { policy.put(propertyName,defaultValue); } return this; }
Adds a particular configuration property for controlling content to be included in the formatter's output.
public boolean isRTPMarkerSet(){ return (flags & FLAG_RTP_MARKER) != 0; }
Check if the RTP marker is set
public TouchHandler(GraphicalView view,AbstractChart chart){ graphicalView=view; zoomR=graphicalView.getZoomRectangle(); if (chart instanceof XYChart) { mRenderer=((XYChart)chart).getRenderer(); } else { mRenderer=((RoundChart)chart).getRenderer(); } if (mRenderer.isPanEnabled()) { mPan=new Pan(chart); } if (mRenderer.isZoomEnabled()) { mPinchZoom=new Zoom(chart,true,1); } }
Creates a new graphical view.
@Override public String childByDescription(Selector collection,Selector child,String text) throws UiObjectNotFoundException { UiObject obj; if (exist(collection) && objInfo(collection).isScrollable()) { obj=new UiScrollable(collection.toUiSelector()).getChildByDescription(child.toUiSelector(),text); } else { obj=new UiCollection(collection.toUiSelector()).getChildByDescription(child.toUiSelector(),text); } return addUiObject(obj); }
Searches for child UI element within the constraints of this UiSelector selector. It looks for any child matching the childPattern argument that has a child UI element anywhere within its sub hierarchy that has content-description text. The returned UiObject will point at the childPattern instance that matched the search and not at the identifying child element that matched the content description.
public static void encodeRaypickColorId(int id,PickerIDAttribute out){ out.r=id & 0x000000FF; out.g=(id & 0x0000FF00) >>> 8; out.b=(id & 0x00FF0000) >>> 16; }
Encodes a id to a GameObjectIdAttribute with rgb channels.
@Subscribe @AllowConcurrentEvents public void sessionFailed(final SessionFailedEvent event){ LOGGER.info("Received test session failed event. " + (event.getComment().isPresent() ? event.getComment().get() : "")); failedSessionIds.add(event.getSessionId()); countDown(); }
Percepts a test session failure event, registers the session ID of the failed session.
public static String escapeHtml(String str){ if (str == null) { return null; } try { StringWriter writer=new StringWriter((int)(str.length() * 1.5)); escapeHtml(writer,str); return writer.toString(); } catch ( IOException ioe) { throw new UnhandledException(ioe); } }
<p>Escapes the characters in a <code>String</code> using HTML entities.</p> <p> For example: </p> <p><code>"bread" & "butter"</code></p> becomes: <p> <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>. </p> <p>Supports all known HTML 4.0 entities, including funky accents. Note that the commonly used apostrophe escape character (&amp;apos;) is not a legal entity and so is not supported). </p>
@Override public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.mediaplayer_2); mPreview=(SurfaceView)findViewById(R.id.surface); holder=mPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); extras=getIntent().getExtras(); }
Called when the activity is first created.
public static void d(String tag,String msg,Throwable throwable){ if (sLevel > LEVEL_DEBUG) { return; } Log.d(tag,msg,throwable); }
Send a DEBUG log message
public void receive(DatagramPacket p) throws IOException { if (delegateAsDelegatingSocket != null) { delegateAsDelegatingSocket.receive(p); } else { SocketChannel channel=getChannel(); if (channel == null) { if (inputStream == null) inputStream=getInputStream(); DelegatingSocket.receiveFromInputStream(p,inputStream,getInetAddress(),getPort()); } else { receiveFromChannel(channel,p); } InetSocketAddress localAddress=(InetSocketAddress)super.getLocalSocketAddress(); if (StunDatagramPacketFilter.isStunPacket(p) || DelegatingDatagramSocket.logNonStun(++nbReceivedPackets)) { StunStack.logPacketToPcap(p,false,localAddress.getAddress(),localAddress.getPort()); } } }
Receives a datagram packet from this socket. The <tt>DatagramPacket</tt>s returned by this method do not match any of the <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedSocket</tt>s associated with this instance at the time of their receipt. When this method returns, the <tt>DatagramPacket</tt>'s buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine. <p> This method blocks until a datagram is received. The <tt>length</tt> field of the datagram packet object contains the length of the received message. If the message is longer than the packet's length, the message is truncated. </p>
public static double acos(double x){ return HALF_PI - MathLib.asin(x); }
Returns the arc cosine of the specified value, in the range of 0.0 through <i>pi</i>.
public static TvListing parse(InputStream inputStream) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(inputStream)); String line; List<Channel> channels=new ArrayList<>(); List<Program> programs=new ArrayList<>(); Map<Integer,Integer> channelMap=new HashMap<>(); int defaultDisplayNumber=0; while ((line=in.readLine()) != null) { if (line.startsWith("#EXTINF:")) { String id=null; String displayName=null; String displayNumber=null; int originalNetworkId=0; String icon=null; String[] parts=line.split(",",2); if (parts.length == 2) { for ( String part : parts[0].split(" ")) { if (part.startsWith("#EXTINF:")) { displayNumber=part.substring(8).replaceAll("^0+",""); if (displayNumber.isEmpty()) displayNumber=defaultDisplayNumber + ""; if (displayNumber.equals("-1")) displayNumber=defaultDisplayNumber + ""; defaultDisplayNumber++; originalNetworkId=Integer.parseInt(displayNumber); } else if (part.startsWith("tvg-id=")) { int end=part.indexOf("\"",8); if (end > 8) { id=part.substring(8,end); } } else if (part.startsWith("tvg-logo=")) { int end=part.indexOf("\"",10); if (end > 10) { icon=part.substring(10,end); } } } displayName=parts[1].replaceAll("\\[\\/?(COLOR |)[^\\]]*\\]",""); } if (originalNetworkId != 0 && displayName != null) { Channel channel=new Channel().setChannelId(Integer.parseInt(id)).setName(displayName).setNumber(displayNumber).setLogoUrl(icon).setOriginalNetworkId(originalNetworkId); if (channelMap.containsKey(originalNetworkId)) { int freeChannel=1; while (channelMap.containsKey(new Integer(freeChannel))) { freeChannel++; } channelMap.put(freeChannel,channels.size()); channel.setNumber(freeChannel + ""); channels.add(channel); } else { channelMap.put(originalNetworkId,channels.size()); channels.add(channel); } } else { Log.d(TAG,"Import failed: " + originalNetworkId + "= "+ line); } } else if (line.startsWith("http") && channels.size() > 0) { channels.get(channels.size() - 1).setInternalProviderData(line); } else if (line.startsWith("rtmp") && channels.size() > 0) { channels.get(channels.size() - 1).setInternalProviderData(line); } } TvListing tvl=new TvListing(channels,programs); Log.d(TAG,"Done parsing"); Log.d(TAG,tvl.toString()); return new TvListing(channels,programs); }
When you have an inputStream that is a valid M3U8 playlist, this function parses it into a model that can be applied to Live Channels
private Object toggleExponentSign(int offset,char aChar) throws BadLocationException, ParseException { String string=getFormattedTextField().getText(); int replaceLength=0; int loc=getAttributeStart(NumberFormat.Field.EXPONENT_SIGN); if (loc >= 0) { replaceLength=1; offset=loc; } if (aChar == getPositiveSign()) { string=getReplaceString(offset,replaceLength,null); } else { string=getReplaceString(offset,replaceLength,new String(new char[]{aChar})); } return stringToValue(string); }
Invoked to toggle the sign of the exponent (for scientific numbers).
protected boolean hasAttemptRemaining(){ return mCurrentRetryCount <= mMaxNumRetries; }
Returns true if this policy has attempts remaining, false otherwise.
public EclipseApp productBuildCmd(File buildDir) throws Exception { EclipseApp antApp=new EclipseApp(EclipseApp.AntRunner.ID); antApp.addArg("buildfile",getPdeBuildProductBuildXml().getAbsolutePath()); antApp.addArg("Dbuilder=" + FileMisc.quote(buildDir)); return antApp; }
Returns a command which will execute the PDE builder for a product.
private void summaryRecursive(IgfsFile file,IgfsPathSummary sum) throws IgniteCheckedException { assert file != null; assert sum != null; if (file.isDirectory()) { if (!F.eq(IgfsPath.ROOT,file.path())) sum.directoriesCount(sum.directoriesCount() + 1); for ( IgfsFile childFile : listFiles(file.path())) summaryRecursive(childFile,sum); } else { sum.filesCount(sum.filesCount() + 1); sum.totalLength(sum.totalLength() + file.length()); } }
Calculates size of directory or file for given ID.
void release(){ if (inNetBuffer != null) { inNetBuffer.free(); inNetBuffer=null; } if (outNetBuffer != null) { outNetBuffer.free(); outNetBuffer=null; } }
Free the allocated buffers
@Override public void drawItem(Graphics2D g2,CategoryItemRendererState state,Rectangle2D dataArea,CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis,CategoryDataset dataset,int row,int column,int pass){ if (!getItemVisible(row,column)) { return; } int visibleRow=state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } int visibleRowCount=state.getVisibleSeriesCount(); PlotOrientation orientation=plot.getOrientation(); MultiValueCategoryDataset d=(MultiValueCategoryDataset)dataset; List values=d.getValues(row,column); if (values == null) { return; } int valueCount=values.size(); for (int i=0; i < valueCount; i++) { double x1; if (this.useSeriesOffset) { x1=domainAxis.getCategorySeriesMiddle(column,dataset.getColumnCount(),visibleRow,visibleRowCount,this.itemMargin,dataArea,plot.getDomainAxisEdge()); } else { x1=domainAxis.getCategoryMiddle(column,getColumnCount(),dataArea,plot.getDomainAxisEdge()); } Number n=(Number)values.get(i); double value=n.doubleValue(); double y1=rangeAxis.valueToJava2D(value,dataArea,plot.getRangeAxisEdge()); Shape shape=getItemShape(row,column); if (orientation == PlotOrientation.HORIZONTAL) { shape=ShapeUtilities.createTranslatedShape(shape,y1,x1); } else if (orientation == PlotOrientation.VERTICAL) { shape=ShapeUtilities.createTranslatedShape(shape,x1,y1); } if (getItemShapeFilled(row,column)) { if (this.useFillPaint) { g2.setPaint(getItemFillPaint(row,column)); } else { g2.setPaint(getItemPaint(row,column)); } g2.fill(shape); } if (this.drawOutlines) { if (this.useOutlinePaint) { g2.setPaint(getItemOutlinePaint(row,column)); } else { g2.setPaint(getItemPaint(row,column)); } g2.setStroke(getItemOutlineStroke(row,column)); g2.draw(shape); } } }
Draw a single data item.
protected void removeSocket(TransportAddress localAddress,TransportAddress remoteAddress){ Connector connector=null; final Map<TransportAddress,Map<TransportAddress,Connector>> connectorsMap=(localAddress.getTransport() == Transport.UDP) ? udpConnectors : tcpConnectors; synchronized (connectorsMap) { Map<TransportAddress,Connector> connectorsForLocalAddress=connectorsMap.get(localAddress); if (connectorsForLocalAddress != null) { connector=connectorsForLocalAddress.get(remoteAddress); if (connector != null) { connectorsForLocalAddress.remove(remoteAddress); if (connectorsForLocalAddress.isEmpty()) connectorsMap.remove(localAddress); } } } if (connector != null) connector.stop(); }
Stops and deletes the specified access point.