code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public boolean hasMoreElements(){
if (m_mine.hasMoreElements()) {
return true;
}
if (m_next != null) {
return m_next.hasMoreElements();
}
return false;
}
| Method hasMoreElements. |
public void testVerifyCommitRecordIndex(){
final Properties properties=new Properties(getProperties());
properties.setProperty(AbstractTransactionService.Options.MIN_RELEASE_AGE,"400");
final Journal store=getJournal(properties);
try {
MemStrategy bs=(MemStrategy)store.getBufferStrategy();
for (int r=0; r < 10; r++) {
ArrayList<Long> addrs=new ArrayList<Long>();
for (int i=0; i < 100; i++) {
addrs.add(bs.write(randomData(45)));
}
store.commit();
for ( long addr : addrs) {
bs.delete(addr);
}
store.commit();
}
Thread.currentThread().sleep(400);
verifyCommitIndex(store,20);
store.close();
}
catch ( InterruptedException e) {
}
finally {
store.destroy();
}
}
| Can be tested by removing RWStore call to journal.removeCommitRecordEntries in freeDeferrals. final int commitPointsRemoved = journal.removeCommitRecordEntries(fromKey, toKey); replaced with final int commitPointsRemoved = commitPointsRecycled; |
@Override public FlowHandler createFlowHandler(FacesContext context){
return new FlowHandlerImpl();
}
| Create the flow handler. |
private Operation createNotifyOp(String coordinator,String serviceLink,String header,Operation.CompletionHandler callback){
ConflictCheckRequest body=new ConflictCheckRequest();
body.serviceLink=serviceLink;
return Operation.createPatch(this,coordinator).addRequestHeader(Operation.TRANSACTION_HEADER,header).setBody(body).setReferer(getUri()).setCompletion(callback);
}
| Prepare an operation to check conflicts with a remote coordinator |
public void testConstructorSignBytesNegative1(){
byte aBytes[]={12,56,100,-2,-76,89,45,91,3,-15};
int aSign=-1;
byte rBytes[]={-13,-57,-101,1,75,-90,-46,-92,-4,15};
BigInteger aNumber=new BigInteger(aSign,aBytes);
byte resBytes[]=new byte[rBytes.length];
resBytes=aNumber.toByteArray();
for (int i=0; i < resBytes.length; i++) {
assertTrue(resBytes[i] == rBytes[i]);
}
assertEquals("incorrect sign",-1,aNumber.signum());
}
| Create a negative number from a sign and an array of bytes. The number fits in an array of integers. The most significant byte is positive. |
public boolean isMotorEnabled(){
return joint.isMotorEnabled();
}
| Is the joint motor enabled? |
static void writeShort(final byte[] b,final int index,final int s){
b[index]=(byte)(s >>> 8);
b[index + 1]=(byte)s;
}
| Writes a short value in the given byte array. |
public DERUTCTime(Date time){
SimpleDateFormat dateF=new SimpleDateFormat("yyMMddHHmmss'Z'");
dateF.setTimeZone(new SimpleTimeZone(0,"Z"));
this.time=Strings.toByteArray(dateF.format(time));
}
| base constructer from a java.util.date object |
private void updateWidget(){
RemoteViews remoteViews=WidgetProvider.configureWidgetIntents(this,mCurrentEpisode);
AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(this);
ComponentName thisWidget=new ComponentName(getApplicationContext(),WidgetProvider.class);
int playPauseResId=PlaybackButtonHelper.getWidgetPlaybackButtonResId(getPlaybackState());
int[] allWidgetIds=appWidgetManager.getAppWidgetIds(thisWidget);
if (allWidgetIds == null || allWidgetIds.length == 0) {
return;
}
if (mCurrentEpisode == null) {
remoteViews.setTextViewText(R.id.episode_title,"");
remoteViews.setTextViewText(R.id.channel_title,"");
remoteViews.setImageViewResource(R.id.play,playPauseResId);
remoteViews.setImageViewResource(R.id.channel_art,R.drawable.default_channel_art);
}
else {
ImageLoadHelper.loadImageIntoWidget(this,mCurrentEpisode.getChannelArtworkUrl(),remoteViews,R.id.channel_art,allWidgetIds,new RoundedCornersTransformation(this));
remoteViews.setOnClickPendingIntent(R.id.play,PendingIntentHelper.getPlayOrPauseIntent(this,getPlaybackState()));
remoteViews.setTextViewText(R.id.episode_title,mCurrentEpisode.getTitle());
remoteViews.setTextViewText(R.id.channel_title,mCurrentEpisode.getChannelTitle());
remoteViews.setImageViewResource(R.id.play,playPauseResId);
}
for ( int widgetId : allWidgetIds) {
appWidgetManager.updateAppWidget(widgetId,remoteViews);
}
}
| Widget update related functions |
private int trimToPowerOf2(int initialCapacity){
int capacity=1;
while (capacity < initialCapacity) {
capacity<<=1;
}
return capacity;
}
| Return a power of 2 for initialCapacity |
protected Polygon createArrow(mxPoint p0,mxPoint pe){
double spacing=mxConstants.ARROW_SPACING * scale;
double width=mxConstants.ARROW_WIDTH * scale;
double arrow=mxConstants.ARROW_SIZE * scale;
double dx=pe.getX() - p0.getX();
double dy=pe.getY() - p0.getY();
double dist=Math.sqrt(dx * dx + dy * dy);
double length=dist - 2 * spacing - arrow;
double nx=dx / dist;
double ny=dy / dist;
double basex=length * nx;
double basey=length * ny;
double floorx=width * ny / 3;
double floory=-width * nx / 3;
double p0x=p0.getX() - floorx / 2 + spacing * nx;
double p0y=p0.getY() - floory / 2 + spacing * ny;
double p1x=p0x + floorx;
double p1y=p0y + floory;
double p2x=p1x + basex;
double p2y=p1y + basey;
double p3x=p2x + floorx;
double p3y=p2y + floory;
double p5x=p3x - 3 * floorx;
double p5y=p3y - 3 * floory;
Polygon poly=new Polygon();
poly.addPoint((int)Math.round(p0x),(int)Math.round(p0y));
poly.addPoint((int)Math.round(p1x),(int)Math.round(p1y));
poly.addPoint((int)Math.round(p2x),(int)Math.round(p2y));
poly.addPoint((int)Math.round(p3x),(int)Math.round(p3y));
poly.addPoint((int)Math.round(pe.getX() - spacing * nx),(int)Math.round(pe.getY() - spacing * ny));
poly.addPoint((int)Math.round(p5x),(int)Math.round(p5y));
poly.addPoint((int)Math.round(p5x + floorx),(int)Math.round(p5y + floory));
return poly;
}
| Creates a polygon that represents an arrow. |
public EventType(){
id=String.valueOf(count++);
}
| Creates a new event type. |
public boolean startsWith(XMLString prefix){
return m_str.startsWith(prefix.toString());
}
| Tests if this string starts with the specified prefix. |
public IOUtils(){
super();
}
| Instances should NOT be constructed in standard programming. |
@Override public void slaveLost(SchedulerDriver driver,Protos.SlaveID slaveId){
scheduler.expireAllLeasesByVMId(slaveId.getValue());
}
| Upon slave lost notification, tell Fenzo scheduler to expire all leases with the given slave ID. Note, however, that if there was no offer received from that slave prior to this call, Fenzo would not have a mapping from the slave ID to hostname (Fenzo maintains slaves state by hostname). This is OK since there would be no offers to expire. However, any tasks running on the lost slave will not be removed by this call to Fenzo. Task lost status updates would ensure that. |
@Override public void draw(Graphics2D g){
if (getOwner().isTransformable()) {
drawRectangle(g,(Color)getEditor().getHandleAttribute(HandleAttributeKeys.MOVE_HANDLE_FILL_COLOR),(Color)getEditor().getHandleAttribute(HandleAttributeKeys.MOVE_HANDLE_STROKE_COLOR));
}
else {
drawRectangle(g,(Color)getEditor().getHandleAttribute(HandleAttributeKeys.NULL_HANDLE_FILL_COLOR),(Color)getEditor().getHandleAttribute(HandleAttributeKeys.NULL_HANDLE_STROKE_COLOR));
}
}
| Draws this handle. <p> If the figure is transformable, the handle is drawn as a filled rectangle. If the figure is not transformable, the handle is drawn as an unfilled rectangle. |
@Override public void addExternalHandler(final Object newHandler,final int type){
switch (type) {
case Options.FormsActionHandler:
userActionHandler=(ActionHandler)newHandler;
break;
case Options.CustomMouseHandler:
JavaFXMouseListener.setCustomMouseFunctions((JavaFXMouseFunctionality)newHandler);
break;
case Options.ThumbnailHandler:
pages.setThumbnailPanel((org.jpedal.display.GUIThumbnailPanel)newHandler);
break;
default :
externalHandlers.addExternalHandler(newHandler,type);
}
}
| not part of API used internally allows external helper classes to be added to JPedal to alter default functionality - |
public static void main(String[] args){
double[][] matrix1=getmatrix(1);
double[][] matrix2=getmatrix(2);
double[][] matrix3=multiplyMatrix(matrix1,matrix2);
print(matrix1,matrix2,matrix3);
}
| Main method |
private void genTable(String tableName,String whereClause,boolean completeXML,Properties ctx,WebInfo wi){
String l_szTrxName=null;
StringBuffer tmpCode=new StringBuffer();
String dataTableName=tableName;
String l_whereClause=replaceSessionElements(wi,whereClause);
tmpCode.append("<" + tableName + ">\n");
if (whereClause.indexOf("AD_Reference") > -1) {
dataTableName="AD_Ref_List";
}
int[] l_nIDs=PO.getAllIDs(dataTableName,l_whereClause,l_szTrxName);
int[] l_nTableIDs=MTable.getAllIDs("AD_Table","TableName='" + dataTableName + "'",l_szTrxName);
if (l_nTableIDs.length > 0) {
MTable table=MTable.get(ctx,l_nTableIDs[0]);
PO l_Object=null;
if (completeXML) {
for (int i=0; i < l_nIDs.length; i++) {
l_Object=table.getPO(l_nIDs[i],l_szTrxName);
l_Object.get_xmlString(tmpCode);
}
}
else {
String sql=MLookupFactory.getLookup_TableDirEmbed(Language.getLanguage("en"),dataTableName + "_ID",dataTableName);
sql=sql.concat(" AND " + l_whereClause);
PreparedStatement pstm=DB.prepareStatement(sql,l_szTrxName);
ResultSet rs=null;
try {
rs=pstm.executeQuery();
}
catch ( Exception e) {
}
for (int i=0; i < l_nIDs.length; i++) {
l_Object=table.getPO(l_nIDs[i],l_szTrxName);
tmpCode.append("<" + dataTableName + " AD_Table_ID=\""+ table.get_ID()+ "\" Record_ID=\""+ l_Object.get_ID()+ "\">\n");
tmpCode.append("<" + dataTableName + "_ID>");
tmpCode.append(l_Object.get_ID());
tmpCode.append("</" + dataTableName + "_ID>\n");
if (dataTableName.equals("AD_Ref_List")) {
tmpCode.append("<Value>");
tmpCode.append("<![CDATA[" + l_Object.get_Value("Value") + "]]>\n");
tmpCode.append("</Value>\n");
}
if (dataTableName.equals("AD_User") || dataTableName.equals("C_Project")) {
tmpCode.append("<C_BPartner_ID>");
tmpCode.append(l_Object.get_Value("C_BPartner_ID"));
tmpCode.append("</C_BPartner_ID>\n");
}
tmpCode.append("<DisplayName>\n");
try {
if (rs.next()) {
tmpCode.append("<![CDATA[" + rs.getString(1) + "]]>\n");
}
}
catch ( SQLException e) {
tmpCode.append("<![CDATA[" + e.getMessage() + "]]\n");
}
tmpCode.append("</DisplayName>\n");
tmpCode.append("</" + dataTableName + ">\n");
}
try {
rs.close();
pstm.close();
}
catch ( Exception e) {
}
}
}
tmpCode.append("</" + tableName + ">\n");
xmlCode.append(tmpCode);
}
| Creates the nodes for the request tables in the XML-tree. |
@Inline public static boolean isZeroed(Address start,int bytes){
return isSet(start,bytes,false,0);
}
| Check that a memory range is zeroed |
public int kthSmallestB(TreeNode root,int k){
Deque<TreeNode> stack=new ArrayDeque<>();
int count=k;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root=root.left;
}
else {
root=stack.pop();
count--;
if (count == 0) {
return root.val;
}
root=root.right;
}
}
return -1;
}
| Iterasive solution with stack. |
public static String toString(Calendar v){
if (v != null) {
return new SimpleDateFormat("EEE MM/dd/yyyy hh:mm:ss a").format(v.getTime());
}
return null;
}
| Calendar -> String |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int col;
int row;
int numCols;
int numRows;
int a;
int i;
float progress;
int range;
boolean blnTextOutput=false;
double z;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
blnTextOutput=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster image=new WhiteboxRaster(inputHeader,"r");
numRows=image.getNumberRows();
numCols=image.getNumberColumns();
double noData=image.getNoDataValue();
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
output.setPreferredPalette("spectrum.pal");
output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS);
int minValue=(int)(image.getMinimumValue());
int maxValue=(int)(image.getMaximumValue());
range=maxValue - minValue;
double[] data;
double[][] totals=new double[4][range + 1];
double[] radius=new double[range + 1];
double[][] centroid=new double[2][range + 1];
double[] DFCSum=new double[range + 1];
long[][] minRowAndCol=new long[2][range + 1];
for (a=0; a <= range; a++) {
minRowAndCol[0][a]=Long.MAX_VALUE;
minRowAndCol[1][a]=Long.MAX_VALUE;
}
updateProgress("Finding patch min row and columns:",0);
for (row=0; row < numRows; row++) {
data=image.getRowValues(row);
for (col=0; col < numCols; col++) {
if (data[col] > 0) {
a=(int)(data[col] - minValue);
if (row < minRowAndCol[0][a]) {
minRowAndCol[0][a]=row;
}
if (col < minRowAndCol[1][a]) {
minRowAndCol[1][a]=col;
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Finding patch min row and columns:",(int)progress);
}
updateProgress("Loop 1 of 3:",0);
for (row=0; row < numRows; row++) {
data=image.getRowValues(row);
for (col=0; col < numCols; col++) {
if (data[col] > 0) {
a=(int)(data[col] - minValue);
totals[0][a]+=(col - minRowAndCol[1][a]);
totals[1][a]+=(row - minRowAndCol[0][a]);
totals[2][a]++;
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 1 of 3:",(int)progress);
}
for (a=0; a <= range; a++) {
if (totals[2][a] > 0) {
centroid[0][a]=totals[0][a] / totals[2][a] + minRowAndCol[1][a];
centroid[1][a]=totals[1][a] / totals[2][a] + minRowAndCol[0][a];
radius[a]=Math.sqrt((totals[2][a]) / Math.PI) - 0.5;
}
}
updateProgress("Loop 2 of 3:",0);
double d;
for (row=0; row < numRows; row++) {
data=image.getRowValues(row);
for (col=0; col < numCols; col++) {
if (data[col] > 0) {
a=(int)(data[col] - minValue);
d=Math.sqrt(Math.pow((col - centroid[0][a]),2d) + Math.pow((row - centroid[1][a]),2));
DFCSum[a]+=(double)d;
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 2 of 3:",(int)progress);
}
for (a=0; a <= range; a++) {
if (totals[2][a] > 0) {
DFCSum[a]=DFCSum[a] / totals[2][a];
}
}
updateProgress("Loop 3 of 3:",0);
for (row=0; row < numRows; row++) {
data=image.getRowValues(row);
for (col=0; col < numCols; col++) {
if (data[col] > 0) {
a=(int)(data[col] - minValue);
output.setValue(row,col,DFCSum[a]);
}
else {
output.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 3 of 3:",(int)progress);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
image.close();
output.close();
if (blnTextOutput) {
DecimalFormat df;
df=new DecimalFormat("0.0000");
String retstr="Radius of Gyration\nPatch ID\tValue";
for (a=0; a <= range; a++) {
if (DFCSum[a] > 0) {
retstr=retstr + "\n" + (a + minValue)+ "\t"+ df.format(DFCSum[a]);
}
}
returnData(retstr);
}
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public String transformBackToOriginalTipText(){
return "Transform through the PC space and back to the original space. " + "If only the best n PCs are retained (by setting varianceCovered < 1) " + "then this option will give a dataset in the original space but with "+ "less attribute noise.";
}
| Returns the tip text for this property |
public StandardOutputPrinter(){
this(InternalLogWriter.ALL_LEVEL);
}
| Creates a writer that logs to <code>System.err</code>. All messages will be logged. |
@Override public JnaDatabase identify() throws SQLException {
return new JnaDatabase(this);
}
| Contrary to the description in the super class, this will simply return an unconnected instance. |
private boolean isBigEndian(){
return getFormat().isBigEndian();
}
| Returns if this stream (the decoded one) is big endian. |
public static void playAlbum(final Context context,final long albumId,int position){
final long[] albumList=getSongListForAlbum(context,albumId);
if (albumList != null) {
playAll(albumList,position,false);
}
}
| Plays songs from an album. |
public String edgesToString(){
String result="";
for (Iterator<Edge<T>> it=edgesIterator(); it.hasNext(); ) {
Edge<T> edge=it.next();
result+="(" + edge.from.value + "->"+ edge.to.value+ ")";
}
return result;
}
| Returns a String describing the Edges only. May be helpful while analyzing cycles. |
public static _Fields findByThriftIdOrThrow(int fieldId){
_Fields fields=findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
| Find the _Fields constant that matches fieldId, throwing an exception if it is not found. |
@Override public AffineTransform inverse(){
double det=this.determinant();
return new AffineTransform((m11 * m22 - m21 * m12) / det,(m21 * m01 - m01 * m22) / det,(m01 * m12 - m11 * m02) / det,(m01 * (m22 * m13 - m12 * m23) + m02 * (m11 * m23 - m21 * m13) - m03 * (m11 * m22 - m21 * m12)) / det,(m20 * m12 - m10 * m22) / det,(m00 * m22 - m20 * m02) / det,(m10 * m02 - m00 * m12) / det,(m00 * (m12 * m23 - m22 * m13) - m02 * (m10 * m23 - m20 * m13) + m03 * (m10 * m22 - m20 * m12)) / det,(m10 * m21 - m20 * m11) / det,(m20 * m01 - m00 * m21) / det,(m00 * m11 - m10 * m01) / det,(m00 * (m21 * m13 - m11 * m23) + m01 * (m10 * m23 - m20 * m13) - m03 * (m10 * m21 - m20 * m11)) / det);
}
| Computes the inverse affine transform. |
public Instrumenter attachAdaptiveTimeContinuationCollector(){
includeAdaptiveTimeContinuation=true;
return this;
}
| Includes the adaptive time continuation collector when instrumenting algorithms. |
public void push(final int value){
if (value >= -1 && value <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + value);
}
else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
mv.visitIntInsn(Opcodes.BIPUSH,value);
}
else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
mv.visitIntInsn(Opcodes.SIPUSH,value);
}
else {
mv.visitLdcInsn(value);
}
}
| Generates the instruction to push the given value on the stack. |
protected void handleENumValChildren(Element e,EnumVariableValue var){
List<Element> local=e.getChildren();
for (int k=0; k < local.size(); k++) {
Element el=local.get(k);
if (el.getName().equals("enumChoice")) {
Attribute valAttr=el.getAttribute("value");
if (valAttr == null) {
var.addItem(LocaleSelector.getAttribute(el,"choice"));
}
else {
var.addItem(LocaleSelector.getAttribute(el,"choice"),Integer.parseInt(valAttr.getValue()));
}
}
else if (el.getName().equals("enumChoiceGroup")) {
var.startGroup(LocaleSelector.getAttribute(el,"name"));
handleENumValChildren(el,var);
var.endGroup();
}
}
}
| Recursively walk the child enumChoice elements, working through the enumChoiceGroup elements as needed. |
public void resetOriginals(){
mStartingStartTrim=0;
mStartingEndTrim=0;
mStartingRotation=0;
setStartTrim(0);
setEndTrim(0);
setRotation(0);
}
| Reset the progress spinner to default rotation, start and end angles. |
public void put(Object key,Object value){
if (hints != null) {
hints.put(key,value);
}
}
| Set RenderingHint on this object. |
public boolean contains(Object o){
if (o == null) return false;
int mask=elements.length - 1;
int i=head;
Object x;
while ((x=elements[i]) != null) {
if (o.equals(x)) return true;
i=(i + 1) & mask;
}
return false;
}
| Returns <tt>true</tt> if this deque contains the specified element. More formally, returns <tt>true</tt> if and only if this deque contains at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. |
public void addCertificates(Store certStore) throws CMSException {
certs.addAll(CMSUtils.getCertificatesFromStore(certStore));
}
| Add the certificates in certStore to the certificate set to be included with the generated SignedData message. |
public int compareTo(Boolean that){
return compare(value,that.value);
}
| Compares this object to the specified boolean object to determine their relative order. |
public final AlertDialog initiateScan(int cameraId){
return initiateScan(ALL_CODE_TYPES,cameraId);
}
| Initiates a scan for all known barcode types with the specified camera. |
public MutablePeriod(long startInstant,long endInstant,Chronology chrono){
super(startInstant,endInstant,null,chrono);
}
| Creates a period from the given interval endpoints using the standard set of fields. |
public final RealMatrix procrustinate(RealMatrix X){
if (X.getRowDimension() != rowDimension) {
throw new IllegalArgumentException("X does not have the expected number of rows");
}
if (X.getColumnDimension() != columnDimension) {
throw new IllegalArgumentException("X does not have the expected number of columns");
}
RealMatrix tt=new Array2DRowRealMatrix(rowDimension,columnDimension);
for (int i=0; i < rowDimension; i++) {
tt.setRowMatrix(i,T.transpose());
}
return X.multiply(R).scalarMultiply(s).add(tt);
}
| procrustinate the complete matrix of coordinates |
public Instant withDurationAdded(long durationToAdd,int scalar){
if (durationToAdd == 0 || scalar == 0) {
return this;
}
long instant=getChronology().add(getMillis(),durationToAdd,scalar);
return withMillis(instant);
}
| Gets a copy of this instant with the specified duration added. <p> If the addition is zero, then <code>this</code> is returned. |
public InspectableFileCachedInputStream(final int bufferSize) throws IOException {
this(bufferSize,null);
}
| Creates a new instance with specified buffer size and default overflow-file directory. |
public Builder addFormDataPart(String name,String value){
return addPart(Part.createFormData(name,value));
}
| Add a form data part to the body. |
public Object extractMin(){
int numElem=this.numElem;
Object[] objects=this.objects;
double[] keys=this.keys;
if (numElem == 0) return null;
keys[1 - 1]=keys[numElem - 1];
keys[numElem - 1]=0;
Object result=objects[1 - 1];
objects[1 - 1]=objects[numElem - 1];
objects[numElem - 1]=null;
numElem--;
heapify(1,numElem);
this.numElem=numElem;
return result;
}
| Removes the minimum element and its key from the heap, and returns the minimum element. Will return null if the heap is empty |
public boolean isActive(){
return active;
}
| Gets the value of the active property. |
protected void processOtherEvent(SimEvent ev){
if (ev == null) {
Log.printConcatLine(getName(),".processOtherEvent(): Error - an event is null.");
}
}
| Here all the method related to VM requests will be received and forwarded to the related method. |
public DoubleConverter(final Object defaultValue){
super(true,defaultValue);
}
| Construct a <b>java.lang.Double</b> <i>Converter</i> that returns a default value if an error occurs. |
public PdxFieldAlreadyExistsException(String message){
super(message);
}
| Constructs a new exception with the given message. |
public void restart(BackgroundTask<T,V> task){
cancel();
this.task=task;
taskHandler=backgroundWorker.handle(task);
taskHandler.execute();
}
| Cancel running task if there is at the moment. Launch new task specified as parameter. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case GamlPackage.UNIT_NAME__REF:
return ref != null;
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean removeCheckedMessage(){
SQLiteDatabase db=getWritableDatabase();
if (db != null) {
db.execSQL("UPDATE " + TABLE + " SET "+ COL_DELETED+ "="+ TRUE+ " WHERE "+ COL_CHECKED+ "="+ TRUE+ ";");
return true;
}
log.debug("Message not added to store, database is null.");
return false;
}
| Remove the given all checked messages from the store, the message data is retained with its deleted state set to true. |
public boolean isEmpty(){
return count == 0;
}
| <p>Tests if this hashtable maps no keys to values.</p> |
@Timed @ExceptionMetered @GET @Path("{name}/clients") @Produces(APPLICATION_JSON) public Set<Client> clientDetailForGroup(@Auth AutomationClient automationClient,@PathParam("name") String name){
Group group=groupDAO.getGroup(name).orElseThrow(null);
return aclDAO.getClientsFor(group);
}
| Retrieve metadata for clients in a particular group. |
protected void paintDeterminate(Graphics g,JComponent c){
if (!(g instanceof Graphics2D)) {
return;
}
if (isUseParentPaint()) {
super.paintDeterminate(g,c);
return;
}
Insets b=progressBar.getInsets();
int barRectWidth=progressBar.getWidth() - (b.right + b.left);
int barRectHeight=progressBar.getHeight() - (b.top + b.bottom);
paintProgressBarBgImpl(progressBar.getOrientation() == JProgressBar.HORIZONTAL,g,b,barRectWidth,barRectHeight);
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
int amountFull=getAmountFull(b,barRectWidth,barRectHeight);
Graphics2D g2=(Graphics2D)g;
g2.setColor(progressBar.getForeground());
if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
if (WinUtils.isLeftToRight(c)) {
paintProgressBarContentImpl(true,g,b.left,b.top,amountFull,barRectHeight,-1);
}
else {
paintProgressBarContentImpl(true,g,barRectWidth + b.left,b.top,barRectWidth + b.left - amountFull,barRectHeight,-1);
}
}
else {
paintProgressBarContentImpl(false,g,b.left,b.top + barRectHeight - amountFull,barRectWidth,amountFull,barRectHeight);
}
if (progressBar.isStringPainted()) {
paintString(g,b.left,b.top,barRectWidth,barRectHeight,amountFull,b);
}
}
| All purpose paint method that should do the right thing for almost all linear, determinate progress bars. By setting a few values in the defaults table, things should work just fine to paint your progress bar. Naturally, override this if you are making a circular or semi-circular progress bar. |
private void emitHeader(ArrayList<PositionList.Entry> sortedPositions,ArrayList<LocalList.Entry> methodArgs) throws IOException {
boolean annotate=(annotateTo != null) || (debugPrint != null);
int mark=output.getCursor();
if (sortedPositions.size() > 0) {
PositionList.Entry entry=sortedPositions.get(0);
line=entry.getPosition().getLine();
}
output.writeUleb128(line);
if (annotate) {
annotate(output.getCursor() - mark,"line_start: " + line);
}
int curParam=getParamBase();
StdTypeList paramTypes=desc.getParameterTypes();
int szParamTypes=paramTypes.size();
if (!isStatic) {
for ( LocalList.Entry arg : methodArgs) {
if (curParam == arg.getRegister()) {
lastEntryForReg[curParam]=arg;
break;
}
}
curParam++;
}
mark=output.getCursor();
output.writeUleb128(szParamTypes);
if (annotate) {
annotate(output.getCursor() - mark,String.format("parameters_size: %04x",szParamTypes));
}
for (int i=0; i < szParamTypes; i++) {
Type pt=paramTypes.get(i);
LocalList.Entry found=null;
mark=output.getCursor();
for ( LocalList.Entry arg : methodArgs) {
if (curParam == arg.getRegister()) {
found=arg;
if (arg.getSignature() != null) {
emitStringIndex(null);
}
else {
emitStringIndex(arg.getName());
}
lastEntryForReg[curParam]=arg;
break;
}
}
if (found == null) {
emitStringIndex(null);
}
if (annotate) {
String parameterName=(found == null || found.getSignature() != null) ? "<unnamed>" : found.getName().toHuman();
annotate(output.getCursor() - mark,"parameter " + parameterName + " "+ RegisterSpec.PREFIX+ curParam);
}
curParam+=pt.getCategory();
}
for ( LocalList.Entry arg : lastEntryForReg) {
if (arg == null) {
continue;
}
CstString signature=arg.getSignature();
if (signature != null) {
emitLocalStartExtended(arg);
}
}
}
| Emits the header sequence, which consists of LEB128-encoded initial line number and string indicies for names of all non-"this" arguments. |
@Timed @ExceptionMetered @DELETE @Path("{name}") public Response deleteClient(@Auth AutomationClient automationClient,@PathParam("name") String name){
Client client=clientDAO.getClient(name).orElseThrow(null);
clientDAO.deleteClient(client);
auditLog.recordEvent(new Event(Instant.now(),EventTag.CLIENT_DELETE,automationClient.getName(),client.getName()));
return Response.noContent().build();
}
| Delete a client |
public static boolean equals(Object[] array1,Object[] array2){
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i=0; i < array1.length; i++) {
Object e1=array1[i], e2=array2[i];
if (!(e1 == null ? e2 == null : e1.equals(e2))) {
return false;
}
}
return true;
}
| Compares the two arrays. |
public static void writeByteArrayToFile(File file,byte[] data) throws IOException {
writeByteArrayToFile(file,data,false);
}
| Writes a byte array to a file creating the file if it does not exist. <p> NOTE: As from v1.3, the parent directories of the file will be created if they do not exist. |
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent){
if (sLogger.isActivated()) {
sLogger.debug("Dialog terminated");
}
}
| Process an asynchronously reported DialogTerminatedEvent |
public static String toString(DBIDs ids){
if (ids instanceof DBID) {
return DBIDFactory.FACTORY.toString((DBID)ids);
}
StringBuilder buf=new StringBuilder();
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(DBIDFactory.FACTORY.toString(iter));
}
return buf.toString();
}
| Format a DBID as string. |
public static void append(Path file,Reader reader,boolean writeBom) throws IOException {
appendBuffered(file,reader,Charset.defaultCharset().name(),writeBom);
}
| Append the text supplied by the Reader at the end of the File, using a specified encoding. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), <code>writeBom</code> is <code>true</code>, and the file doesn't already exist, the requisite byte order mark is written to the file before the text is appended. |
public void addIDCondition(String id){
_specificityB++;
addCondition(Condition.createIDCondition(id));
}
| the CSS condition #ID |
public double[] distributionForInstance(Instance instance) throws Exception {
int num_classes=(int)(snumClasses);
double[] ranking=new double[num_classes];
SortPair[] sortedActivations=ARTActivateCategories(instance);
java.util.Arrays.sort(sortedActivations);
double s0=sortedActivations[0].getValue();
double diff_act=s0 - sortedActivations[numCategories - 2].getValue();
int largest_activ=1;
double activ_change=0;
for (int i=1; i < sortedActivations.length; i++) {
activ_change=(s0 - sortedActivations[i].getValue()) / s0;
if (activ_change > threshold * diff_act) {
break;
}
largest_activ=largest_activ + 1;
}
double[] best_matches=new double[largest_activ];
java.util.Arrays.fill(best_matches,1);
best_matches[0]=s0;
for (int i=1; i < largest_activ; i++) {
best_matches[i]=sortedActivations[i].getValue();
}
double sum_mat=sumArray(best_matches);
int currentCategory=0;
this.neuronsactivated=new int[largest_activ];
this.neuronsactivity=new double[largest_activ];
for (int i=0; i < largest_activ; i++) {
this.neuronsactivity[i]=best_matches[i];
best_matches[i]=best_matches[i] / sum_mat;
currentCategory=sortedActivations[i].getOriginalIndex();
this.neuronsactivated[i]=currentCategory;
int[] s1=weightsB[currentCategory].getKeys();
int sit=weightsB[currentCategory].size();
int j=0;
for (int jt=0; jt < sit; jt++) {
j=s1[jt];
ranking[j]=ranking[j] + best_matches[i] * (Double)weightsB[currentCategory].get(j);
}
}
this.nrinstclassified+=1;
if (m_userankstoclass) {
return ARAMm_Ranking2Class(ranking);
}
return ranking;
}
| Calculates the class membership probabilities for the given test instance. |
private int validate(File file) throws IOException {
MatrixReader reader=null;
try {
reader=new MatrixReader(file);
int count=0;
while (reader.hasNext()) {
if (reader.next().length > index) {
count++;
}
else {
break;
}
}
if (count % (2 * P + 2) != 0) {
System.err.println(file + " is incomplete");
}
return count / (2 * P + 2);
}
finally {
if (reader != null) {
reader.close();
}
}
}
| Ensures the model output file contains N*(2P+2) lines and returns N, the number of samples. |
public static void trace(String method,String fileName,Object o){
if (SysProperties.TRACE_IO) {
System.out.println("IOUtils." + method + " "+ fileName+ " "+ o);
}
}
| Trace input or output operations if enabled. |
public BurlapRuntimeException(String message,Throwable rootCause){
super(message);
this.rootCause=rootCause;
}
| Create the exception. |
private int calculateOptimalCacheCharsThreshold(int numTermVectors,int numPostings){
if (numPostings == 0 && numTermVectors == 0) {
return 0;
}
else if (numTermVectors >= 2) {
return 0;
}
else {
return getCacheFieldValCharsThreshold();
}
}
| When cacheCharsThreshold is 0, loadFieldValues() only fetches one document at a time. We override it to be 0 in two circumstances: |
public void create() throws IOException {
folder=createTemporaryFolderIn(parentFolder);
}
| for testing purposes only. Do not use. |
private boolean updateAnchorFromChildren(RecyclerView.State state,AnchorInfo anchorInfo){
if (getChildCount() == 0) {
return false;
}
final View focused=getFocusedChild();
if (focused != null && anchorInfo.isViewValidAsAnchor(focused,state)) {
anchorInfo.assignFromViewAndKeepVisibleRect(focused);
return true;
}
View referenceChild=anchorInfo.mLayoutFromEnd ? findReferenceChildClosestToEnd(state) : findReferenceChildClosestToStart(state);
if (referenceChild != null) {
anchorInfo.assignFromView(referenceChild);
if (!state.isPreLayout() && supportsPredictiveItemAnimations()) {
final boolean notVisible=mOrientationHelper.getDecoratedStart(referenceChild) >= mOrientationHelper.getEndAfterPadding() || mOrientationHelper.getDecoratedEnd(referenceChild) < mOrientationHelper.getStartAfterPadding();
if (notVisible) {
anchorInfo.mCoordinate=anchorInfo.mLayoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding();
}
}
return true;
}
return false;
}
| Finds an anchor child from existing Views. Most of the time, this is the view closest to start or end that has a valid position (e.g. not removed). <p> If a child has focus, it is given priority. |
@SuppressWarnings("rawtypes") public Iterator<T> preorder(){
if (root == null) {
return empty();
}
return new ValueExtractor<T>(new PreorderTraversal(root));
}
| Use pre-order traversal over the tree. |
public void update(final double key,final U value){
update(Util.doubleToLongArray(key),value);
}
| Updates this sketch with a double key and U value. The value is passed to update() method of the Summary object associated with the key |
public void write(String text,int offset,int length){
buffer.append(text.substring(offset,offset + length));
}
| Write a portion of a string. |
public boolean endpointIsDiscovered(String key){
String value=getEndpointsMap().get(key.toUpperCase());
if (value == null) {
return false;
}
return new Boolean(value);
}
| Returns true if the endpoint specified was discovered |
@Override public void executionUnitImported(final ExecutionUnit process,final Element element){
NodeList children=element.getChildNodes();
children=element.getChildNodes();
for (int i=0; i < children.getLength(); i++) {
Node child=children.item(i);
if (child instanceof Element) {
Element backgroundElement=(Element)child;
if (XML_TAG_BACKGROUND.equals(backgroundElement.getTagName())) {
String xStr=backgroundElement.getAttribute(XML_ATTRIBUTE_X_POSITION);
String yStr=backgroundElement.getAttribute(XML_ATTRIBUTE_Y_POSITION);
String wStr=backgroundElement.getAttribute(XML_ATTRIBUTE_WIDTH);
String hStr=backgroundElement.getAttribute(XML_ATTRIBUTE_HEIGHT);
String imgLocStr=backgroundElement.getAttribute(XML_ATTRIBUTE_LOCATION);
try {
int xLoc=Integer.parseInt(xStr);
int yLoc=Integer.parseInt(yStr);
int wLoc=Integer.parseInt(wStr);
int hLoc=Integer.parseInt(hStr);
ProcessBackgroundImage bgImg=new ProcessBackgroundImage(xLoc,yLoc,wLoc,hLoc,imgLocStr,process);
setBackgroundImage(bgImg);
}
catch ( NullPointerException|IllegalArgumentException e) {
}
}
}
}
}
| Extracts port spacings from the XML element. |
public boolean init(){
BufferedReader fin=null;
String modelFile=taggerOpt.modelDir + File.separator + taggerOpt.modelFile;
try {
fin=new BufferedReader(new InputStreamReader(new FileInputStream(modelFile),"UTF-8"));
taggerMaps.readCpMaps(fin);
System.gc();
taggerMaps.readLbMaps(fin);
System.gc();
taggerDict.readDict(fin);
System.gc();
taggerFGen.readFeatures(fin);
System.gc();
fin.close();
}
catch ( IOException e) {
System.out.println("Couldn't open model file: " + modelFile);
System.out.println(e.toString());
return false;
}
if (lambda == null) {
int numFeatures=taggerFGen.numFeatures();
lambda=new double[numFeatures];
for (int i=0; i < numFeatures; i++) {
Feature f=(Feature)taggerFGen.features.get(i);
lambda[f.idx]=f.wgt;
}
}
if (taggerVtb != null) {
taggerVtb.init(this);
}
return true;
}
| Inits the. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
@Override final public boolean isKeys(){
return true;
}
| Instances are searchable and support duplicate keys. |
public RuntimeMBeanException(java.lang.RuntimeException e){
super();
runtimeException=e;
}
| Creates a <CODE>RuntimeMBeanException</CODE> that wraps the actual <CODE>java.lang.RuntimeException</CODE>. |
public static File convertToRelativePath(File absolute) throws Exception {
File result;
String fileStr;
result=null;
if (File.separator.equals("\\")) {
try {
fileStr=absolute.getPath();
fileStr=fileStr.substring(0,1).toLowerCase() + fileStr.substring(1);
result=createRelativePath(new File(fileStr));
}
catch ( Exception e) {
result=createRelativePath(absolute);
}
}
else {
result=createRelativePath(absolute);
}
return result;
}
| Converts a File's absolute path to a path relative to the user (ie start) directory. Includes an additional workaround for Cygwin, which doesn't like upper case drive letters. |
public void updateRecordSoft(int id) throws IOException {
if (!database.isOpen()) throw new IllegalStateException("don't access the table before opening the database");
if (hardWriteMode) throw new IllegalStateException("soft write attempted during hard write mode");
if (id > lastTransactionInsertId) throw new IllegalStateException("attempt to update a row past the last inserted row");
if (id >= committedNextRowId) return;
if (softModeSavedRows.get(id,false)) return;
softModeSavedRows.put(id,true);
synchronized (this) {
getRecord(tempRecordData,id);
}
Util.writeInt(rollBackOut,id);
rollBackOut.write(tempRecordData);
}
| Both a soft write and a hard write must be done in order to update a record. All soft writes for a transaction must be done, then a soft commit and finally hard writes are performed. Hard writes must write to the same rows that the soft writes did. |
private synchronized void reinitialize(){
if (plot == null) {
initializePlot();
}
else {
final ActionEvent ev=new ActionEvent(this,ActionEvent.ACTION_PERFORMED,OVERVIEW_REFRESHING);
for ( ActionListener actionListener : actionListeners) {
actionListener.actionPerformed(ev);
}
}
for ( Pair<Element,Visualization> pair : vistoelem.values()) {
SVGUtil.removeFromParent(pair.first);
}
plotmap=arrangeVisualizations(ratio,1.0);
recalcViewbox();
final int thumbsize=(int)Math.max(screenwidth / plotmap.getWidth(),screenheight / plotmap.getHeight());
LayerMap oldlayers=vistoelem;
vistoelem=new LayerMap();
SVGUtil.removeFromParent(plotlayer);
SVGUtil.removeFromParent(hoverlayer);
plotlayer=plot.svgElement(SVGConstants.SVG_G_TAG);
hoverlayer=plot.svgElement(SVGConstants.SVG_G_TAG);
hoverlayer.setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE,SVGPlot.NO_EXPORT_ATTRIBUTE);
for ( Entry<PlotItem,double[]> e : plotmap.entrySet()) {
final double basex=e.getValue()[0];
final double basey=e.getValue()[1];
for (Iterator<PlotItem> iter=e.getKey().itemIterator(); iter.hasNext(); ) {
PlotItem it=iter.next();
boolean hasDetails=false;
Element g=plot.svgElement(SVGConstants.SVG_G_TAG);
SVGUtil.setAtt(g,SVGConstants.SVG_TRANSFORM_ATTRIBUTE,"translate(" + (basex + it.x) + " "+ (basey + it.y)+ ")");
plotlayer.appendChild(g);
vistoelem.put(it,null,g,null);
for ( VisualizationTask task : it.tasks) {
if (!visibleInOverview(task)) {
continue;
}
hasDetails|=!task.hasAnyFlags(VisualizationTask.FLAG_NO_DETAIL);
Pair<Element,Visualization> pair=oldlayers.remove(it,task);
if (pair == null) {
pair=new Pair<>(null,null);
pair.first=plot.svgElement(SVGConstants.SVG_G_TAG);
}
if (pair.second == null) {
pair.second=embedOrThumbnail(thumbsize,it,task,pair.first);
}
g.appendChild(pair.first);
vistoelem.put(it,task,pair);
}
if (hasDetails && !single) {
Element hover=plot.svgRect(basex + it.x,basey + it.y,it.w,it.h);
SVGUtil.addCSSClass(hover,selcss.getName());
EventTarget targ=(EventTarget)hover;
targ.addEventListener(SVGConstants.SVG_MOUSEOVER_EVENT_TYPE,hoverer,false);
targ.addEventListener(SVGConstants.SVG_MOUSEOUT_EVENT_TYPE,hoverer,false);
targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE,hoverer,false);
targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE,new SelectPlotEvent(it),false);
hoverlayer.appendChild(hover);
}
}
}
for ( Pair<Element,Visualization> pair : oldlayers.values()) {
if (pair.second != null) {
pair.second.destroy();
}
}
plot.getRoot().appendChild(plotlayer);
plot.getRoot().appendChild(hoverlayer);
plot.updateStyleElement();
final ActionEvent ev=new ActionEvent(this,ActionEvent.ACTION_PERFORMED,OVERVIEW_REFRESHED);
for ( ActionListener actionListener : actionListeners) {
actionListener.actionPerformed(ev);
}
}
| Refresh the overview plot. |
public final int actualNumClasses(int bagIndex){
int returnValue=0;
int i;
for (i=0; i < m_perClass.length; i++) {
if (Utils.gr(m_perClassPerBag[bagIndex][i],0)) {
returnValue++;
}
}
return returnValue;
}
| Returns number of classes actually occuring in given bag. |
private int scanForEqualItem(final int pStart,final int pEnd,final int pGuess,final T pItem,final boolean pReturnSequenceEndIfNoEqualItemFound){
int i=pGuess - 1;
while ((i >= pStart) && (pItem.compareTo(this.mList.get(i)) == 0)) {
i--;
}
i++;
while (i < pEnd) {
final T item=this.mList.get(i);
if (i <= pGuess) {
if (pItem.equals(item)) {
return i;
}
}
else {
if (pItem.compareTo(item) == 0) {
if (pItem.equals(item)) {
return i;
}
}
else {
return ListUtils.encodeInsertionIndex(i);
}
}
i++;
}
if (pReturnSequenceEndIfNoEqualItemFound) {
return i;
}
else {
return SortedList.INDEX_INVALID;
}
}
| Scans for items around <code>pGuess</code> that fulfill <code>pItem.compareTo(item) == 0</code> and starting from the leftmost found, it returns the index of the first one that fulfills <code>pItem.equals(item)</code>. |
private String[] parseCommand(String command){
if (command.startsWith("search")) {
return command.trim().split(" ",2);
}
else if (command.startsWith("create")) {
return command.trim().split(" ",3);
}
else if (command.startsWith("upload")) {
return command.trim().split(" ",3);
}
return command.trim().split(" ");
}
| Parses the command entered by the user into individual arguments. |
public void addFrame(CCSpriteFrame frame){
frames_.add(frame);
}
| Adds a frame to a CCAnimation. |
private void layoutFrame(){
frame.setTitle(Messages.getString("MegaMek.SkinEditor.label") + Messages.getString("ClientGUI.clientTitleSuffix"));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(this,BorderLayout.CENTER);
frame.validate();
}
| Lays out the frame by setting this Client object to take up the full frame display area. |
@SuppressWarnings("unchecked") public static <T extends Packet>void registerOutListener(final Class<T> type,Player player,Predicate<T> listener){
NetworkManagerWrapper wrapper=wrapNetworkManager(player);
wrapper.registerOutgoingListener(type,listener);
}
| Register a listener for an incoming packet type. The type may be abstract. The listeners registered will be fired in the inverse order that they were registered; last fired first, and the first fired last (with the default server handler last). Listeners that return false will not fire any other handlers afterwards. Also, remember packets are handled in a separate thread! Make sure to use schedulers if you need to call Bukkit-related code, or just synchronize your listener implementation (avoid blocking). This method also requires that the player's network manager to be wrapper first. If it is not already wrapped, this will be done first. This only works for outgoing (client-bound) packets. |
public int maximumGap(int[] num){
if (num == null || num.length < 2) return 0;
int n=num.length;
int min=num[0];
int max=num[0];
for ( int i : num) {
max=Math.max(max,i);
min=Math.min(min,i);
}
double dist=(double)(max - min) / (n - 1);
int[] uppers=new int[n - 1];
int[] lowers=new int[n - 1];
Arrays.fill(uppers,-1);
Arrays.fill(lowers,-1);
for ( int i : num) {
int idx=(i == max ? n - 2 : (int)((i - min) / dist));
if (lowers[idx] == -1 || i < lowers[idx]) lowers[idx]=i;
if (uppers[idx] == -1 || i > uppers[idx]) uppers[idx]=i;
}
int prevUpper=uppers[0];
int maxGap=uppers[0] - lowers[0];
for (int i=1; i < n - 1; i++) {
if (lowers[i] == -1) continue;
maxGap=Math.max(maxGap,lowers[i] - prevUpper);
prevUpper=uppers[i];
}
return maxGap;
}
| O(n) Time, O(n) Space Find max and min in one traverse Calculate bucket length and divide numbers into buckets Traverse buckets to find max gap |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
@Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_webview);
mPullRefreshWebView=(PullToRefreshWebView)findViewById(R.id.pull_refresh_webview);
mWebView=mPullRefreshWebView.getRefreshableView();
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new SampleWebViewClient());
mWebView.loadUrl("http://www.google.com");
}
| Called when the activity is first created. |
private void calculateItemFittingMetadata(int width){
int maxNumItemsPerRow=mMaxItemsPerRow;
int numItems=getChildCount();
for (int i=0; i < numItems; i++) {
LayoutParams lp=(LayoutParams)getChildAt(i).getLayoutParams();
lp.maxNumItemsOnRow=1;
for (int curNumItemsPerRow=maxNumItemsPerRow; curNumItemsPerRow > 0; curNumItemsPerRow--) {
if (lp.desiredWidth < width / curNumItemsPerRow) {
lp.maxNumItemsOnRow=curNumItemsPerRow;
break;
}
}
}
}
| For each item, calculates the most dense row that fully shows the item's title. |
public boolean releaseRow(int row){
if (row < 0) {
return false;
}
else if (m_openrows != null && m_openrows.containsKey(row)) {
return false;
}
else if (row == m_curid) {
--m_curid;
}
else if (row == m_firstid) {
++m_firstid;
}
else {
if (m_openrows == null) m_openrows=new IntIntTreeMap(false);
m_openrows.put(row,row);
}
return true;
}
| Release a row and mark it as free. |
protected void addReactionPropertyDescriptor(Object object){
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),getResourceLocator(),getString("_UI_ReactionFired_reaction_feature"),getString("_UI_PropertyDescriptor_description","_UI_ReactionFired_reaction_feature","_UI_ReactionFired_type"),SexecPackage.Literals.REACTION_FIRED__REACTION,true,false,true,null,null,null));
}
| This adds a property descriptor for the Reaction feature. <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int[] numbers=new int[5];
System.out.print("Enter five numbers: ");
for (int i=0; i < numbers.length; i++) {
numbers[i]=input.nextInt();
}
System.out.println("The greatest common divisor is " + gcd(numbers));
}
| Main method |
public int addHistogramPlot(String name,Color color,double[] sample,int n){
return ((Plot2DCanvas)plotCanvas).addHistogramPlot(name,color,sample,n);
}
| Adds a plot of the statistical repartition of a sample, as a histogram. |
public String go(){
StringWriter sw=new StringWriter();
try {
go(sw);
}
catch ( IOException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
| Writes the iCalendar objects to a string. |
public static String normalizeUnsignedLong(String value){
return normalizeIntegerValue(value,"0","18446744073709551615");
}
| Normalizes an xsd:unsignedLong. |
public ReceiveMessageResult receiveMessage(String queueUrl){
ReceiveMessageRequest receiveMessageRequest=new ReceiveMessageRequest(queueUrl);
return receiveMessage(receiveMessageRequest);
}
| <p> Retrieves one or more messages, with a maximum limit of 10 messages, from the specified queue. Downloads the message payloads from Amazon S3 when necessary. Long poll support is enabled by using the <code>WaitTimeSeconds</code> parameter. For more information, see <a href= "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html" > Amazon SQS Long Poll </a> in the <i>Amazon SQS Developer Guide</i> . </p> <p> Short poll is the default behavior where a weighted random set of machines is sampled on a <code>ReceiveMessage</code> call. This means only the messages on the sampled machines are returned. If the number of messages in the queue is small (less than 1000), it is likely you will get fewer messages than you requested per <code>ReceiveMessage</code> call. If the number of messages in the queue is extremely small, you might not receive any messages in a particular <code>ReceiveMessage</code> response; in which case you should repeat the request. </p> <p> For each message returned, the response includes the following: </p> <ul> <li> <p> Message body </p> </li> <li> <p> MD5 digest of the message body. For information about MD5, go to <a href="http://www.faqs.org/rfcs/rfc1321.html"> http://www.faqs.org/rfcs/rfc1321.html </a> . </p> </li> <li> <p> Message ID you received when you sent the message to the queue. </p> </li> <li> <p> Receipt handle. </p> </li> <li> <p> Message attributes. </p> </li> <li> <p> MD5 digest of the message attributes. </p> </li> </ul> <p> The receipt handle is the identifier you must provide when deleting the message. For more information, see <a href= "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html" > Queue and Message Identifiers </a> in the <i>Amazon SQS Developer Guide</i> . </p> <p> You can provide the <code>VisibilityTimeout</code> parameter in your request, which will be applied to the messages that Amazon SQS returns in the response. If you do not include the parameter, the overall visibility timeout for the queue is used for the returned messages. For more information, see <a href= "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html" > Visibility Timeout </a> in the <i>Amazon SQS Developer Guide</i> . </p> <p> <b>NOTE:</b> Going forward, new attributes might be added. If you are writing code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully. </p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.