code
stringlengths
10
174k
nl
stringlengths
3
129k
public TriggerIsNPCNameForUnstartedQuestCondition(final List<String> regions){ this.regions=ImmutableList.copyOf(regions); }
Creates a new TriggerIsNPCNameForUnstartedQuestCondition
public JavaPacketizer(){ }
Because packets can come out of order, it is possible that some packets for a newer frame may arrive while an older frame is still incomplete. However, in the case where we get nothing but incomplete frames, we don't want to keep all of them around forever.
protected void drawPoints(Canvas canvas,Paint paint,List<Float> pointsList,XYSeriesRenderer seriesRenderer,float yAxisValue,int seriesIndex,int startIndex){ if (isRenderPoints(seriesRenderer)) { ScatterChart pointsChart=getPointsChart(); if (pointsChart != null) { int length=(int)mPathMeasure.getLength(); int pointsLength=pointsList.size(); float[] coords=new float[2]; for (int i=0; i < length; i++) { mPathMeasure.getPosTan(i,coords,null); double prevDiff=Double.MAX_VALUE; boolean ok=true; for (int j=0; j < pointsLength && ok; j+=2) { double diff=Math.abs(pointsList.get(j) - coords[0]); if (diff < 1) { pointsList.set(j + 1,coords[1]); prevDiff=diff; } ok=prevDiff > diff; } } pointsChart.drawSeries(canvas,paint,pointsList,seriesRenderer,yAxisValue,seriesIndex,startIndex); } } }
Draws the series points.
public boolean isLeaf(){ return (getChildCount() == 0); }
Returns true if this node has no children. To distinguish between nodes that have no children and nodes that <i>cannot</i> have children (e.g. to distinguish files from empty directories), use this method in conjunction with <code>getAllowsChildren</code>
public void testLoadContent(){ System.out.println("loadContent"); AuditCommand mockAuditCommand=createMock(AuditCommand.class); mockAuditCommand.loadContent(); expectLastCall().once(); replay(mockAuditCommand); AuditServiceThreadImpl instance=initialiseAuditServiceThread(mockAuditCommand); instance.loadContent(); verify(mockAuditCommand); }
Test of loadContent method, of class AuditServiceThreadImpl.
private void nextToken(StreamTokenizer tokenizer) throws IOException { tokenizer.nextToken(); if ((tokenizer.ttype == '\'') || (tokenizer.ttype == '"')) { tokenizer.ttype=StreamTokenizer.TT_WORD; } else if ((tokenizer.ttype == StreamTokenizer.TT_WORD) && (tokenizer.sval.equals("?"))) { tokenizer.ttype='?'; } if (LOG.isDebugging()) { if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) { LOG.debug("token: " + tokenizer.nval); } else if (tokenizer.ttype == StreamTokenizer.TT_WORD) { LOG.debug("token: " + tokenizer.sval); } else if (tokenizer.ttype == StreamTokenizer.TT_EOF) { LOG.debug("token: EOF"); } else if (tokenizer.ttype == StreamTokenizer.TT_EOL) { LOG.debug("token: EOL"); } else { LOG.debug("token type: " + tokenizer.ttype); } } }
Helper function for token handling.
private TStep makeStep(String opName){ int count=0; for ( TStep step : steps) { if (step.name().equals(opName)) { count++; } } return new TStep(opName,count); }
creates a new step from a name
public static void onContextStop(){ PersistedEvents.persistEvents(applicationContext,stateMap); }
Call this when the consuming Activity/Fragment receives an onStop() callback in order to persist any outstanding events to disk so they may be flushed at a later time. The next flush (explicit or not) will check for any outstanding events and if present, include them in that flush. Note that this call may trigger an I/O operation on the calling thread. Explicit use of this method is necessary.
private void ensureBoundsVisible(){ final Rectangle screenBounds=GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds(); final Rectangle bounds=getBounds(); boolean aligned=false; if (bounds.x < screenBounds.x) { bounds.x=screenBounds.x; aligned=true; } if (bounds.x + bounds.width > screenBounds.x + screenBounds.width) { bounds.x=screenBounds.x + screenBounds.width - bounds.width; aligned=true; } if (bounds.y + bounds.height > screenBounds.y + screenBounds.height) { bounds.y=screenBounds.y + screenBounds.height - bounds.height; aligned=true; } if (bounds.y < screenBounds.y) { bounds.y=screenBounds.y; aligned=true; } if (aligned) { settings.set(centerXSetting,(int)bounds.getCenterX()); settings.set(centerYSetting,(int)bounds.getCenterY()); } }
Ensures that the whole overlay card is visible (inside the screen). <p> If some parts of the dialog would fall outside of the screen, the dialog will be moved to still just fit in. </p>
public static void throwIfNotQueryable(final AccessibleObject accessor){ Queryable queryable=accessor.getAnnotation(Queryable.class); if (queryable != null && !queryable.value()) { throw new NotQueryableException(String.format("%1$s \"%2$s\" (%3$s) is not queryable as has been marked with @Queryable(false)",Classes.RAW_CLASS.apply(GenericPropertyInfo.propertyTypeOf(accessor)).getSimpleName(),((Member)accessor).getName(),((Member)accessor).getDeclaringClass().getName())); } }
Verify that the provided accessor method has not been marked with a Queryable(false).
public void updateBinaryStream(int columnIndex,java.io.InputStream x,int length) throws SQLException { checkState(); checkTypeConcurrency(); rs.updateBinaryStream(columnIndex,x,length); }
Updates the designated column with a binary stream value. The <code>updateXXX</code> methods are used to update column values in the current row or the insert row. The <code>updateXXX</code> methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database.
public void handleEnumerationRequest(EnumerationContext aws){ switch (aws.stage) { case HOSTDESC: getHostComputeDescription(aws,AWSEnumerationStages.PARENTAUTH); break; case PARENTAUTH: getParentAuth(aws,AWSEnumerationStages.KICKOFF_ENUMERATION); break; case KICKOFF_ENUMERATION: kickOffEnumerationWorkFlows(aws,AWSEnumerationStages.PATCH_COMPLETION); break; case PATCH_COMPLETION: setOperationDurationStat(aws.awsAdapterOperation); AdapterUtils.sendPatchToEnumerationTask(this,aws.computeEnumerationRequest.taskReference); break; case ERROR: AdapterUtils.sendFailurePatchToEnumerationTask(this,aws.computeEnumerationRequest.taskReference,aws.error); break; default : logSevere("Unknown AWS enumeration stage %s ",aws.stage.toString()); aws.error=new Exception("Unknown AWS enumeration stage"); AdapterUtils.sendFailurePatchToEnumerationTask(this,aws.computeEnumerationRequest.taskReference,aws.error); break; } }
Creates operations for the creation and deletion adapter services and spawns them off in parallel
public static <K,V>SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> map){ if (map == null) { throw new NullPointerException(); } return new SynchronizedSortedMap<K,V>(map); }
Returns a wrapper on the specified sorted map which synchronizes all access to the sorted map.
private static MkSocket createMockSocket() throws IOException { return new MkSocket(new ByteArrayInputStream(Joiner.on(BkBasicTest.CRLF).join("GET / HTTP/1.1",BkBasicTest.HOST,"Content-Length: 2","","hi").getBytes())); }
Creates Socket mock for reuse.
@SuppressWarnings("deprecation") public static LocalVariableMap[] readResultFile(JobConf job,String fname) throws DMLRuntimeException, IOException { HashMap<Long,LocalVariableMap> tmp=new HashMap<Long,LocalVariableMap>(); FileSystem fs=FileSystem.get(job); Path path=new Path(fname); LongWritable key=new LongWritable(); Text value=new Text(); int countAll=0; for ( Path lpath : MatrixReader.getSequenceFilePaths(fs,path)) { SequenceFile.Reader reader=new SequenceFile.Reader(FileSystem.get(job),lpath,job); try { while (reader.next(key,value)) { if (!tmp.containsKey(key.get())) tmp.put(key.get(),new LocalVariableMap()); Object[] dat=ProgramConverter.parseDataObject(value.toString()); tmp.get(key.get()).put((String)dat[0],(Data)dat[1]); countAll++; } } finally { if (reader != null) reader.close(); } } LOG.debug("Num remote worker results (before deduplication): " + countAll); LOG.debug("Num remote worker results: " + tmp.size()); return tmp.values().toArray(new LocalVariableMap[0]); }
Result file contains hierarchy of workerID-resultvar(incl filename). We deduplicate on the workerID. Without JVM reuse each task refers to a unique workerID, so we will not find any duplicates. With JVM reuse, however, each slot refers to a workerID, and there are duplicate filenames due to partial aggregation and overwrite of fname (the RemoteParWorkerMapper ensures uniqueness of those files independent of the runtime implementation).
private Targetable chooseTarget(Coords pos){ boolean friendlyFire=clientgui.getClient().getGame().getOptions().booleanOption("friendly_fire"); Targetable choice=null; Iterator<Entity> choices; if (friendlyFire) { choices=clientgui.getClient().getGame().getEntities(pos); } else { choices=clientgui.getClient().getGame().getEnemyEntities(pos,ce()); } List<Targetable> targets=new ArrayList<Targetable>(); final IPlayer localPlayer=clientgui.getClient().getLocalPlayer(); while (choices.hasNext()) { Targetable t=choices.next(); boolean isSensorReturn=false; boolean isVisible=true; if (t instanceof Entity) { isSensorReturn=((Entity)t).isSensorReturn(localPlayer); isVisible=((Entity)t).hasSeenEntity(localPlayer); } if (!ce().equals(t) && !isSensorReturn && isVisible) { targets.add(t); } } Building bldg=clientgui.getClient().getGame().getBoard().getBuildingAt(pos); if (bldg != null) { targets.add(new BuildingTarget(pos,clientgui.getClient().getGame().getBoard(),Targetable.TYPE_BLDG_TAG)); } targets.add(new HexTarget(pos,clientgui.getClient().getGame().getBoard(),Targetable.TYPE_HEX_TAG)); if (targets.size() == 1) { choice=targets.get(0); } else if (targets.size() > 1) { String input=(String)JOptionPane.showInputDialog(clientgui,Messages.getString("FiringDisplay.ChooseTargetDialog.message",new Object[]{pos.getBoardNum()}),Messages.getString("FiringDisplay.ChooseTargetDialog.title"),JOptionPane.QUESTION_MESSAGE,null,SharedUtility.getDisplayArray(targets),null); choice=SharedUtility.getTargetPicked(targets,input); } return choice; }
Have the player select a target from the entities at the given coords.
@Deprecated public SimpleTriggerImpl(String name,String group,int repeatCount,long repeatInterval){ this(name,group,new Date(),null,repeatCount,repeatInterval); }
<p> Create a <code>SimpleTrigger</code> that will occur immediately, and repeat at the the given interval the given number of times. </p>
public boolean isIndependent(Node x,Node y,List<Node> z){ x=getVariable(variables,x.getName()); z=GraphUtils.replaceNodes(z,variables); double[] residualsX=residuals(x,z); double[] residualsY=residuals(y,z); List<Double> residualsXFiltered=new ArrayList<>(); List<Double> residualsYFiltered=new ArrayList<>(); for (int i=0; i < residualsX.length; i++) { if (!Double.isNaN(residualsX[i]) && !Double.isNaN(residualsY[i])) { residualsXFiltered.add(residualsX[i]); residualsYFiltered.add(residualsY[i]); } } residualsX=new double[residualsXFiltered.size()]; residualsY=new double[residualsYFiltered.size()]; for (int i=0; i < residualsXFiltered.size(); i++) { residualsX[i]=residualsXFiltered.get(i); residualsY[i]=residualsYFiltered.get(i); } if (residualsX.length != residualsY.length) throw new IllegalArgumentException("Missing values handled."); int sampleSize=residualsX.length; double r=StatUtils.correlation(residualsX,residualsY); if (r > 1.) r=1.; if (r < -1.) r=-1.; double fisherZ=Math.sqrt(sampleSize - z.size() - 3.0) * 0.5 * (Math.log(1.0 + r) - Math.log(1.0 - r)); if (Double.isNaN(fisherZ)) { return false; } double pvalue=2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0,1,Math.abs(fisherZ))); this.pValue=pvalue; boolean independent=pvalue > alpha; if (verbose) { if (independent) { TetradLogger.getInstance().log("independencies",SearchLogUtils.independenceFactMsg(x,y,z,getPValue())); System.out.println(SearchLogUtils.independenceFactMsg(x,y,z,getPValue())); } else { TetradLogger.getInstance().log("dependencies",SearchLogUtils.dependenceFactMsg(x,y,z,getPValue())); } } return independent; }
Determines whether variable x is independent of variable y given a list of conditioning variables z.
public void initializeRegion(){ InternalDistributedSystem system=this.newRegion.getSystem(); for (int retry=0; retry < 5; retry++) { Set recps=getRecipients(); if (logger.isDebugEnabled()) { logger.debug("Creating region {}",this.newRegion); } if (recps.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("CreateRegionProcessor.initializeRegion, no recipients, msg not sent"); } this.newRegion.getDistributionAdvisor().setInitialized(); EventTracker tracker=((LocalRegion)this.newRegion).getEventTracker(); if (tracker != null) { tracker.setInitialized(); } return; } CreateRegionReplyProcessor replyProc=new CreateRegionReplyProcessor(recps); boolean useMcast=false; CreateRegionMessage msg=getCreateRegionMessage(recps,replyProc,useMcast); if (((LocalRegion)newRegion).isUsedForPartitionedRegionBucket()) { replyProc.enableSevereAlertProcessing(); msg.severeAlertCompatible=true; } this.newRegion.getDistributionManager().putOutgoing(msg); try { this.newRegion.getCache().getCancelCriterion().checkCancelInProgress(null); try { replyProc.waitForRepliesUninterruptibly(); if (!replyProc.needRetry()) { break; } } catch ( ReplyException e) { Throwable t=e.getCause(); if (t instanceof IllegalStateException) { throw (IllegalStateException)t; } e.handleAsUnexpected(); break; } } finally { replyProc.cleanup(); EventTracker tracker=((LocalRegion)this.newRegion).getEventTracker(); if (tracker != null) { tracker.setInitialized(); } if (((LocalRegion)this.newRegion).isUsedForPartitionedRegionBucket()) { if (logger.isDebugEnabled()) { logger.debug("initialized bucket event tracker: {}",tracker); } } } } this.newRegion.getDistributionAdvisor().setInitialized(); }
this method tells other members that the region is being created
public static TypeReference newTypeParameterBoundReference(int sort,int paramIndex,int boundIndex){ return new TypeReference((sort << 24) | (paramIndex << 16) | (boundIndex << 8)); }
Returns a reference to a type parameter bound of a generic class or method.
public XMLWriter(OutputStream output) throws IOException { this(new OutputStreamWriter(output,"UTF8")); }
Create a new XMLWriter
protected void installDefaults(){ LookAndFeel.installColorsAndFont(table,"Table.background","Table.foreground","Table.font"); LookAndFeel.installProperty(table,"opaque",Boolean.TRUE); Color sbg=table.getSelectionBackground(); if (sbg == null || sbg instanceof UIResource) { sbg=UIManager.getColor("Table.selectionBackground"); table.setSelectionBackground(sbg != null ? sbg : UIManager.getColor("textHighlight")); } Color sfg=table.getSelectionForeground(); if (sfg == null || sfg instanceof UIResource) { sfg=UIManager.getColor("Table.selectionForeground"); table.setSelectionForeground(sfg != null ? sfg : UIManager.getColor("textHighlightText")); } Color gridColor=table.getGridColor(); if (gridColor == null || gridColor instanceof UIResource) { gridColor=UIManager.getColor("Table.gridColor"); table.setGridColor(gridColor != null ? gridColor : Color.GRAY); } Container parent=SwingUtilities.getUnwrappedParent(table); if (parent != null) { parent=parent.getParent(); if (parent != null && parent instanceof JScrollPane) { LookAndFeel.installBorder((JScrollPane)parent,"Table.scrollPaneBorder"); } } isFileList=Boolean.TRUE.equals(table.getClientProperty("Table.isFileList")); }
Initialize JTable properties, e.g. font, foreground, and background. The font, foreground, and background properties are only set if their current value is either null or a UIResource, other properties are set if the current value is null.
final boolean removeStrategy(final GenericPlanStrategy<T,I> strategy,final String subpopulation){ final StrategyWeights<T,I> weights=getStrategyWeights(subpopulation); int idx=weights.strategies.indexOf(strategy); if (idx != -1) { weights.strategies.remove(idx); double weight=weights.weights.remove(idx); weights.totalWeights-=weight; return true; } return false; }
removes the specified strategy from this manager for the specified subpopulation
void cancelRedirectsAndImages(){ if (redirectThread != null) { redirectThread.cancel(); redirectThread=null; } threadQueue.discardQueue(); embeddedCSS=null; externalCSS=null; if (getComponentForm() != null) { marqueeMotion=null; getComponentForm().deregisterAnimated(this); } }
Cancels redirects if exists. This is useful when the page has a meta tag with redirection/refresh in X seconds, and in that time the user clicked a link
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter,java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix=xmlWriter.getPrefix(namespace); if (prefix == null) { prefix=generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix=org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } return prefix; }
Register a namespace prefix
public static void convertOSM2MultimodalNetwork(String path2InputFiles,String path2OSMFile){ log.info("Conversion from OSM to multimodal MATSim network..."); new MultimodalNetworkCreatorPT(network).createMultimodalNetwork(path2OSMFile); new PTScheduleCreatorHAFAS(schedule,vehicles,transformation).createSchedule(path2InputFiles); new PTMapperBusAndTram(schedule).routePTLines(network); log.info("Conversion from OSM to multimodal MATSim network... done."); }
Converts a given OSM network to a multimodal MATSim network with the help of a HAFAS schedule.
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); }
Util method to write an attribute with the ns prefix
public static VqlParser parse(String columnPath){ return parse(columnPath,false); }
Parses a link table (LTR) columnPath and returns the path as an instance of class VqlParser. Class VqlParser is generated by ANTLR. If a parse error occurs a ColumnPathParseException is thrown.
protected UnManagedVolume injectVolumeCharacterstics(UnManagedVolume storageVolumeInfo,CIMInstance volumeInstance,Map<String,String> volumeCharacterstics){ if (null == volumeCharacterstics) { volumeCharacterstics=new HashMap<String,String>(); } for ( SupportedVolumeCharacterstics characterstic : SupportedVolumeCharacterstics.values()) { injectIntoVolumeCharactersticContainer(volumeCharacterstics,characterstic.getCharacterstic(),characterstic.getAlterCharacterstic(),volumeInstance); } if (storageVolumeInfo.getVolumeCharacterstics() == null) { storageVolumeInfo.setVolumeCharacterstics(new StringMap()); } storageVolumeInfo.getVolumeCharacterstics().replace(volumeCharacterstics); return storageVolumeInfo; }
Loop through each VolumeCharacterstics Entry in Enum, extract the property value from Provider, and insert into Volume info's VolumeCharacterstci Map.
public void dispose() throws GSSException { x.dispose(); }
Disposes the GSSContext within
public String toString(){ return this.m00 + ", " + this.m01+ ", "+ this.m02+ ", "+ this.m03+ "\n"+ this.m10+ ", "+ this.m11+ ", "+ this.m12+ ", "+ this.m13+ "\n"+ this.m20+ ", "+ this.m21+ ", "+ this.m22+ ", "+ this.m23+ "\n"+ this.m30+ ", "+ this.m31+ ", "+ this.m32+ ", "+ this.m33+ "\n"; }
Returns a string that contains the values of this Matrix4f.
public void runTest() throws Throwable { Document doc1; Document doc2; Node newChild; NodeList elementList; Node elementNode; Node appendedChild; doc1=(Document)load("hc_staff",false); doc2=(Document)load("hc_staff",true); newChild=doc1.createElement("br"); elementList=doc2.getElementsByTagName("p"); elementNode=elementList.item(1); { boolean success=false; try { appendedChild=elementNode.appendChild(newChild); } catch ( DOMException ex) { success=(ex.code == DOMException.WRONG_DOCUMENT_ERR); } assertTrue("throw_WRONG_DOCUMENT_ERR",success); } }
Runs the test case.
public SE8cSignalHead(String sname,NamedBeanHandle<Turnout> lowTO,NamedBeanHandle<Turnout> highTO){ super(sname); this.lowTurnout=lowTO; this.highTurnout=highTO; systemName=sname; init(); }
Ctor for specifying system name
@Override public void repaint(Rectangle r){ }
Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for more information.
public void activeLineRangeChanged(ActiveLineRangeEvent e){ if (e.getMin() == -1) { clearActiveLineRange(); } else { setActiveLineRange(e.getMin(),e.getMax()); } }
Modifies the "active line range" that is painted in this component.
void forgetVolumes(List<VolumeInfo> nativeVolumeInfoList){ Map<String,Set<String>> systemVolumesMap=new HashMap<String,Set<String>>(); for ( VolumeInfo volumeInfo : nativeVolumeInfoList) { String systemGuid=volumeInfo.getStorageSystemNativeGuid(); Set<String> systemVolumes=null; if (systemVolumesMap.containsKey(systemGuid)) { systemVolumes=systemVolumesMap.get(systemGuid); } else { systemVolumes=new HashSet<String>(); systemVolumesMap.put(systemGuid,systemVolumes); } systemVolumes.add(volumeInfo.getVolumeWWN()); } rediscoverStorageSystems(new ArrayList<String>(systemVolumesMap.keySet())); VPlexApiUtils.pauseThread(60000); Set<String> logUnitsPaths=findLogicalUnits(systemVolumesMap); try { URI requestURI=_vplexApiClient.getBaseURI().resolve(VPlexApiConstants.URI_FORGET_LOG_UNIT); s_logger.info("Forget logical units URI is {}",requestURI.toString()); StringBuilder argBuilder=new StringBuilder(); for ( String logUnitPath : logUnitsPaths) { if (argBuilder.length() != 0) { argBuilder.append(","); } argBuilder.append(logUnitPath); } Map<String,String> argsMap=new HashMap<String,String>(); argsMap.put(VPlexApiConstants.ARG_DASH_U,argBuilder.toString()); JSONObject postDataObject=VPlexApiUtils.createPostData(argsMap,false); s_logger.info("Forget logical units POST data is {}",postDataObject.toString()); ClientResponse response=_vplexApiClient.post(requestURI,postDataObject.toString()); String responseStr=response.getEntity(String.class); s_logger.info("Forget logical units response is {}",responseStr); int status=response.getStatus(); response.close(); if (status != VPlexApiConstants.SUCCESS_STATUS) { if (response.getStatus() == VPlexApiConstants.ASYNC_STATUS) { s_logger.info("Forget volumes is completing asynchronously"); _vplexApiClient.waitForCompletion(response); } else { s_logger.error("Request to forget logical units failed with Status: {}",response.getStatus()); return; } } s_logger.info("Successfully forgot logical units"); } catch ( Exception e) { s_logger.error("Exception forgetting logical units: %s",e.getMessage(),e); } }
Causes the VPLEX to "forget" about the volumes identified by the passed native volume information. Typically called when the calling application has deleted backend volumes and wants the VPLEX to disregard these volumes.
public void clearHighlightedView(){ mStrokeCell=null; mStrokeCellPrevBound=null; invalidate(); requestLayout(); }
Clears the cell selector
public Element next(){ return theNext; }
Return the next element in an element stack or queue.
@GET @Path("check-geo-distributed") public Response checkGeoSetup(){ Boolean isGeo=false; List<URI> ids=_dbClient.queryByType(VirtualDataCenter.class,true); Iterator<VirtualDataCenter> iter=_dbClient.queryIterativeObjects(VirtualDataCenter.class,ids); while (iter.hasNext()) { VirtualDataCenter vdc=iter.next(); if (!vdc.getLocal()) { if ((vdc.getConnectionStatus() == VirtualDataCenter.ConnectionStatus.ISOLATED) || vdc.getRepStatus() == VirtualDataCenter.GeoReplicationStatus.REP_NONE) { continue; } isGeo=true; } } return Response.ok(isGeo.toString(),MediaType.APPLICATION_OCTET_STREAM).build(); }
Check if the setup is geo-distributed multi-VDC
public static boolean isHadoop2Env(){ Configuration hadoopConf=new Configuration(); String hadoopVersion=hadoopConf.get(MAPREDUCE_FRAMEWORK_NAME_PROP); return hadoopVersion != null && hadoopVersion.equals(YARN); }
Detect if the current Hadoop environment is 2.x
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.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public void reconnectCircuit(){ ArrayList<Gate> new_Gates=new ArrayList<Gate>(); ArrayList<Wire> new_Wires=new ArrayList<Wire>(); if (_Gates != null) { for (int i=0; i < _Gates.size(); i++) { Gate g=new Gate(_Gates.get(i)); new_Gates.add(g); } } if (_Wires != null) { for (int i=0; i < _Wires.size(); i++) { Wire w=new Wire(_Wires.get(i)); new_Wires.add(w); } } for (int i=0; i < new_Gates.size(); i++) { if (_Gates.get(i).Outgoing != null) { int index=_Gates.get(i).Outgoing.Index; for ( Wire w : new_Wires) { if (w.Index == index) { new_Gates.get(i).Outgoing=w; } } } } for (int i=0; i < new_Wires.size(); i++) { if (_Wires.get(i).From != null) { int index=_Wires.get(i).From.Index; for ( Gate g : new_Gates) { if (g.Index == index) { new_Wires.get(i).From=g; } } } if (_Wires.get(i).To != null) { int index=_Wires.get(i).To.Index; for ( Gate g : new_Gates) { if (g.Index == index) { new_Wires.get(i).To=g; } } } if (_Wires.get(i).Next != null) { int index=_Wires.get(i).Next.Index; for ( Wire w : new_Wires) { if (w.Index == index) { new_Wires.get(i).Next=w; } } } } _Gates=new_Gates; _Wires=new_Wires; }
Gate and Wire objects must "point" to each other in memory in a connected circuit
private boolean hasLocationsChanges(String newLocations){ String oldLocations=this.preferencePage.getPreferenceStore().getString(LIBRARY_PATH_LOCATION_PREFIX); if (oldLocations != null && oldLocations.equalsIgnoreCase(newLocations)) { return false; } List<String> oldCheckedElements=new ArrayList<String>(); if (oldLocations != null && oldLocations.length() > 0) { String[] locations=oldLocations.split(ESCAPE_REGEX + LOCATION_DELIM); for (int i=0; i < locations.length; i++) { String values[]=locations[i].split(ESCAPE_REGEX + STATE_DELIM); if (Boolean.valueOf(values[1]).booleanValue()) { oldCheckedElements.add(values[0]); } } } Object[] newCheckedLocations=fTableViewer.getCheckedElements(); if (newCheckedLocations.length != oldCheckedElements.size()) { return true; } for (int i=0; i < newCheckedLocations.length; i++) { if (!oldCheckedElements.contains(newCheckedLocations[i])) { return true; } } return false; }
Detects changes to the use scan locations
protected boolean shouldSelect(Transaction tx){ return isSelectable(tx); }
Sub-classes can override this to just customize whether transactions are usable, but keep age sorting.
@RequestMapping(value="/_search/bloodPressures/{query}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) @Timed public List<BloodPressure> search(@PathVariable String query){ return StreamSupport.stream(bloodPressureSearchRepository.search(queryString(query)).spliterator(),false).collect(Collectors.toList()); }
SEARCH /_search/bloodPressures/:query -> search for the bloodPressure corresponding to the query.
public void route(){ long startTime=System.currentTimeMillis(); final int distanceLimitMm; final int tmpTimeLimitSeconds; if (destinationSplit != null) { int maxAbsLatFixed=Math.max(Math.abs(destinationSplit.fixedLat),Math.abs(maxAbsOriginLat)); double maxAbsLatRadians=Math.toRadians(VertexStore.fixedDegreesToFloating(maxAbsLatFixed)); millimetersPerDegreeLonFixed=MM_PER_DEGREE_LAT_FIXED * Math.cos(maxAbsLatRadians); double maxSpeedMetersPerSecond=profileRequest.getSpeed(streetMode); if (maxSpeedMetersPerSecond == 0) maxSpeedMetersPerSecond=36.11; maxSpeedSecondsPerMillimeter=1 / (maxSpeedMetersPerSecond * 1000); } if (distanceLimitMeters > 0) { distanceLimitMm=distanceLimitMeters * 1000; if (dominanceVariable != State.RoutingVariable.DISTANCE_MILLIMETERS) { LOG.warn("Setting a distance limit when distance is not the dominance function, this is a resource limiting issue and paths may be incorrect."); } } else { distanceLimitMm=Integer.MAX_VALUE; } if (timeLimitSeconds > 0) { tmpTimeLimitSeconds=timeLimitSeconds; if (dominanceVariable != State.RoutingVariable.DURATION_SECONDS) { LOG.warn("Setting a time limit when time is not the dominance function, this is a resource limiting issue and paths may be incorrect."); } } else { tmpTimeLimitSeconds=Integer.MAX_VALUE; } if (timeLimitSeconds > 0 && distanceLimitMeters > 0) { LOG.warn("Both distance limit of {}m and time limit of {}s are set in StreetRouter",distanceLimitMeters,timeLimitSeconds); } else if (timeLimitSeconds == 0 && distanceLimitMeters == 0) { LOG.debug("Distance and time limit are both set to 0 in StreetRouter. This means NO LIMIT in searching so the entire street graph will be explored. This can be slow."); } else if (distanceLimitMeters > 0) { LOG.debug("Using distance limit of {} meters",distanceLimitMeters); } else if (timeLimitSeconds > 0) { LOG.debug("Using time limit of {} sec",timeLimitSeconds); } if (queue.size() == 0) { LOG.warn("Routing without first setting an origin, no search will happen."); } PrintStream debugPrintStream=null; if (DEBUG_OUTPUT) { File debugFile=new File(String.format("street-router-debug.csv")); OutputStream outputStream; try { outputStream=new BufferedOutputStream(new FileOutputStream(debugFile)); } catch ( FileNotFoundException e) { throw new RuntimeException(e); } debugPrintStream=new PrintStream(outputStream); debugPrintStream.println("lat,lon,weight"); } EdgeStore.Edge edge=streetLayer.edgeStore.getCursor(); if (transitStopSearch) { routingVisitor=new StopVisitor(streetLayer,dominanceVariable,maxTransitStops,profileRequest.getMinTimeLimit(streetMode)); } else if (flagSearch != null) { routingVisitor=new VertexFlagVisitor(streetLayer,dominanceVariable,flagSearch,maxVertices,profileRequest.getMinTimeLimit(streetMode)); } while (!queue.isEmpty()) { State s0=queue.poll(); if (DEBUG_OUTPUT) { VertexStore.Vertex v=streetLayer.vertexStore.getCursor(s0.vertex); double lat=v.getLat(); double lon=v.getLon(); if (s0.backEdge != -1) { EdgeStore.Edge e=streetLayer.edgeStore.getCursor(s0.backEdge); v.seek(e.getFromVertex()); lat=(lat + v.getLat()) / 2; lon=(lon + v.getLon()) / 2; } debugPrintStream.println(String.format("%.6f,%.6f,%d",v.getLat(),v.getLon(),s0.weight)); } if (s0.backEdge >= 0 && !bestStatesAtEdge.get(s0.backEdge).contains(s0)) continue; if (toVertex > 0 && toVertex == s0.vertex) break; if (s0.getRoutingVariable(dominanceVariable) > bestValueAtDestination) break; if (routingVisitor != null) { routingVisitor.visitVertex(s0); if (routingVisitor.shouldBreakSearch()) { LOG.debug("{} routing visitor stopped search",routingVisitor.getClass().getSimpleName()); queue.clear(); break; } } if (destinationSplit != null && (s0.vertex == destinationSplit.vertex0 || s0.vertex == destinationSplit.vertex1)) { State atDest=getState(destinationSplit); if (atDest != null && bestValueAtDestination > atDest.getRoutingVariable(dominanceVariable)) { bestValueAtDestination=atDest.getRoutingVariable(dominanceVariable); } } streetLayer.outgoingEdges.get(s0.vertex).forEach(null); } if (DEBUG_OUTPUT) { debugPrintStream.close(); } long routingTimeMsec=System.currentTimeMillis() - startTime; LOG.debug("Routing took {} msec",routingTimeMsec); }
Call one of the setOrigin functions first before calling route(). It uses all nonzero limit as a limit whichever gets hit first For example if distanceLimitMeters &gt; 0 it is used a limit. But if it isn't timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set warning is shown and both are used.
public void clearAll(){ scriptString=null; clearIOS(); }
Clear the script string, inputs, outputs, and symbol table.
public RDN(AttributeTypeAndValue[] aAndVs){ this.values=new DERSet(aAndVs); }
Create a multi-valued RDN.
public ServiceCall<Void> resetCustomization(String customizationId){ Validator.notNull(customizationId,"customizationId cannot be null"); RequestBuilder requestBuilder=RequestBuilder.post(String.format(PATH_RESET,customizationId)); return createServiceCall(requestBuilder.build(),ResponseConverterUtils.getVoid()); }
Resets a custom language model by removing all corpora and words from the model. Resetting a custom model initializes the model to its state when it was first created. Metadata such as the name and language of the model are preserved.
public NotificationPopup(@NotNull StatusNotification notification,@NotNull Resources resources,@NotNull NotificationActionDelegate delegate){ this.notification=notification; this.resources=resources; this.delegate=delegate; setStyleName(resources.notificationCss().notificationPopupPanel()); notification.addObserver(this); FlowPanel contentWrapper=new FlowPanel(); contentWrapper.add(titlePanel=createTitleWidget()); contentWrapper.add(messagePanel=createContentWidget()); contentWrapper.setStyleName(resources.notificationCss().notificationPopupContentWrapper()); contentWrapper.ensureDebugId(CONTENT_DBG_ID + notification.getId()); FlowPanel notificationWrapper=new FlowPanel(); notificationWrapper.add(iconPanel=createIconWidget()); notificationWrapper.add(contentWrapper); notificationWrapper.add(createCloseWidget()); notificationWrapper.setStyleName(resources.notificationCss().notificationPopup()); notificationWrapper.ensureDebugId(NOTIFICATION_WRAPPER_DBG_ID + notification.getId()); setWidget(notificationWrapper); }
Create notification message.
public Iterator<TreeNode> findChildren(){ List<TreeNode> nodes; if (children == null) nodes=Collections.emptyList(); else nodes=children; return nodes.iterator(); }
Return an Iterator of all children of this node. If there are no children, an empty Iterator is returned.
@SuppressWarnings("try") private static void deconstructSSIForm(LIR lir){ for ( AbstractBlockBase<?> block : lir.getControlFlowGraph().getBlocks()) { try (Indent i=Debug.logAndIndent("Fixup Block %s",block)){ if (block.getPredecessorCount() != 0) { SSIUtil.removeIncoming(lir,block); } else { assert lir.getControlFlowGraph().getStartBlock().equals(block); } SSIUtil.removeOutgoing(lir,block); } } }
Remove Phi/Sigma In/Out. Note: Incoming Values are needed for the RegisterVerifier, otherwise SIGMAs/PHIs where the Out and In value matches (ie. there is no resolution move) are falsely detected as errors.
@Override public void hide(){ super.hide(); }
Hides the button. <p>This method will animate the button hide if the view has already been laid out.</p>
public DrawerAdapter(Context context,int headerLayoutResourceId,int entryLayoutResourceId){ super(context,headerLayoutResourceId,entryLayoutResourceId); mContext=context; mHeaderLayoutResourceId=headerLayoutResourceId; mEntryLayoutResourceId=entryLayoutResourceId; mLayoutInflater=LayoutInflater.from(mContext); this.add(new Entry(0,null)); setNotifyOnChange(true); }
Construct an adapter to display a drawer adapter
public void initJava(){ int index=(p_panel != null ? p_panel.fJavaType.getSelectedIndex() : 0); initJava(index); }
Init Database
private Name serializedLambdaName(){ StringBuilder buf=new StringBuilder(); buf.append(names.lambda); buf.append(enclosingMethodName()); buf.append('$'); String disam=serializedLambdaDisambiguation(); buf.append(Integer.toHexString(disam.hashCode())); buf.append('$'); buf.append(syntheticMethodNameCounts.getIndex(buf)); String result=buf.toString(); return names.fromString(result); }
For a serializable lambda, generate a method name which maximizes name stability across deserialization.
public String formatLongDateTime(Date date){ return DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG).format(date); }
Formats a date/time in 'long' style.
private void printNextNodes(BasicBlock block){ if (forward) { System.out.print(block + " Succs:"); } else { System.out.print(block + " Preds:"); } Enumeration<BasicBlock> e=getNextNodes(block); while (e.hasMoreElements()) { System.out.print(' '); System.out.print(e.nextElement()); } System.out.println(); }
Print the "next" nodes (either out or in) for the passed block depending on which way we are viewing the graph
protected boolean canClone(Object obj,String getter){ try { Class objClass=obj.getClass().getMethod(getter).getReturnType(); if (Enum.class.isAssignableFrom(objClass)) { logger.log(Level.FINE,"Found enum, not cloneable"); return false; } Method meth=objClass.getMethod("clone"); if (meth != null) { logger.log(Level.FINE,"Found clone method"); if (meth.getParameterTypes().length == 0 && meth.getReturnType().isAssignableFrom(objClass)) { return true; } else { logger.log(Level.FINE,"Wrong kind of clone method, parameter size {0}, returnType {1}",new Object[]{meth.getParameterTypes().length,meth.getReturnType()}); } } } catch ( NoSuchMethodException ex) { } catch ( SecurityException ex) { Exceptions.printStackTrace(ex); } return false; }
Checks if a getters return object can be cloned
public CacheLIRS(long maxMemory){ this(maxMemory,16,8); }
Create a new cache with the given number of entries, and the default settings (16 segments, and stack move distance of 8.
public BayesImEditorObs(BayesImWrapperObs wrapper,BayesIm bayesIm){ if (wrapper == null) { throw new NullPointerException(); } this.wrapper=wrapper; init(bayesIm); }
Constructs a new instanted model editor from a Bayes IM.
public static UnitValue parseUnitValue(String s,boolean isHor){ return parseUnitValue(s,null,isHor); }
Parses a single unit value. E.g. "10px" or "5in"
public static String removeAdditionalParty(HttpServletRequest request,HttpServletResponse response){ ShoppingCart cart=getCartObject(request); String partyId=request.getParameter("additionalPartyId"); String roleTypeId[]=request.getParameterValues("additionalRoleTypeId"); List<String> eventList=new LinkedList<String>(); Locale locale=UtilHttp.getLocale(request); int i; if (UtilValidate.isEmpty(partyId) || roleTypeId.length < 1) { request.setAttribute("_ERROR_MESSAGE_",UtilProperties.getMessage(resource_error,"OrderPartyIdAndOrRoleTypeIdNotDefined",locale)); return "error"; } if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) { List<String> msg=UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_")); eventList.addAll(msg); } for (i=0; i < roleTypeId.length; i++) { try { cart.removeAdditionalPartyRole(partyId,roleTypeId[i]); } catch ( Exception e) { Debug.logInfo(e.getLocalizedMessage(),module); eventList.add(e.getLocalizedMessage()); } } request.removeAttribute("_EVENT_MESSAGE_LIST_"); request.setAttribute("_EVENT_MESSAGE_LIST_",eventList); return "success"; }
Removes a previously associated party to order
@Override public void run(){ try { ArchiveManager archives=new ArchiveManager(); ArticleReaderInterface articleReader=null; ArchiveDescription description=null; Task<Revision> task=null; DiffCalculatorInterface diffCalc; if (MODE_STATISTICAL_OUTPUT) { diffCalc=new TimedDiffCalculator(new TaskTransmitter()); } else { diffCalc=new DiffCalculator(new TaskTransmitter()); } long start, time; while (archives.hasArchive()) { System.gc(); try { description=archives.getArchive(); ArticleFilter nameFilter=new ArticleFilter(); articleReader=InputFactory.getTaskReader(description,nameFilter); ArticleConsumerLogMessages.logArchiveRetrieved(logger,description); } catch ( ArticleReaderException e) { articleReader=null; ArticleConsumerLogMessages.logExceptionRetrieveArchive(logger,description,e); } while (articleReader != null) { try { if (articleReader.hasNext()) { start=System.currentTimeMillis(); task=articleReader.next(); time=System.currentTimeMillis() - start; if (task == null) { continue; } ArticleConsumerLogMessages.logArticleRead(logger,task,time,articleReader.getBytePosition()); start=System.currentTimeMillis(); diffCalc.process(task); time=System.currentTimeMillis() - start; DiffConsumerLogMessages.logArticleProcessed(logger,task,time); } else { ArticleConsumerLogMessages.logNoMoreArticles(logger,description); articleReader=null; } } catch ( ArticleReaderException e) { ArticleConsumerLogMessages.logTaskReaderException(logger,e); articleReader.resetTaskCompleted(); } catch ( DiffException e) { DiffConsumerLogMessages.logDiffException(logger,e); articleReader.resetTaskCompleted(); diffCalc.reset(); } } } diffCalc.closeTransmitter(); ArticleConsumerLogMessages.logNoMoreArchives(logger); } catch ( ConfigurationException e) { DiffToolLogMessages.logException(logger,e); throw new RuntimeException(e); } catch ( UnsupportedEncodingException e) { DiffToolLogMessages.logException(logger,e); throw new RuntimeException(e); } catch ( IOException e) { DiffToolLogMessages.logException(logger,e); throw new RuntimeException(e); } catch ( TimeoutException e) { DiffToolLogMessages.logException(logger,e); throw new RuntimeException(e); } catch ( Exception e) { DiffToolLogMessages.logException(logger,e); throw new RuntimeException(e); } }
Runs the diff creation process
public void takeSnapshot(String tag,String... keyspaceNames) throws IOException { if (operationMode == Mode.JOINING) throw new IOException("Cannot snapshot until bootstrap completes"); if (tag == null || tag.equals("")) throw new IOException("You must supply a snapshot name."); Iterable<Keyspace> keyspaces; if (keyspaceNames.length == 0) { keyspaces=Keyspace.all(); } else { ArrayList<Keyspace> t=new ArrayList<>(keyspaceNames.length); for ( String keyspaceName : keyspaceNames) t.add(getValidKeyspace(keyspaceName)); keyspaces=t; } for ( Keyspace keyspace : keyspaces) if (keyspace.snapshotExists(tag)) throw new IOException("Snapshot " + tag + " already exists."); for ( Keyspace keyspace : keyspaces) keyspace.snapshot(tag,null); }
Takes the snapshot for the given keyspaces. A snapshot name must be specified.
public SolrQuery removeSort(String itemName){ if (sortClauses != null) { for ( SortClause existing : sortClauses) { if (existing.getItem().equals(itemName)) { sortClauses.remove(existing); if (sortClauses.isEmpty()) sortClauses=null; serializeSorts(); break; } } } return this; }
Removes a single sort field from the current sort information.
public Iterator<ValueNumberFrame> factIterator(){ return factAtLocationMap.values().iterator(); }
Get an Iterator over all dataflow facts that we've recorded for the Locations in the CFG. Note that this does not include result facts (since there are no Locations corresponding to the end of basic blocks).
public double eval(Map<String,Double> tuple) throws Exception { synchronized (this) { this.setVariables(tuple); return this.eval(); } }
Thread safe
public static double sortableLongToDouble(long encoded){ return Double.longBitsToDouble(sortableDoubleBits(encoded)); }
Converts a sortable <code>long</code> back to a <code>double</code>.
public Class loadClass(String name) throws ClassNotFoundException { return (loadClass(name,false)); }
Load the class with the specified name. This method searches for classes in the same manner as <code>loadClass(String, boolean)</code> with <code>false</code> as the second argument.
public void defaultRouteSet(boolean enabled){ mDefaultRouteSet.set(enabled); }
Set a flag indicating default route is set for the network
public void start(){ this.dbHistory.start(); }
Start by acquiring resources needed to persist the database history
public Builder binLogPosition(int position){ this.innerBinLogPosition=position; return this; }
Set bin log position to start replicating from.
private void readEncodingData(int base){ if (base == 0) { System.arraycopy(FontSupport.standardEncoding,0,encoding,0,FontSupport.standardEncoding.length); } else if (base == 1) { System.out.println("**** EXPERT ENCODING!"); } else { pos=base; int encodingtype=readByte(); if ((encodingtype & 127) == 0) { int ncodes=readByte(); for (int i=1; i < ncodes + 1; i++) { int idx=readByte() & 0xff; encoding[idx]=i; } } else if ((encodingtype & 127) == 1) { int nranges=readByte(); int p=1; for (int i=0; i < nranges; i++) { int start=readByte(); int more=readByte(); for (int j=start; j < start + more + 1; j++) { encoding[j]=p++; } } } else { System.out.println("Bad encoding type: " + encodingtype); } } }
parse information about the encoding of this file.
public void registerClasses(Iterable<?> objs) throws IgniteCheckedException { if (objs != null) for ( Object o : objs) registerClass(o); }
Register local classes.
public void saveAsEPS(String file) throws IOException { java.awt.Color paper=fxToAWTColor(background); java.awt.Color ink=fxToAWTColor(foreground); PostScriptRenderer eps=new PostScriptRenderer(new FileOutputStream(file),zoom,border,paper,ink); eps.render(barcode); }
save as PostScript (eps)
protected void drawChartValuesText(Canvas canvas,XYSeries series,XYSeriesRenderer renderer,Paint paint,List<Float> points,int seriesIndex,int startIndex){ int seriesNr=mDataset.getSeriesCount(); int length=points.size(); float halfDiffX=getHalfDiffX(points,length,seriesNr); for (int i=0; i < length; i+=2) { int index=startIndex + i / 2; double value=series.getY(index); if (!isNullValue(value)) { float x=points.get(i); if (mType == Type.DEFAULT) { x+=seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX; } if (value >= 0) { drawText(canvas,getLabel(renderer.getChartValuesFormat(),value),x,points.get(i + 1) - renderer.getChartValuesSpacing(),paint,0); } else { drawText(canvas,getLabel(renderer.getChartValuesFormat(),value),x,points.get(i + 1) + renderer.getChartValuesTextSize() + renderer.getChartValuesSpacing() - 3,paint,0); } } } }
The graphical representation of the series values as text.
protected Element addElement(Element parent,String name,String classname,boolean primitive,int array){ return addElement(parent,name,classname,primitive,array,false); }
appends a new node to the parent with the given parameters
public void quitServer(String reason){ this.sendRawLine("QUIT :" + reason); }
Quits from the IRC server with a reason. Providing we are actually connected to an IRC server, the onDisconnect() method will be called as soon as the IRC server disconnects us.
public void testThrowingException() throws Exception { Map<String,Method> functions=new HashMap<>(); functions.put("foo",StaticThrowingException.class.getMethod("method")); String source="3 * foo() / 5"; Expression expr=JavascriptCompiler.compile(source,functions,getClass().getClassLoader()); ArithmeticException expected=expectThrows(ArithmeticException.class,null); assertEquals(MESSAGE,expected.getMessage()); StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); expected.printStackTrace(pw); pw.flush(); assertTrue(sw.toString().contains("JavascriptCompiler$CompiledExpression.evaluate(" + source + ")")); }
the method throws an exception. We should check the stack trace that it contains the source code of the expression as file name.
public Vector<HtmlLink> grabLinks(final String html){ final Vector<HtmlLink> result=new Vector<HtmlLink>(); final Matcher matcherTag=patternTag.matcher(html); while (matcherTag.find()) { final String href=matcherTag.group(1); final String linkText=matcherTag.group(2); final Matcher matcherLink=patternLink.matcher(href); while (matcherLink.find()) { final String link=matcherLink.group(1); final HtmlLink obj=new HtmlLink(link,linkText); result.add(obj); } } return result; }
Validate html with regular expression
public static float convertLength(String length,String attr,short unitsType,UnitProcessor.Context uctx){ switch (unitsType) { case OBJECT_BOUNDING_BOX: return UnitProcessor.svgOtherLengthToObjectBoundingBox(length,attr,uctx); case USER_SPACE_ON_USE: return UnitProcessor.svgOtherLengthToUserSpace(length,attr,uctx); default : throw new IllegalArgumentException("Invalid unit type"); } }
Returns a float in user units according to the specified parameters.
public void runScript(File file){ try { this.eval(file); } catch ( FileNotFoundException ex) { log.error("File {} not found.",file); } catch ( IOException ex) { log.error("Exception working with file {}",file); } catch ( ScriptException ex) { log.error("Error in script {}.",file,ex); } }
Run a script, suppressing common errors. Note that the file needs to have a registered extension, or a NullPointerException will be thrown.
public static Entity findSpotter(IGame game,Entity attacker,Targetable target){ Entity spotter=null; int taggedBy=-1; if (target instanceof Entity) { taggedBy=((Entity)target).getTaggedBy(); } ToHitData bestMods=new ToHitData(TargetRoll.IMPOSSIBLE,""); for ( Entity other : game.getEntitiesVector()) { if (((other.isSpotting() && (other.getSpotTargetId() == target.getTargetId())) || (taggedBy == other.getId())) && !attacker.isEnemyOf(other)) { LosEffects los=LosEffects.calculateLos(game,other.getId(),target,true); ToHitData mods=los.losModifiers(game); if (game.getOptions().booleanOption("double_blind") && !Compute.inVisualRange(game,los,other,target) && !Compute.inSensorRange(game,los,other,target,null)) { mods.addModifier(TargetRoll.IMPOSSIBLE,"outside of visual and sensor range"); } los.setTargetCover(LosEffects.COVER_NONE); mods.append(Compute.getAttackerMovementModifier(game,other.getId())); if (other.isAttackingThisTurn()) { mods.addModifier(1,"spotter is making an attack this turn"); } if ((spotter == null) || (mods.getValue() < bestMods.getValue())) { spotter=other; bestMods=mods; } } } return spotter; }
Finds the best spotter for the attacker. The best spotter is the one with the lowest attack modifiers, of course. LOS modifiers and movement are considered.
public boolean equals(Object o){ if (o == this) return true; if (!(o instanceof Interval)) return false; Interval other=(Interval)o; return other.start == this.start && other.end == this.end; }
Return <code>true</code> if <code>o</code> is an interval with the same borders.
@Override public int portRemote(){ if (_s != null) return _s.getPort(); else return 0; }
Returns the remote client's port.
public final char yycharat(int pos){ return zzBuffer[zzStartRead + pos]; }
Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos), but faster
public Promise<T> delay(long delay,TimeUnit unit){ return new Promise<T>(observable.delay(delay,unit)); }
Returns a promise that mirrors the source promise but is fulfilled shifted forward in time by a specified delay. Error notifications from the source promise are not delayed.
@Override public String toString(){ return "DateTickUnit[" + this.unitType.toString() + ", "+ this.count+ "]"; }
Returns a string representation of this instance, primarily used for debugging purposes.
private Object parseString(GridField field,String in){ log.log(Level.FINE,"Parse: " + field + ":"+ in); if (in == null) return null; int dt=field.getDisplayType(); try { if (dt == DisplayType.Integer || (DisplayType.isID(dt) && field.getColumnName().endsWith("_ID"))) { int i=Integer.parseInt(in); return new Integer(i); } else if (DisplayType.isNumeric(dt)) { return DisplayType.getNumberFormat(dt).parse(in); } else if (DisplayType.isDate(dt)) { long time=0; try { time=DisplayType.getDateFormat_JDBC().parse(in).getTime(); return new Timestamp(time); } catch ( Exception e) { log.log(Level.SEVERE,in + "(" + in.getClass()+ ")"+ e); time=DisplayType.getDateFormat(dt).parse(in).getTime(); } return new Timestamp(time); } else if (dt == DisplayType.YesNo) return Boolean.valueOf(in); else return in; } catch ( Exception ex) { log.log(Level.SEVERE,"Object=" + in,ex); return null; } }
Parse String
public static NameMatcher<TriggerKey> triggerNameContains(String compareTo){ return NameMatcher.nameContains(compareTo); }
Create a NameMatcher that matches trigger names containing the given string.
@Override protected void closing(){ }
Called when the desktop component is closing.
public boolean equals(Object other){ if (!(other instanceof GF2mVector)) { return false; } GF2mVector otherVec=(GF2mVector)other; if (!field.equals(otherVec.field)) { return false; } return IntUtils.equals(vector,otherVec.vector); }
Compare this vector with another object.
private void updateBlockMirrorConsistencyGroup(){ log.info("Migrating BlockMirror consistencyGroup to consistencyGroups."); DbClient dbClient=getDbClient(); List<URI> blockMirrorURIs=dbClient.queryByType(BlockMirror.class,false); Iterator<BlockMirror> blockMirrors=dbClient.queryIterativeObjects(BlockMirror.class,blockMirrorURIs); List<BlockObject> blockObjects=new ArrayList<BlockObject>(); while (blockMirrors.hasNext()) { blockObjects.add(blockMirrors.next()); } migrate(blockObjects); }
Update the BlockMirror object to migrate the old consistencyGroup field into the new consistencyGroup list field.
private int addToPopulation(Solution solution){ int id=nextFreeId(); solutions.put(id,solution); return id; }
Adds the specified solution to the population, returning its assigned identifier.
public MidiPortWrapper(MidiDeviceInfo info,int portType,int portIndex){ mInfo=info; mType=portType; mPortIndex=portIndex; }
Wrapper for a MIDI device and port description.
public static Validator<CharSequence> emailAddress(@NonNull final CharSequence errorMessage){ return new EmailAddressValidator(errorMessage); }
Creates and returns a validator, which allows to validate texts to ensure, that they represent valid email addresses. Empty texts are also accepted.
public final void writeFloat(float v) throws IOException { this.size+=4; }
Writes a <code>float</code> value, which is comprised of four bytes, to the output stream. It does this as if it first converts this <code>float</code> value to an <code>int</code> in exactly the manner of the <code>Float.floatToIntBits</code> method and then writes the <code>int</code> value in exactly the manner of the <code>writeInt</code> method. The bytes written by this method may be read by the <code>readFloat</code> method of interface <code>DataInput</code>, which will then return a <code>float</code> equal to <code>v</code>.
public Terrain(int terrainSize,float scale,float minY,float maxY,String heightMapFile,String textureFile,int textInc) throws Exception { this.terrainSize=terrainSize; gameItems=new GameItem[terrainSize * terrainSize]; BufferedImage heightMapImage=ImageIO.read(getClass().getResourceAsStream(heightMapFile)); verticesPerCol=heightMapImage.getWidth() - 1; verticesPerRow=heightMapImage.getHeight() - 1; heightMapMesh=new HeightMapMesh(minY,maxY,heightMapImage,textureFile,textInc); boundingBoxes=new Rectangle2D.Float[terrainSize][terrainSize]; for (int row=0; row < terrainSize; row++) { for (int col=0; col < terrainSize; col++) { float xDisplacement=(col - ((float)terrainSize - 1) / (float)2) * scale * HeightMapMesh.getXLength(); float zDisplacement=(row - ((float)terrainSize - 1) / (float)2) * scale * HeightMapMesh.getZLength(); GameItem terrainBlock=new GameItem(heightMapMesh.getMesh()); terrainBlock.setScale(scale); terrainBlock.setPosition(xDisplacement,0,zDisplacement); gameItems[row * terrainSize + col]=terrainBlock; boundingBoxes[row][col]=getBoundingBox(terrainBlock); } } }
A Terrain is composed by blocks, each block is a GameItem constructed from a HeightMap.