code
stringlengths
10
174k
nl
stringlengths
3
129k
public void testRestartWithNoDeployable() throws Exception { if ("glassfish4x".equals(getTestData().containerId)) { return; } if ("jonas4x".equals(getTestData().containerId)) { return; } setContainer(createContainer(createConfiguration(ConfigurationType.STANDALONE))); if (ContainerType.EMBEDDED.equals(getContainer().getType()) && getTestData().containerId.startsWith("jetty")) { return; } getLocalContainer().start(); assertEquals(State.STARTED,getContainer().getState()); getLocalContainer().restart(); assertEquals(State.STARTED,getContainer().getState()); getLocalContainer().stop(); assertEquals(State.STOPPED,getContainer().getState()); getLocalContainer().restart(); assertEquals(State.STARTED,getContainer().getState()); getLocalContainer().stop(); assertEquals(State.STOPPED,getContainer().getState()); }
Smoke test: startup with no deployable.
public void finer(CharSequence message,Throwable e){ log(Level.FINER,message,e); }
Log a message at the 'finer' debugging level. You should check isDebugging() before building the message.
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; String reclassFile=null; int row, col; float progress=0; double z, val; int i; double noData; boolean assignMode=false; boolean assignModeFound=false; boolean delimiterFound=false; double[][] reclassData=new double[0][0]; 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) { reclassFile=args[i]; } } if ((inputHeader == null) || (outputHeader == null) || (reclassFile == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster image=new WhiteboxRaster(inputHeader,"r"); int rows=image.getNumberRows(); int cols=image.getNumberColumns(); noData=image.getNoDataValue(); WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); output.setPreferredPalette(image.getPreferredPalette()); int numClasses=countLines(reclassFile); DataInputStream in=null; BufferedReader br=null; try { FileInputStream fstream=new FileInputStream(reclassFile); in=new DataInputStream(fstream); br=new BufferedReader(new InputStreamReader(in)); String delimiter="\t"; if (reclassFile != null) { String line; String[] str; if (!assignMode) { reclassData=new double[3][numClasses]; } else { reclassData=new double[2][numClasses]; } i=0; while ((line=br.readLine().trim()) != null) { str=line.split(delimiter); if (!delimiterFound) { if (str.length < 2) { delimiter=","; str=line.split(delimiter); if (str.length < 2) { delimiter=" "; str=line.split(delimiter); if (str.length < 2) { showFeedback("No recognizable delimiter in text file. Columns must " + "be seperated by tabs, commas, or spaces."); return; } else { delimiterFound=true; } } else { delimiterFound=true; } } else { delimiterFound=true; } } if (!assignModeFound) { if (str.length == 2) { assignMode=true; } else { assignMode=false; } assignModeFound=true; } if (!assignMode) { reclassData[0][i]=Double.parseDouble(str[0]); reclassData[1][i]=Double.parseDouble(str[1]); reclassData[2][i]=Double.parseDouble(str[2]); } else { reclassData[0][i]=Double.parseDouble(str[0]); reclassData[1][i]=Double.parseDouble(str[1]); } i++; } in.close(); br.close(); } } catch ( java.io.IOException e) { System.err.println("Error: " + e.getMessage()); } catch ( Exception e) { System.err.println("Error: " + e.getMessage()); } finally { try { if (in != null || br != null) { in.close(); br.close(); } } catch ( java.io.IOException ex) { } } if (!assignMode) { for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=image.getValue(row,col); if (z != noData) { val=noData; for (i=0; i < numClasses; i++) { if ((z >= reclassData[1][i]) && (z < reclassData[2][i])) { val=reclassData[0][i]; break; } } if (val != noData) { output.setValue(row,col,val); } else { output.setValue(row,col,z); } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } } else { for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=image.getValue(row,col); if (z != noData) { val=noData; for (i=0; i < numClasses; i++) { if ((z == reclassData[1][i])) { val=reclassData[0][i]; break; } if (val != noData) { output.setValue(row,col,val); } else { output.setValue(row,col,z); } } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } } image.close(); output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); output.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
protected <S extends PropertySource<?>>List<S> findPropertySources(Class<S> sourceClass){ List<S> managedSources=new LinkedList<>(); LinkedList<PropertySource<?>> sources=toLinkedList(environment.getPropertySources()); while (!sources.isEmpty()) { PropertySource<?> source=sources.pop(); if (source instanceof CompositePropertySource) { CompositePropertySource comp=(CompositePropertySource)source; sources.addAll(comp.getPropertySources()); } else if (sourceClass.isInstance(source)) { managedSources.add(sourceClass.cast(source)); } } return managedSources; }
Finds all registered property sources of the given type.
private synchronized long applyTermDeletes(CoalescedUpdates updates,SegmentState[] segStates) throws IOException { long startNS=System.nanoTime(); int numReaders=segStates.length; long delTermVisitedCount=0; long segTermVisitedCount=0; FieldTermIterator iter=updates.termIterator(); String field=null; SegmentQueue queue=null; BytesRef term; while ((term=iter.next()) != null) { if (iter.field() != field) { field=iter.field(); queue=new SegmentQueue(numReaders); long segTermCount=0; for (int i=0; i < numReaders; i++) { SegmentState state=segStates[i]; Terms terms=state.reader.fields().terms(field); if (terms != null) { segTermCount+=terms.size(); state.termsEnum=terms.iterator(); state.term=state.termsEnum.next(); if (state.term != null) { queue.add(state); } } } assert checkDeleteTerm(null); } assert checkDeleteTerm(term); delTermVisitedCount++; long delGen=iter.delGen(); while (queue.size() != 0) { SegmentState state=queue.top(); segTermVisitedCount++; int cmp=term.compareTo(state.term); if (cmp < 0) { break; } else if (cmp == 0) { } else { TermsEnum.SeekStatus status=state.termsEnum.seekCeil(term); if (status == TermsEnum.SeekStatus.FOUND) { } else { if (status == TermsEnum.SeekStatus.NOT_FOUND) { state.term=state.termsEnum.term(); queue.updateTop(); } else { queue.pop(); } continue; } } assert state.delGen != delGen; if (state.delGen < delGen) { final Bits acceptDocs=state.rld.getLiveDocs(); state.postingsEnum=state.termsEnum.postings(state.postingsEnum,PostingsEnum.NONE); assert state.postingsEnum != null; while (true) { final int docID=state.postingsEnum.nextDoc(); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (acceptDocs != null && acceptDocs.get(docID) == false) { continue; } if (!state.any) { state.rld.initWritableLiveDocs(); state.any=true; } state.rld.delete(docID); } } state.term=state.termsEnum.next(); if (state.term == null) { queue.pop(); } else { queue.updateTop(); } } } if (infoStream.isEnabled("BD")) { infoStream.message("BD",String.format(Locale.ROOT,"applyTermDeletes took %.1f msec for %d segments and %d packets; %d del terms visited; %d seg terms visited",(System.nanoTime() - startNS) / 1000000.,numReaders,updates.terms.size(),delTermVisitedCount,segTermVisitedCount)); } return delTermVisitedCount; }
Merge sorts the deleted terms and all segments to resolve terms to docIDs for deletion.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public static short parseShort(String string,int radix) throws NumberFormatException { int intValue=Integer.parseInt(string,radix); short result=(short)intValue; if (result == intValue) { return result; } throw new NumberFormatException("Value out of range for short: \"" + string + "\""); }
Parses the specified string as a signed short value using the specified radix. The ASCII character \u002d ('-') is recognized as the minus sign.
public void reply(NceReply r){ if (!r.isUnsolicited()) { int bits; synchronized (this) { bits=r.pollValue(); awaitingReply=false; this.notify(); } currentAIU.markChanges(bits); if (log.isDebugEnabled()) { String str=jmri.util.StringUtil.twoHexFromInt((bits >> 4) & 0xf); str+=" "; str=jmri.util.StringUtil.appendTwoHexFromInt(bits & 0xf,str); log.debug("sensor poll reply received: \"" + str + "\""); } } }
Process single received reply from sensor poll
public NavigationEvent(Navigator source,T valueOld,T valueNew){ this.source=source; this.valueOld=valueOld; this.valueNew=valueNew; }
Initializes a new instance.
public void addEntry(PutAllEntryData putAllEntry){ this.putAllData[this.putAllDataSize]=putAllEntry; this.putAllDataSize+=1; }
Add an entry that this putall operation should distribute.
private static ParseResults parseMimeType(String mimeType){ String[] parts=StringKit.split(mimeType,";"); ParseResults results=new ParseResults(); results.params=new HashMap<String,String>(); for (int i=1; i < parts.length; ++i) { String p=parts[i]; String[] subParts=StringKit.split(p,"="); if (subParts.length == 2) { results.params.put(subParts[0].trim(),subParts[1].trim()); } } String fullType=parts[0].trim(); if (fullType.equals("*")) { fullType="*/*"; } int slashIndex=fullType.indexOf('/'); if (slashIndex != -1) { results.type=fullType.substring(0,slashIndex); results.subType=fullType.substring(slashIndex + 1); } else { results.type=fullType; results.subType="*"; } return results; }
Carves up a mime-type and returns a ParseResults object For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'})
public static String keyString(SecretKeys keys){ return keys.toString(); }
Converts the given AES/HMAC keys into a base64 encoded string suitable for storage. Sister function of keys.
public SelectionDialog(Dialog owner,String key,int mode,Object[] arguments,List<String> optionsToSelect,List<String> optionsToCheck){ this(owner,key,mode,arguments); this.optionsToSelect=optionsToSelect; this.optionsToCheck=optionsToCheck; }
Constructs new dialog. Only sets object variables.
private String makeDeleteAllUrl() throws UnsupportedEncodingException { HttpSolrClient client=(HttpSolrClient)getSolrClient(); String deleteQuery="<delete><query>*:*</query></delete>"; return client.getBaseURL() + "/update?commit=true&stream.body=" + URLEncoder.encode(deleteQuery,"UTF-8"); }
Compose a url that if you get it, it will delete all the data.
public static boolean isEquals(Object actual,Object expected){ return actual == expected || (actual == null ? expected == null : actual.equals(expected)); }
compare two object
@Override public void clear(){ this._map.clear(); }
Empties the map.
public Piece(int magnitude){ this.magnitude=new BigDecimal(magnitude); this.unitType=PieceUnit.PC.getBaseUnit(); }
Create a new <code>Piece</code>.
public void removeFromTags(String removeTag){ tags.remove(removeTag); firePropertyChange(TAG,null,removeTag); firePropertyChange(TAGS_AS_STRING,null,removeTag); }
Removes the from tags.
@DSSafe(DSCat.ANDROID_CALLBACK) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:35:26.538 -0500",hash_original_method="A28646D8654C968065CCEE80C360B171",hash_generated_method="5BDF40E1FD876DCB9A201D9F7020DAE4") @Override public void onDestroyView(){ super.onDestroyView(); if (mDialog != null) { mViewDestroyed=true; mDialog.dismiss(); mDialog=null; } }
Remove dialog.
protected void notifyDataChangedEvent(){ if (datasetObservers != null) { for ( DataSetObserver observer : datasetObservers) { observer.onChanged(); } } }
Notifies observers about data changing
public boolean hasPurchase(String sku){ return mPurchaseMap.containsKey(sku); }
Returns whether or not there exists a purchase of the given product.
public static boolean isBookmarkInMobileBookmarksBranch(Context context,long nodeId){ Boolean result=chromeBrowserProviderCall(Boolean.class,ChromeBrowserProvider.CLIENT_API_IS_BOOKMARK_IN_MOBILE_BOOKMARKS_BRANCH,context,argsToBundle(nodeId)); return result != null ? result.booleanValue() : false; }
Checks if a bookmark node is in the Mobile Bookmarks folder branch.
public Object remove(int index){ Object o=opt(index); this.myArrayList.remove(index); return o; }
Remove an index and close the hole.
private void processIfCmp(Instruction s){ ValueGraphVertex v=new ValueGraphVertex(s); graph.addGraphNode(v); nameMap.put(s,v); v.setLabel(s.operator(),3); link(v,findOrCreateVertex(bypassMoves(IfCmp.getVal1(s))),0); link(v,findOrCreateVertex(bypassMoves(IfCmp.getVal2(s))),1); link(v,findOrCreateVertex(IfCmp.getCond(s)),2); }
Update the value graph to account for a given IfCmp instruction. <p><b>PRECONDITION:</b> <code> IfCmp.conforms(s); </code>
public void write(long x){ writeByte((int)((x >>> 56) & 0xff)); writeByte((int)((x >>> 48) & 0xff)); writeByte((int)((x >>> 40) & 0xff)); writeByte((int)((x >>> 32) & 0xff)); writeByte((int)((x >>> 24) & 0xff)); writeByte((int)((x >>> 16) & 0xff)); writeByte((int)((x >>> 8) & 0xff)); writeByte((int)((x >>> 0) & 0xff)); }
Writes the 64-bit long to the binary output stream.
public void install(ISelectionProvider selectionProvider){ if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider=(IPostSelectionProvider)selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } }
Installs this selection changed listener with the given selection provider. If the selection provider is a post selection provider, post selection changed events are the preferred choice, otherwise normal selection changed events are requested.
int compareTo(PageParamInfo other){ if (mFormula != null && other.mFormula == null) return 1; if (mFormula == null && other.mFormula != null) return -1; if (mType == other.mType) return 0; if (mType == Type.PAGE_NUMBER) return 1; if (other.mType == Type.PAGE_NUMBER) return -1; return 0; }
Evaluates which PageParamInfo is better based on the properties of PageParamInfo. We prefer the one if the list of PageLinkInfo forms a linear formula, see getLinearFormula(). Returns 1 if this is better, -1 if other is better and 0 if they are equal.
public void insertBack(Item x){ if (size == items.length) { resize(size * RFACTOR); } items[size]=x; size=size + 1; }
Inserts X into the back of the list.
private boolean holdsSinglePolyfillSource(PolyfillValidationState state){ EList<TMember> myPolyMember=state.polyType.getOwnedMembers(); XtextResource res=(XtextResource)state.polyType.eResource(); IResourceDescriptions index=resourceDescriptionsProvider.getResourceDescriptions(res); IContainer container=containerManager.getContainer(res.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(res),index); Iterable<IEObjectDescription> iterEObj=container.getExportedObjects(TypesPackage.Literals.TCLASSIFIER,N4TSQualifiedNameProvider.getPolyfillFQN(state.filledType,qualifiedNameProvider),false); ListMultimap<TMember,TModule> clashProviders=LinkedListMultimap.create(); for ( IEObjectDescription pivotObjectDescription : iterEObj) { EObject eob=pivotObjectDescription.getEObjectOrProxy(); if (eob.eIsProxy()) { eob=EcoreUtil.resolve(eob,res); } if (eob == state.polyType) { continue; } EList<TMember> pivotPolyMember=((TClassifier)eob).getOwnedMembers(); ListMultimap<TMember,TMember> clashing=findClashingMembersByName(myPolyMember,pivotPolyMember); for ( TMember myMember : clashing.keySet()) { clashProviders.put(myMember,clashing.get(myMember).get(0).getContainingModule()); } } List<TMember> sortedMembers=clashProviders.keySet().stream().sorted().collect(Collectors.toList()); for ( TMember myMember : sortedMembers) { String uris=Stream.concat(Stream.of(myMember.getContainingModule()),clashProviders.get(myMember).stream()).map(null).sorted().reduce("",null); if (uris.startsWith(PREFIX_LIST)) uris=uris.substring(PREFIX_LIST.length()); int lastPrefix_idx=uris.lastIndexOf(PREFIX_LIST); if (lastPrefix_idx >= 0) { StringBuffer sb=new StringBuffer(uris); uris=sb.replace(lastPrefix_idx,lastPrefix_idx + PREFIX_LIST.length()," and ").toString(); } String memberAxis=myMember.getContainingType().getName() + "." + myMember.getName(); String msg=IssueCodes.getMessageForCLF_POLYFILL_MULTIPOLYFILLS_MEMBER_CONFLICT(uris,memberAxis); state.host.addIssue(msg,myMember.getAstElement(),N4JSPackage.Literals.PROPERTY_NAME_OWNER__DECLARED_NAME,IssueCodes.CLF_POLYFILL_MULTIPOLYFILLS_MEMBER_CONFLICT); } return true; }
Constraints 129 (Applying Polyfills) No member must be filled by more than one polyfill.
public static <T>T checkNotNull(T reference){ if (reference == null) { throw new NullPointerException(); } return reference; }
Ensures that an object reference passed as a parameter to the calling method is not null.
public ValueModelUserLink(String name,ArrayListUserLink defaultValue){ super(name,defaultValue); }
Create ValueModel
public String toString(){ final String TAB=" "; StringBuffer retValue=new StringBuffer(); retValue.append("ConjunctionCriterion ( ").append("criteria = ").append(this.criteria).append(TAB).append("type = ").append(this.type).append(TAB).append(" )"); return retValue.toString(); }
Constructs a <code>String</code> with all attributes in name = value format.
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter,namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } }
Util method to write an attribute without the ns prefix
public static boolean isInArea(Coord coord,Coord[] area){ return (getCompassQuarter(area[0],coord) == 1 && getCompassQuarter(area[1],coord) == 3); }
Checks if a coordinate is in the area
public JSONObject putOpt(String key,Object value) throws JSONException { if (key != null && value != null) { put(key,value); } return this; }
Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.
public void testSerialization(){ LogFormat f1=new LogFormat(10.0,"10",true); LogFormat f2=(LogFormat)TestUtilities.serialised(f1); assertEquals(f1,f2); }
Serialize an instance, restore it, and check for equality.
public void addProcessListener(INodejsProcessListener listener){ synchronized (listeners) { listeners.add(listener); } }
Add the given process listener.
@Override protected void propertyChange(PropertyChangeEvent evt){ if (SynthLookAndFeel.shouldUpdateStyle(evt)) { updateStyle((JTextComponent)evt.getSource()); } super.propertyChange(evt); }
This method gets called when a bound property is changed on the associated JTextComponent. This is a hook which UI implementations may change to reflect how the UI displays bound properties of JTextComponent subclasses. This is implemented to rebuild the ActionMap based upon an EditorKit change.
protected void checkConsistency(){ for ( Collection<? extends ConfigGroup> sets : getParameterSets().values()) { for ( ConfigGroup set : sets) set.checkConsistency(); } }
Check if the set values go well together. This method is usually called after reading the configuration from a file. If an inconsistency is found, a warning or error should be issued and (optionally) a RuntimeException being thrown.
public void lookupTable(String[] values) throws IOException { writeCode(LOOKUP_TABLE); ByteArrayOutputStream baout=new ByteArrayOutputStream(); OutStream bout=new OutStream(baout); bout.writeUI16(values.length); for (int i=0; i < values.length; i++) { bout.writeString(values[i]); } bout.flush(); byte[] data=baout.toByteArray(); out.writeUI16(data.length); out.write(data); }
SWFActions interface
public CDumpAllWaiter(final IDebugger debugger,final IAddress offset,final int size){ m_debugger=Preconditions.checkNotNull(debugger,"IE01429: Debugger argument can not be null"); m_offset=Preconditions.checkNotNull(offset,"IE01430: Offset argument can not be null"); m_size=size; debugger.addListener(m_debuggerListener); debugger.getProcessManager().addListener(m_processListener); }
Creates a new waiter object.
private void bindPhoto(Bitmap bitmap){ if (bitmap != null) { if (mPhotoView != null) { mPhotoView.bindPhoto(bitmap); } enableImageTransforms(true); } }
Binds an image to the photo view.
public void put(int b){ put((byte)(b & 0xFF)); }
Writes the lowest 8 bits of the given int to this ByteBuffer, at the current position. Advances the current position by 1.
protected LiteralImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected void revalidate(){ valid=true; }
Initializes the list, if needed. Does nothing, since there is no attribute to read the list from.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
@NonNull public static Animator alpha(float alpha){ return alpha(alpha,0); }
Sets view alpha to specified value instantly
@Override public boolean equals(Object obj){ if (obj instanceof Video) { Video other=(Video)obj; return Objects.equal(name,other.name) && Objects.equal(url,other.url) && duration == other.duration; } else { return false; } }
Two Videos are considered equal if they have exactly the same values for their name, url, and duration.
public List transform(OrganoProductor[] organosProductores){ List ltOrganosProductores=new ArrayList(); if (organosProductores != null) { for (int i=0; i < organosProductores.length; i++) { OrganoProductor organoProductor=(OrganoProductor)organosProductores[i]; OrganoProductorImpl organoProductorImpl=new OrganoProductorImpl(organoProductor.getId(),organoProductor.getInicioProduccion()); ltOrganosProductores.add(organoProductorImpl); } } return ltOrganosProductores; }
Transforma una lista de organos productores procedentes del API en una lista de objetos que implemementan el interfaz de organos productores
private boolean parseZoneLine(Scanner s,List<TZDBZone> zoneList){ TZDBZone zone=new TZDBZone(); zoneList.add(zone); zone.standardOffset=parseOffset(s.next()); String savingsRule=parseOptional(s.next()); if (savingsRule == null) { zone.fixedSavingsSecs=0; zone.savingsRule=null; } else { try { zone.fixedSavingsSecs=parsePeriod(savingsRule); zone.savingsRule=null; } catch ( Exception ex) { zone.fixedSavingsSecs=null; zone.savingsRule=savingsRule; } } zone.text=s.next(); if (s.hasNext()) { zone.year=Integer.parseInt(s.next()); if (s.hasNext()) { parseMonthDayTime(s,zone); } return false; } else { return true; } }
Parses a Zone line.
protected VisualizePanel createPanel(Instances data) throws Exception { VisualizePanel result=new ThresholdVisualizePanel(); PlotData2D plot=new PlotData2D(data); plot.setPlotName("Micro-averaged Performance"); plot.m_displayAllPoints=true; boolean[] connectPoints=new boolean[data.numInstances()]; for (int cp=1; cp < connectPoints.length; cp++) connectPoints[cp]=true; plot.setConnectPoints(connectPoints); result.addPlot(plot); if (data.attribute(SAMPLES) != null) result.setXIndex(data.attribute(SAMPLES).index()); if (data.attribute(ACCURACY) != null) result.setYIndex(data.attribute(ACCURACY).index()); return result; }
Creates a panel displaying the data.
public Bundle onSaveInstanceState(){ Bundle bundle=new Bundle(); bundle.putBoolean(DIALOG_SHOWING_TAG,mShowing); if (mCreated) { bundle.putBundle(DIALOG_HIERARCHY_TAG,mWindow.saveHierarchyState()); } return bundle; }
Saves the state of the dialog into a bundle. The default implementation saves the state of its view hierarchy, so you'll likely want to call through to super if you override this to save additional state.
public static BoundThisTypeRef createBoundThisTypeRefStructural(ParameterizedTypeRef actualThisTypeRef,ThisTypeRefStructural thisTypeStructural){ if (actualThisTypeRef == null) { throw new NullPointerException("Actual this type must not be null!"); } BoundThisTypeRef boundThisTypeRef=TypeRefsFactory.eINSTANCE.createBoundThisTypeRef(); boundThisTypeRef.setActualThisTypeRef(TypeUtils.copyIfContained(actualThisTypeRef)); copyStructuralTypingInfo(boundThisTypeRef,thisTypeStructural); return boundThisTypeRef; }
Creates a new this type reference bound to the given actual type.
public Matrix3f rotationZYX(float angleZ,float angleY,float angleX){ float cosZ=(float)Math.cos(angleZ); float sinZ=(float)Math.sin(angleZ); float cosY=(float)Math.cos(angleY); float sinY=(float)Math.sin(angleY); float cosX=(float)Math.cos(angleX); float sinX=(float)Math.sin(angleX); float m_sinZ=-sinZ; float m_sinY=-sinY; float m_sinX=-sinX; float nm00=cosZ; float nm01=sinZ; float nm10=m_sinZ; float nm11=cosZ; float nm20=nm00 * sinY; float nm21=nm01 * sinY; float nm22=cosY; m00=nm00 * cosY; m01=nm01 * cosY; m02=m_sinY; m10=nm10 * cosX + nm20 * sinX; m11=nm11 * cosX + nm21 * sinX; m12=nm22 * sinX; m20=nm10 * m_sinX + nm20 * cosX; m21=nm11 * m_sinX + nm21 * cosX; m22=nm22 * cosX; return this; }
Set this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> This method is equivalent to calling: <tt>rotationZ(angleZ).rotateY(angleY).rotateX(angleX)</tt>
public ToStringBuilder append(String fieldName,short[] array,boolean fullDetail){ style.append(buffer,fieldName,array,BooleanUtils.toBooleanObject(fullDetail)); return this; }
<p>Append to the <code>toString</code> a <code>short</code> array.</p> <p>A boolean parameter controls the level of detail to show. Setting <code>true</code> will output the array in full. Setting <code>false</code> will output a summary, typically the size of the array.
public void add(BaseBlock... blocks){ for ( BaseBlock block : blocks) { add(block); } }
Add the given blocks to the list of criteria.
protected boolean beforeSave(boolean newRecord){ if (!isInstanceAttribute() && (isSerNo() || isLot() || isGuaranteeDate())) setIsInstanceAttribute(true); return true; }
Before Save. - set instance attribute flag
public PaymentChannelServerState(TransactionBroadcaster broadcaster,Wallet wallet,ECKey serverKey,long minExpireTime){ this.state=State.WAITING_FOR_REFUND_TRANSACTION; this.serverKey=checkNotNull(serverKey); this.wallet=checkNotNull(wallet); this.broadcaster=checkNotNull(broadcaster); this.minExpireTime=minExpireTime; }
Creates a new state object to track the server side of a payment channel.
public void commit(){ if (database != null) { lastModificationId=database.getNextModificationDataId(); } }
Mark the transaction as committed, so that the modification counter of the database is incremented.
public void testLastMessageAcked() throws JMSException { connection.start(); Session session=connection.createSession(false,ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); Queue queue=session.createQueue(getQueueName()); MessageProducer producer=session.createProducer(queue); TextMessage msg1=session.createTextMessage("msg1"); TextMessage msg2=session.createTextMessage("msg2"); TextMessage msg3=session.createTextMessage("msg3"); producer.send(msg1); producer.send(msg2); producer.send(msg3); MessageConsumer consumer=session.createConsumer(queue); Message msg=consumer.receive(1000); assertNotNull(msg); msg=consumer.receive(1000); assertNotNull(msg); msg=consumer.receive(1000); assertNotNull(msg); msg.acknowledge(); session.close(); session=connection.createSession(false,ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); consumer=session.createConsumer(queue); msg=consumer.receive(1000); assertNotNull(msg); assertEquals(msg1,msg); msg=consumer.receive(1000); assertNotNull(msg); assertEquals(msg2,msg); msg=consumer.receive(1000); assertNull(msg); session.close(); }
Tests if acknowledged messages are being consumed.
public boolean isAlwaysUpdateable(){ if (isVirtualColumn() || !m_vo.IsUpdateable) return false; return m_vo.IsAlwaysUpdateable; }
Is Always Updateable
public static String convertTime(int time){ time/=1000; int minute=time / 60; int second=time % 60; minute%=60; return String.format("%02d:%02d",minute,second); }
convert time str
protected synchronized void putJarTypeInfo(IJavaElement type,Object info){ this.cache.jarTypeCache.put(type,info); }
Remember the info for the jar binary type
protected boolean activateAccelerometer(){ if (mSensorManager != null && mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),(int)(mAccelerometerInterval * 1000.0f))) return true; PLLog.debug("PLView::activateAccelerometer","Accelerometer sensor is not available on the device!"); return false; }
accelerometer methods
public static void addEmojis(Context context,Spannable text,int emojiSize,int emojiAlignment,int textSize,int index,int length){ addEmojis(context,text,emojiSize,emojiAlignment,textSize,index,length,false); }
Convert emoji characters of the given Spannable to the according emojicon.
protected void notifyReceivedMsg(MqttWireMessage message) throws MqttException { final String methodName="notifyReceivedMsg"; this.lastInboundActivity=System.currentTimeMillis(); log.fine(CLASS_NAME,methodName,"651",new Object[]{new Integer(message.getMessageId()),message}); if (!quiescing) { if (message instanceof MqttPublish) { MqttPublish send=(MqttPublish)message; switch (send.getMessage().getQos()) { case 0: case 1: if (callback != null) { callback.messageArrived(send); } break; case 2: persistence.put(getReceivedPersistenceKey(message),(MqttPublish)message); inboundQoS2.put(new Integer(send.getMessageId()),send); this.send(new MqttPubRec(send),null); break; default : } } else if (message instanceof MqttPubRel) { MqttPublish sendMsg=(MqttPublish)inboundQoS2.get(new Integer(message.getMessageId())); if (sendMsg != null) { if (callback != null) { callback.messageArrived(sendMsg); } } else { MqttPubComp pubComp=new MqttPubComp(message.getMessageId()); this.send(pubComp,null); } } } }
Called by the CommsReceiver when a message has been received. Handles inbound messages and other flows such as PUBREL.
private void clearCache(){ getCacheForEntryById().clear(); getCacheForEntryByParentId().clear(); getCacheForDeletedEntries().clear(); getCacheForUserById().clear(); }
Clear the cache of records that have been created, modified or queried during the transaction.
public static boolean isRunningMacOSX(){ return System.getProperty("os.name").startsWith("Mac"); }
Determines whether the program is running in Windows.
public static void visitClassLiteral(MethodVisitor mv,ClassNode classNode){ if (ClassHelper.isPrimitiveType(classNode)) { mv.visitFieldInsn(GETSTATIC,getClassInternalName(ClassHelper.getWrapper(classNode)),"TYPE","Ljava/lang/Class;"); } else { mv.visitLdcInsn(org.objectweb.asm.Type.getType(getTypeDescription(classNode))); } }
Visits a class literal. If the type of the classnode is a primitive type, the generated bytecode will be a GETSTATIC Integer.TYPE. If the classnode is not a primitive type, we will generate a LDC instruction.
public boolean isPsuedoVarRef(){ java.lang.String ns=m_qname.getNamespaceURI(); if ((null != ns) && ns.equals(PSUEDOVARNAMESPACE)) { if (m_qname.getLocalName().startsWith("#")) return true; } return false; }
Tell if this is a psuedo variable reference, declared by Xalan instead of by the user.
public static boolean isSupplementaryCodePoint(int codePoint){ return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT && codePoint < MAX_CODE_POINT + 1; }
Determines whether the specified character (Unicode code point) is in the <a href="#supplementary">supplementary character</a> range.
public void updateAmountCost(){ if (movementQuantity.signum() > 0) { costDetail.setCostAmt(costDetail.getAmt().subtract(costDetail.getCostAdjustment())); costDetail.setCostAmtLL(costDetail.getAmtLL().subtract(costDetail.getCostAdjustmentLL())); } else if (movementQuantity.signum() < 0) { costDetail.setCostAmt(costDetail.getAmt().add(adjustCost)); costDetail.setCostAmtLL(costDetail.getAmtLL().add(adjustCostLowerLevel)); } costDetail.setCumulatedQty(getNewAccumulatedQuantity(lastCostDetail)); costDetail.setCumulatedAmt(getNewAccumulatedAmount(lastCostDetail)); final String idColumnName=CostEngine.getIDColumnName(model); costDetail.set_ValueOfColumn(idColumnName,CostEngine.getIDColumn(model)); if (model instanceof MInOutLine) { MInOutLine ioLine=(MInOutLine)model; costDetail.setC_OrderLine_ID(ioLine.getC_OrderLine_ID()); costDetail.setC_InvoiceLine_ID(0); } if (model instanceof MMatchInv && costDetail.getM_InOutLine_ID() == 0) { MMatchInv iMatch=(MMatchInv)model; costDetail.setM_InOutLine_ID(iMatch.getM_InOutLine_ID()); } if (model instanceof MMatchPO && costDetail.getM_InOutLine_ID() == 0) { MMatchPO poMatch=(MMatchPO)model; costDetail.setM_InOutLine_ID(poMatch.getM_InOutLine_ID()); } if (model instanceof MLandedCostAllocation) { MLandedCostAllocation allocation=(MLandedCostAllocation)model; costDetail.setM_InOutLine_ID(allocation.getM_InOutLine_ID()); costDetail.setC_InvoiceLine_ID(allocation.getC_InvoiceLine_ID()); costDetail.setProcessed(false); } costDetail.saveEx(); }
Update Cost Amt
@SuppressWarnings({"UseOfSystemOutOrSystemErr","HardCodedStringLiteral","CallToPrintStackTrace","UseOfObsoleteCollectionType"}) public static void main(String[] args){ if (args.length != 2) { System.err.println("Invalid amount of arguments: " + Arrays.asList(args)); System.exit(ERROR_EXIT_CODE); } int port; try { port=Integer.parseInt(args[0]); } catch ( NumberFormatException ex) { System.err.println("Invalid port number: " + args[0]); System.exit(ERROR_EXIT_CODE); return; } final String handlerValue=System.getenv(IDEA_REBASE_HANDER_NO); if (handlerValue == null) { System.err.println("Handler no is not specified"); System.exit(ERROR_EXIT_CODE); } int handler; try { handler=Integer.parseInt(handlerValue); } catch ( NumberFormatException ex) { System.err.println("Invalid handler number: " + handlerValue); System.exit(ERROR_EXIT_CODE); return; } String file=args[1]; try { XmlRpcClientLite client=new XmlRpcClientLite("127.0.0.1",port); Vector<Object> params=new Vector<Object>(); params.add(handler); if (System.getProperty("os.name").toLowerCase().startsWith("windows") && file.startsWith(CYGDRIVE_PREFIX)) { int p=CYGDRIVE_PREFIX.length(); file=file.substring(p,p + 1) + ":" + file.substring(p + 1); } params.add(new File(file).getAbsolutePath()); Integer exitCode=(Integer)client.execute(HANDLER_NAME + ".editCommits",params); if (exitCode == null) { exitCode=ERROR_EXIT_CODE; } System.exit(exitCode.intValue()); } catch ( Exception e) { System.err.println("Unable to contact IDEA: " + e); e.printStackTrace(); System.exit(ERROR_EXIT_CODE); } }
The application entry point
protected void replaceText(CharSequence text){ switch (mAutoCompleteMode) { case AUTOCOMPLETE_MODE_SINGLE: ((InternalAutoCompleteTextView)mInputView).superReplaceText(text); break; case AUTOCOMPLETE_MODE_MULTI: ((InternalMultiAutoCompleteTextView)mInputView).superReplaceText(text); break; } }
<p>Performs the text completion by replacing the current text by the selected item. Subclasses should override this method to avoid replacing the whole content of the edit box.</p>
protected StepExecution(){ }
Don't use! Only here because required by JPA.
@Override public void addEdge(final InstructionGraphEdge edge){ super.addEdge(edge); }
Adds an instruction edge to the instruction graph.
public AccountInfo(final Account a){ id=a.getId(); fullName=a.getFullName(); preferredEmail=a.getPreferredEmail(); username=a.getUserName(); }
Create an account description from a real data store record.
public int hammingWeightB(int n){ int res=0; for (int i=0; i < 32; i++) if ((n >>> i & 0x1) == 1) res++; return res; }
Most straight forward solution Iterate 32 times to check each digit in n
private ResourceImpl aggregate(ResourceImpl resourceA,ResourceImpl resourceB) throws NotFoundException { final String typeId=resourceA.getType(); final ResourceType resourceType=getResourceType(typeId); return resourceType.aggregate(resourceA,resourceB); }
Aggregates two resources which have the same type.
public void addValue(String key,boolean val,String comment) throws HeaderCardException { addHeaderCard(key,new HeaderCard(key,val,comment)); }
Add or replace a key with the given boolean value and comment.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
@Override public boolean equals(Object obj){ if (obj == null) { return false; } else if (obj instanceof String) { String theString=(String)obj; return toString().equalsIgnoreCase(theString); } else if (obj instanceof MailAddress) { MailAddress addr=(MailAddress)obj; return getLocalPart().equalsIgnoreCase(addr.getLocalPart()) && getDomain().equalsIgnoreCase(addr.getDomain()); } return false; }
Indicates whether some other object is "equal to" this one. Note that this implementation breaks the general contract of the <code>equals</code> method by allowing an instance to equal to a <code>String</code>. It is recommended that implementations avoid relying on this design which may be removed in a future release.
public static void time(ErrorMessages message,Timer time){ if (Options.time) { String msg=ErrorMessages.get(message,time.toString()); out.println(msg); } }
Report time statistic data.
public SaveVisionWorldAsAction(final VisionWorldDesktopComponent desktopComponent){ super("Save As..."); if (desktopComponent == null) { throw new IllegalArgumentException("Desktop component must not be null"); } this.desktopComponent=desktopComponent; putValue(SMALL_ICON,ResourceManager.getImageIcon("SaveAs.png")); putValue(SHORT_DESCRIPTION,"Save Vision World As"); }
Create a new create pixel matrix action.
protected void processBDDPLists(){ int count=0; Set<NodePortTuple> nptList=new HashSet<NodePortTuple>(); while (count < BDDP_TASK_SIZE && quarantineQueue.peek() != null) { NodePortTuple npt; npt=quarantineQueue.remove(); if (!toRemoveFromQuarantineQueue.remove(npt)) { sendDiscoveryMessage(npt.getNodeId(),npt.getPortId(),false,false); } nptList.add(npt); count++; } count=0; while (count < BDDP_TASK_SIZE && maintenanceQueue.peek() != null) { NodePortTuple npt; npt=maintenanceQueue.remove(); if (!toRemoveFromMaintenanceQueue.remove(npt)) { sendDiscoveryMessage(npt.getNodeId(),npt.getPortId(),false,false); } count++; } for ( NodePortTuple npt : nptList) { generateSwitchPortStatusUpdate(npt.getNodeId(),npt.getPortId()); } }
This method processes the quarantine list in bursts. The task is at most once per BDDP_TASK_INTERVAL. One each call, BDDP_TASK_SIZE number of switch ports are processed. Once the BDDP packets are sent out through the switch ports, the ports are removed from the quarantine list.
public Counter newCounter(String key){ return new UnsynchronizedLongCounter(key); }
Generate a new counter.
public Provider<TypeDefinitionGitLocationProvider> provideTypeDefinitionGitLocationProvider(){ return Access.contributedProvider(TypeDefinitionGitLocationProvider.class); }
Binds the type definition Git location provider.
public List<NamedRelatedResourceRep> listStoragePools(URI id){ StoragePoolList response=client.get(StoragePoolList.class,getIdUrl() + "/storage-pools",id); return defaultList(response.getPools()); }
Lists the storage pools for the given file virtual pool by ID. <p> API Call: <tt>GET /file/vpools/{id}/storage-pools</tt>
public static String buildUiResourceUriPrefixPath(Service service){ return buildUiResourceUriPrefixPath(service.getClass()); }
Compute URI prefix for static resources of a service.
public double distance(final Double2D p){ final double dx=(double)this.x - p.x; final double dy=(double)this.y - p.y; return Math.sqrt(dx * dx + dy * dy); }
Returns the distance FROM this MutableInt2D TO the specified point.
private boolean checkBreachDuration(double threshold,Trigger t){ long expectedBreachDuration=t.getBreachDurationSecs() * 1000L; Long breachStartTime=this.breachCounterMap.get(t.generateKey()); if (null == breachStartTime) { setBreachStartTime(t,Long.valueOf(System.currentTimeMillis())); logger.debug("Set breach start time to NOW for app " + t.getAppId() + ", trigger "+ t.getTriggerId()+ "-"+ t.getMetric()+ "-"+ t.getThresholdType()); return false; } long currentTime=System.currentTimeMillis(); long breachDuration=currentTime - breachStartTime.longValue(); logger.debug("Current breach duration is " + breachDuration / 1000 + " seconds. Expected breach duration is " + t.getBreachDurationSecs()); if (breachDuration >= expectedBreachDuration) { return true; } else return false; }
Check if the metric value is greater than the upper threshold or less than the lower threshold for the breach duration
public static boolean handleEvaluationVersion(final Window parent){ if (isBetaVersion() && hasExpired()) { CMessageBox.showInformation(parent,String.format("Your beta version of %s has expired.",Constants.PROJECT_NAME_VERSION)); return false; } return true; }
Handles everything that is necessary for expired and non-expired evaluation version.
public void stop(){ stopped=true; focusing=false; cancelOutstandingTask(); if (useAutoFocus) { try { camera.cancelAutoFocus(); } catch ( RuntimeException re) { Log.w(TAG,"Unexpected exception while cancelling focusing",re); } } }
Stop auto-focus.
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
The doPost method of the servlet. <br> This method is called when a form has its tag value method equals to post.
public void doPut(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
Put - Processes Get
public static void onlyNominalAttributes(Attributes attributes,String task) throws OperatorException { for ( Attribute attribute : attributes) { if (!Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(),Ontology.NOMINAL)) { throw new UserError(null,103,task,attribute.getName()); } } }
The attributes all have to be nominal or binary.
public void startElement(StylesheetHandler handler,String uri,String localName,String rawName,Attributes attributes) throws org.xml.sax.SAXException { setPropertiesFromAttributes(handler,rawName,attributes,this); try { Source sourceFromURIResolver=getSourceFromUriResolver(handler); String hrefUrl=getBaseURIOfIncludedStylesheet(handler,sourceFromURIResolver); if (handler.importStackContains(hrefUrl)) { throw new org.xml.sax.SAXException(XSLMessages.createMessage(getStylesheetInclErr(),new Object[]{hrefUrl})); } handler.pushImportURL(hrefUrl); handler.pushImportSource(sourceFromURIResolver); int savedStylesheetType=handler.getStylesheetType(); handler.setStylesheetType(this.getStylesheetType()); handler.pushNewNamespaceSupport(); try { parse(handler,uri,localName,rawName,attributes); } finally { handler.setStylesheetType(savedStylesheetType); handler.popImportURL(); handler.popImportSource(); handler.popNamespaceSupport(); } } catch ( TransformerException te) { handler.error(te.getMessage(),te); } }
Receive notification of the start of an xsl:include element.
public static String enumToCounter(Enum e){ return e.name(); }
Convert an Enum to the counter portion of its name.
protected void processPacket(Packet packet){ if (packet == null) { return; } while (!resultQueue.offer(packet)) { resultQueue.poll(); } }
Processes a packet to see if it meets the criteria for this packet collector. If so, the packet is added to the result queue.
public static void editLocalEdgeComment(final AbstractSQLProvider provider,final INaviEdge edge,final Integer commentId,final Integer userId,final String newComment) throws CouldntSaveDataException { Preconditions.checkNotNull(provider,"IE00856: provider argument can not be null"); Preconditions.checkNotNull(edge,"IE00857: codeNode argument can not be null"); Preconditions.checkNotNull(commentId,"IE00858: comment argument can not be null"); Preconditions.checkNotNull(userId,"IE00874: userId argument can not be null"); PostgreSQLCommentFunctions.editComment(provider,commentId,userId,newComment); }
This function edits a local edge comment which is associated with the edge provided as argument.