code
stringlengths
10
174k
nl
stringlengths
3
129k
private static void runTests2(){ Graph g=GraphConverter.convert("X1-->X2,X3-->X2,X4-->X5"); HashMap<String,Integer> nd=new HashMap<>(); nd.put("X1",0); nd.put("X2",0); nd.put("X3",4); nd.put("X4",4); nd.put("X5",4); g=MixedUtils.makeMixedGraph(g,nd); GeneralizedSemPm pm=MixedUtils.GaussianCategoricalPm(g,"Split(-1.5,-.5,.5,1.5)"); System.out.println(pm); GeneralizedSemIm im=MixedUtils.GaussianCategoricalIm(pm); System.out.println(im); int samps=1000; DataSet ds=im.simulateDataAvoidInfinity(samps,false); ds=MixedUtils.makeMixedData(ds,nd); double lambda=0; MGM model=new MGM(ds,new double[]{lambda,lambda,lambda}); System.out.println("Init nll: " + model.smoothValue(model.params.toMatrix1D())); System.out.println("Init reg term: " + model.nonSmoothValue(model.params.toMatrix1D())); model.learn(1e-8,1000); System.out.println("Learned nll: " + model.smoothValue(model.params.toMatrix1D())); System.out.println("Learned reg term: " + model.nonSmoothValue(model.params.toMatrix1D())); System.out.println("params:\n" + model.params); System.out.println("adjMat:\n" + model.adjMatFromMGM()); }
test non penalty use cases
public void accept(MemberValueVisitor visitor){ visitor.visitDoubleMemberValue(this); }
Accepts a visitor.
public boolean hasSectionId(){ return hasExtension(GwoSectionId.class); }
Returns whether it has the section ID.
public IDevice learnEntity(long macAddress,Short vlan,Integer ipv4Address,Long switchDPID,Integer switchPort){ return learnEntity(macAddress,vlan,ipv4Address,switchDPID,switchPort,true); }
Learn a device using the given characteristics.
public static JMenuItem addMenuItem(String actionName,String iconName,KeyStroke ks,JMenu menu,ActionListener al){ if (iconName == null) iconName=actionName; String text=Msg.getMsg(Env.getCtx(),actionName); ImageIcon icon=Env.getImageIcon2(iconName + "16"); CMenuItem mi=new CMenuItem(text,icon); mi.setActionCommand(actionName); if (ks != null) mi.setAccelerator(ks); if (menu != null) menu.add(mi); if (al != null) mi.addActionListener(al); return mi; }
Create Menu Item.
@Override public final void perform(IR ir){ this.ir=ir; translateFromSSA(ir); ir.HIRInfo.dictionary=null; ir.actualSSAOptions=null; branchOpts.perform(ir,true); ir.HIRInfo.dominatorsAreComputed=false; }
perform the main out-of-ssa transformation
public void decrementRunCount(){ count--; if (count <= 0) { synchronized (RequestAPITest.syncObj) { RequestAPITest.syncObj.notifyAll(); } } }
Decrement the run count. If this returns to zero notify any test waiting.
public SpanishAnalyzer(CharArraySet stopwords){ this(stopwords,CharArraySet.EMPTY_SET); }
Builds an analyzer with the given stop words.
public boolean hasNotes(){ return getNotes() != null; }
Returns whether it has the notes.
public StructSet(Collection c,StructType structType){ this.contents=new ObjectOpenCustomHashSet(c,new ObjectArrayHashingStrategy()); if (structType == null) { throw new IllegalArgumentException(LocalizedStrings.StructSet_STRUCTTYPE_MUST_NOT_BE_NULL.toLocalizedString()); } this.structType=structType; }
takes collection of Object[] fieldValues *or* another StructSet
public double length(){ return Math.sqrt(x * x + y * y + z * z); }
Get the length of the vector.
public static void unescapeXml(Writer writer,String str) throws IOException { if (writer == null) { throw new IllegalArgumentException("The Writer must not be null."); } if (str == null) { return; } Entities.XML.unescape(writer,str); }
<p>Unescapes a string containing XML entity escapes to a string containing the actual Unicode characters corresponding to the escapes.</p> <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos). Does not support DTDs or external entities.</p> <p>Feeder that numerical \\u unicode codes are unescaped to their respective unicode characters. This may change in future releases. </p>
public void update(final T dataItem){ if (dataItem == null) return; if (gadget_ == null) gadget_=ItemsSketch.getInstance(k_,comparator_); gadget_.update(dataItem); }
Update this union with the given double (or float) data Item.
public void test_restartSafe_oneWriteNoCommit(){ IAtomicStore store=(IAtomicStore)getStore(); try { assertTrue(store.isStable()); final Random r=new Random(); final int len=100; final byte[] expected=new byte[len]; r.nextBytes(expected); final ByteBuffer tmp=ByteBuffer.wrap(expected); final long addr1=store.write(tmp); assertEquals(len,tmp.position()); assertEquals(tmp.position(),tmp.limit()); final ByteBuffer actual=store.read(addr1); assertEquals(expected,actual); assertEquals(0,actual.position()); assertEquals(expected.length,actual.limit()); store=(IAtomicStore)reopenStore(store); assertTrue(store.isStable()); try { store.read(addr1); fail("Expecting: " + IllegalArgumentException.class); } catch ( RuntimeException ex) { if (InnerCause.isInnerCause(ex,IllegalArgumentException.class)) { if (log.isInfoEnabled()) log.info("Ignoring expected exception: " + ex); } else { fail("Expecting inner cause: " + IllegalArgumentException.class + ", not: "+ ex,ex); } } } finally { store.destroy(); } }
Writes a record, verifies the write but does NOT commit the store. Closes and reopens the store and finally verifies the write was lost.
public AlertIdWithTimestamp(){ }
Creates a new AlertIdWithTimestamp object.
public int numFeatures(){ if (features == null) { return 0; } else { return features.size(); } }
Num features.
private final void notifyConnectionClosed(OFConnection connection){ connection.getListener().connectionClosed(connection); }
Notifies the channel listener that we our connection has been closed
public void registerMetrics(MetricsCollector metricsCollector){ SystemConfig systemConfig=(SystemConfig)SingletonRegistry.INSTANCE.getSingleton(SystemConfig.HERON_SYSTEM_CONFIG); int interval=systemConfig.getHeronMetricsExportIntervalSec(); metricsCollector.registerMetric("__jvm-gc-collection-time-ms",jvmGCTimeMs,interval); metricsCollector.registerMetric("__jvm-gc-collection-count",jvmGCCount,interval); metricsCollector.registerMetric("__jvm-gc-time-ms",jvmGCTimeMsPerGCType,interval); metricsCollector.registerMetric("__jvm-gc-count",jvmGCCountPerGCType,interval); metricsCollector.registerMetric("__jvm-uptime-secs",jvmUpTimeSecs,interval); metricsCollector.registerMetric("__jvm-thread-count",jvmThreadCount,interval); metricsCollector.registerMetric("__jvm-daemon-thread-count",jvmDaemonThreadCount,interval); metricsCollector.registerMetric("__jvm-process-cpu-time-nanos",processCPUTimeNs,interval); metricsCollector.registerMetric("__jvm-threads-cpu-time-nanos",threadsCPUTimeNs,interval); metricsCollector.registerMetric("__jvm-other-threads-cpu-time-nanos",otherThreadsCPUTimeNs,interval); metricsCollector.registerMetric("__jvm-threads-user-cpu-time-nanos",threadsUserCPUTimeNs,interval); metricsCollector.registerMetric("__jvm-other-threads-user-cpu-time-nanos",otherThreadsUserCPUTimeNs,interval); metricsCollector.registerMetric("__jvm-process-cpu-load",processCPULoad,interval); metricsCollector.registerMetric("__jvm-fd-count",fdCount,interval); metricsCollector.registerMetric("__jvm-fd-limit",fdLimit,interval); metricsCollector.registerMetric("__jvm-memory-free-mb",jvmMemoryFreeMB,interval); metricsCollector.registerMetric("__jvm-memory-used-mb",jvmMemoryUsedMB,interval); metricsCollector.registerMetric("__jvm-memory-mb-total",jvmMemoryTotalMB,interval); metricsCollector.registerMetric("__jvm-memory-heap-mb-used",jvmMemoryHeapUsedMB,interval); metricsCollector.registerMetric("__jvm-memory-heap-mb-committed",jvmMemoryHeapCommittedMB,interval); metricsCollector.registerMetric("__jvm-memory-heap-mb-max",jvmMemoryHeapMaxMB,interval); metricsCollector.registerMetric("__jvm-memory-non-heap-mb-used",jvmMemoryNonHeapUsedMB,interval); metricsCollector.registerMetric("__jvm-memory-non-heap-mb-committed",jvmMemoryNonHeapCommittedMB,interval); metricsCollector.registerMetric("__jvm-memory-non-heap-mb-max",jvmMemoryNonHeapMaxMB,interval); metricsCollector.registerMetric("__jvm-peak-usage",jvmPeakUsagePerMemoryPool,interval); metricsCollector.registerMetric("__jvm-collection-usage",jvmCollectionUsagePerMemoryPool,interval); metricsCollector.registerMetric("__jvm-estimated-usage",jvmEstimatedUsagePerMemoryPool,interval); metricsCollector.registerMetric("__jvm-buffer-pool",jvmBufferPoolMemoryUsage,interval); }
Register metrics with the metrics collector
public CheckTourTimer(GuidedTour guidedTour){ this.guidedTour=guidedTour; }
Build instance of timer around the given tour
public void markDirty(){ this.chunkData.markDirty(); }
Marks the data as dirty
int countStackFrames(){ return vmdata.countStackFrames(); }
Count the stack frames of this thread
public String toString(){ StringBuffer result=new StringBuffer(); int temp; temp=ipAddress & 0x000000FF; result.append(temp); result.append("."); temp=(ipAddress >> 8) & 0x000000FF; result.append(temp); result.append("."); temp=(ipAddress >> 16) & 0x000000FF; result.append(temp); result.append("."); temp=(ipAddress >> 24) & 0x000000FF; result.append(temp); return result.toString(); }
Return the string representation of the IP Address following the common decimal-dotted notation xxx.xxx.xxx.xxx.
private ActivityFacility findActivityLocation(String actType,Coord coordStart,Coord coordEnd){ Coord coord=CoordUtils.createCoord((coordStart.getX() + coordEnd.getX()) / 2.0,(coordStart.getY() + coordEnd.getY()) / 2.0); if (actType.equals("leisure")) return (ActivityFacility)leisureFacilityQuadTree.getClosest(coord.getX(),coord.getY()); else if (actType.equals("shop")) return (ActivityFacility)shopFacilityQuadTree.getClosest(coord.getX(),coord.getY()); else throw new NullPointerException("The activity type: " + actType + " ,is not known!"); }
Approximate the location of the new activity by choosing the closest location at the middle point between the neighbouring activities.
public String requestId(){ return requestId; }
Returns request ID.
public void parseVectorDrawable(){ if (ManageInputArguments()) { return; } fileSize=args.length; analyseTrimAndDebugOption(); loadFilesInMemory(); if (exceptionOccursWhenLoadingFiles) { printer.printHelp(); return; } findWorkingDirectoryPath(); if (BuildVectorDrawablesFromFiles()) { return; } vectAlignThePath(); ResultGenerator generator=new ResultGenerator(absoluteWorkingDirectoryPath,vectorDrawables); try { generator.launchGeneration(); } catch ( IOException e) { CustomLogger.logError("Danm fuck the generation failed",e); } }
Main method to parse the VectorDrawable and generate the output files
private void addRoomFeatures(Set extRoomFeatures,Room room,org.hibernate.Session hibSession){ Set roomFeatures=room.getFeatures(); Iterator f=extRoomFeatures.iterator(); Collection globalRoomFeatures=RoomFeature.getAllGlobalRoomFeatures(room.getSession()); while (f.hasNext()) { ExternalRoomFeature extRoomFeature=(ExternalRoomFeature)f.next(); String featureValue=extRoomFeature.getValue(); Iterator g=globalRoomFeatures.iterator(); while (g.hasNext()) { RoomFeature globalFeature=(RoomFeature)g.next(); if (globalFeature.getLabel().equalsIgnoreCase(featureValue)) { globalFeature.getRooms().add((Location)room); hibSession.save(globalFeature); roomFeatures.add(globalFeature); break; } } } room.setFeatures(roomFeatures); return; }
Add room features
public final <V>SynchronizedGenericMatrix<V> synchronizedMatrix(GenericMatrix<V> matrix){ return new SynchronizedGenericMatrix<V>(matrix); }
Wraps another Matrix so that all methods are executed synchronized.
public static void reboot(String into,InetSocketAddress adbSockAddr,Device device) throws TimeoutException, AdbCommandRejectedException, IOException { byte[] request; if (into == null) { request=formAdbRequest("reboot:"); } else { request=formAdbRequest("reboot:" + into); } try (SocketChannel adbChan=SocketChannel.open(adbSockAddr)){ adbChan.configureBlocking(false); setDevice(adbChan,device); write(adbChan,request); } }
Reboot the device.
private static void prepareLoggingSystemEnviroment(){ System.setProperty("log.directory",getLogFolder()); }
Initialize the logging system.
public static _Fields findByThriftId(int fieldId){ switch (fieldId) { case 1: return NODE_ID; case 2: return VERSION; default : return null; } }
Find the _Fields constant that matches fieldId, or null if its not found.
@Override public void requestLocationSuccess(String locationName){ weatherUtils.requestWeather(locationName,this); getLocation().realLocation=locationName; DatabaseHelper.getInstance(this).insertLocation(getLocation()); }
<br> interface.
public Enumeration<Option> listOptions(){ Vector<Option> newVector=new Vector<Option>(1); newVector.addElement(new Option("\tRandom number seed.\n" + "\t(default 1)","S",1,"-S <num>")); newVector.addAll(Collections.list(super.listOptions())); return newVector.elements(); }
Returns an enumeration describing the available options.
public Facet createFacet(){ FacetImpl facet=new FacetImpl(); return facet; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void start(){ invokeAction(null); }
Starts all the invocations.
public void stop(){ if (drivingClip != null) { drivingClip.stop(); } if (turningClip != null) { turningClip.stop(); } }
Stops current clips
TagStack(TagElement tag,TagStack next){ this.tag=tag; this.elem=tag.getElement(); this.next=next; Element elem=tag.getElement(); if (elem.getContent() != null) { this.state=new ContentModelState(elem.getContent()); } if (next != null) { inclusions=next.inclusions; exclusions=next.exclusions; pre=next.pre; } if (tag.isPreformatted()) { pre=true; } if (elem.inclusions != null) { if (inclusions != null) { inclusions=(BitSet)inclusions.clone(); inclusions.or(elem.inclusions); } else { inclusions=elem.inclusions; } } if (elem.exclusions != null) { if (exclusions != null) { exclusions=(BitSet)exclusions.clone(); exclusions.or(elem.exclusions); } else { exclusions=elem.exclusions; } } }
Construct a stack element.
@Override public void mouseReleased(){ isDragging=false; inputManager.releaseElement(this); }
User must call this method to receive layout events relevant to mouse releases.
public T cache(String url,long expire){ return ajax(url,byte[].class,expire,null,null); }
Cache the url to file cache without any callback.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public SIPETagParser(String etag){ super(etag); }
Creates a new instance of PriorityParser
private boolean varrayHasPoolMatchingHaVpool(String nhId,List<StoragePool> haCosPoolList){ for ( StoragePool haCosPool : haCosPoolList) { StringSet poolNHs=haCosPool.getTaggedVirtualArrays(); if (poolNHs != null && poolNHs.contains(nhId)) { return true; } } return false; }
Determine if the varray with the passed id has a storage pool that satisfies the HA CoS.
public static InteriorIntersectionFinder createIntersectionCounter(LineIntersector li){ InteriorIntersectionFinder finder=new InteriorIntersectionFinder(li); finder.setFindAllIntersections(true); finder.setKeepIntersections(false); return finder; }
Creates an intersection finder which counts all interior intersections. The intersections are note recorded to reduce memory usage.
public final void execute() throws Exception { ConfProxyHelper.purgeOutdatedGenerations(conf); ConfigurationDirectory confDir=download(); OutputBuilder output=new OutputBuilder(confDir,conf); output.buildSignedDirectory(); output.moveAndCleanup(); }
Launch the configuration proxy instance. Downloads signed directory, signs it's content and moves it to the public distribution directory.
public void visitCode(){ if (mv != null) { mv.visitCode(); } }
Starts the visit of the method's code, if any (i.e. non abstract method).
static String formatTenthsOfSecond(int tenthsOfSecond){ int seconds=tenthsOfSecond / 10; int tenths=tenthsOfSecond - seconds * 10; return seconds + "." + tenths; }
Formats a value expressing tenths of a second. For example, <code>328</code> is formatted as <code>32.8</code>. <p> Note: This does NOT correct for South or West (negative angles).
void makeAntecedent(){ String str=""; if (_variableList.size() != 0) { String not=Bundle.getMessage("LogicNOT").toLowerCase(); String row="R"; String and=" " + Bundle.getMessage("LogicAND").toLowerCase() + " "; String or=" " + Bundle.getMessage("LogicOR").toLowerCase() + " "; if (_variableList.get(0).isNegated()) { str=not + " "; } str=str + row + "1"; for (int i=1; i < _variableList.size(); i++) { ConditionalVariable variable=_variableList.get(i); switch (variable.getOpern()) { case Conditional.OPERATOR_AND: str=str + and; break; case Conditional.OPERATOR_OR: str=str + or; break; default : break; } if (variable.isNegated()) { str=str + not + " "; } str=str + row + (i + 1); if (i > 0 && i + 1 < _variableList.size()) { str="(" + str + ")"; } } } _antecedent=str; _antecedentField.setText(_antecedent); _showReminder=true; }
build the antecedent statement
private Annotation generateAnnotation(){ return AnnotationParser.annotationForMap(annoType,getAllReflectedValues()); }
Returns a dynamic proxy for an annotation mirror.
private void markSubroutineWalkDFS(final BitSet sub,int index,final BitSet anyvisited){ while (true) { AbstractInsnNode node=instructions.get(index); if (sub.get(index)) { return; } sub.set(index); if (anyvisited.get(index)) { dualCitizens.set(index); if (LOGGING) { log("Instruction #" + index + " is dual citizen."); } } anyvisited.set(index); if (node.getType() == AbstractInsnNode.JUMP_INSN && node.getOpcode() != JSR) { JumpInsnNode jnode=(JumpInsnNode)node; int destidx=instructions.indexOf(jnode.label); markSubroutineWalkDFS(sub,destidx,anyvisited); } if (node.getType() == AbstractInsnNode.TABLESWITCH_INSN) { TableSwitchInsnNode tsnode=(TableSwitchInsnNode)node; int destidx=instructions.indexOf(tsnode.dflt); markSubroutineWalkDFS(sub,destidx,anyvisited); for (int i=tsnode.labels.size() - 1; i >= 0; --i) { LabelNode l=tsnode.labels.get(i); destidx=instructions.indexOf(l); markSubroutineWalkDFS(sub,destidx,anyvisited); } } if (node.getType() == AbstractInsnNode.LOOKUPSWITCH_INSN) { LookupSwitchInsnNode lsnode=(LookupSwitchInsnNode)node; int destidx=instructions.indexOf(lsnode.dflt); markSubroutineWalkDFS(sub,destidx,anyvisited); for (int i=lsnode.labels.size() - 1; i >= 0; --i) { LabelNode l=lsnode.labels.get(i); destidx=instructions.indexOf(l); markSubroutineWalkDFS(sub,destidx,anyvisited); } } switch (instructions.get(index).getOpcode()) { case GOTO: case RET: case TABLESWITCH: case LOOKUPSWITCH: case IRETURN: case LRETURN: case FRETURN: case DRETURN: case ARETURN: case RETURN: case ATHROW: return; } index++; if (index >= instructions.size()) { return; } } }
Performs a simple DFS of the instructions, assigning each to the subroutine <code>sub</code>. Starts from <code>index</code>. Invoked only by <code>markSubroutineWalk()</code>.
public void purgeEvents(Long low,Long high) throws ReplicatorException { LogConnection conn=diskLog.connect(false); try { conn.delete(low,high); conn.release(); } catch ( InterruptedException e) { logger.warn("Delete operation was interrupted!"); } logger.info("Transactions deleted"); }
Purge THL events in the given seqno interval.
@Override public String formatCookie(final Cookie cookie){ LOG.trace("enter CookieSpecBase.formatCookie(Cookie)"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } final StringBuffer buf=new StringBuffer(); buf.append(cookie.getName()); buf.append("="); final String s=cookie.getValue(); if (s != null) { buf.append(s); } return buf.toString(); }
Return a string suitable for sending in a <tt>"Cookie"</tt> header
public final boolean owns(ConditionObject condition){ if (condition == null) throw new NullPointerException(); return condition.isOwnedBy(this); }
Queries whether the given ConditionObject uses this synchronizer as its lock.
private List<String> determineProxies() throws XMPPException { ServiceDiscoveryManager serviceDiscoveryManager=ServiceDiscoveryManager.getInstanceFor(this.connection); List<String> proxies=new ArrayList<String>(); DiscoverItems discoverItems=serviceDiscoveryManager.discoverItems(this.connection.getServiceName()); Iterator<Item> itemIterator=discoverItems.getItems(); while (itemIterator.hasNext()) { Item item=itemIterator.next(); if (this.proxyBlacklist.contains(item.getEntityID())) { continue; } try { DiscoverInfo proxyInfo; proxyInfo=serviceDiscoveryManager.discoverInfo(item.getEntityID()); Iterator<Identity> identities=proxyInfo.getIdentities(); while (identities.hasNext()) { Identity identity=identities.next(); if ("proxy".equalsIgnoreCase(identity.getCategory()) && "bytestreams".equalsIgnoreCase(identity.getType())) { proxies.add(item.getEntityID()); break; } this.proxyBlacklist.add(item.getEntityID()); } } catch ( XMPPException e) { this.proxyBlacklist.add(item.getEntityID()); } } return proxies; }
Returns a list of JIDs of SOCKS5 proxies by querying the XMPP server. The SOCKS5 proxies are in the same order as returned by the XMPP server.
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; int row, col, x, y; float progress=0; double z; double currentVal; int i; int[] dX=new int[]{1,1,1,0,-1,-1,-1,0}; int[] dY=new int[]{-1,0,1,1,1,0,-1,-1}; double[] inflowingVals=new double[]{16,32,64,128,1,2,4,8}; double numInNeighbours; boolean flag=false; double flowDir=0; double flowLength=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]; } } if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster pntr=new WhiteboxRaster(inputHeader,"r"); int rows=pntr.getNumberRows(); int cols=pntr.getNumberColumns(); double noData=pntr.getNoDataValue(); double gridResX=pntr.getCellSizeX(); double gridResY=pntr.getCellSizeY(); double diagGridRes=Math.sqrt(gridResX * gridResX + gridResY * gridResY); double[] gridLengths=new double[]{diagGridRes,gridResX,diagGridRes,gridResY,diagGridRes,gridResX,diagGridRes,gridResY}; WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); output.setPreferredPalette("blueyellow.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); output.setZUnits("dimensionless"); WhiteboxRaster tmpGrid=new WhiteboxRaster(outputHeader.replace(".dep","_temp.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); tmpGrid.isTemporaryFile=true; updateProgress("Loop 1 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (pntr.getValue(row,col) != noData) { z=0; for (i=0; i < 8; i++) { if (pntr.getValue(row + dY[i],col + dX[i]) == inflowingVals[i]) { z++; } } tmpGrid.setValue(row,col,z); } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress("Loop 1 of 2:",(int)progress); } updateProgress("Loop 2 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (tmpGrid.getValue(row,col) == 0) { tmpGrid.setValue(row,col,-1); flag=false; x=col; y=row; do { flowLength=output.getValue(y,x); flowDir=pntr.getValue(y,x); if (flowDir > 0) { i=(int)(Math.log(flowDir) / LnOf2); flowLength+=gridLengths[i]; x+=dX[i]; y+=dY[i]; currentVal=output.getValue(y,x); if (flowLength > currentVal) { output.setValue(y,x,flowLength); } numInNeighbours=tmpGrid.getValue(y,x) - 1; tmpGrid.setValue(y,x,numInNeighbours); if (numInNeighbours == 0) { tmpGrid.setValue(y,x,-1); flag=true; } else { flag=false; } } else { flag=false; } } while (flag); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress("Loop 2 of 2:",(int)progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); tmpGrid.close(); 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.
public <T>T read(T value,File source,boolean strict) throws Exception { InputStream file=new FileInputStream(source); try { return read(value,file,strict); } finally { file.close(); } }
This <code>read</code> method will read the contents of the XML document from the provided source and populate the object with the values deserialized. This is used as a means of injecting an object with values deserialized from an XML document. If the XML source cannot be deserialized or there is a problem building the object graph an exception is thrown.
private void mergeCollapse(){ while (stackSize > 1) { int n=stackSize - 2; if (n > 0 && runLen[n - 1] <= runLen[n] + runLen[n + 1]) { if (runLen[n - 1] < runLen[n + 1]) n--; mergeAt(n); } else if (runLen[n] <= runLen[n + 1]) { mergeAt(n); } else { break; } } }
Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] 2. runLen[i - 2] > runLen[i - 1] This method is called each time a new run is pushed onto the stack, so the invariants are guaranteed to hold for i < stackSize upon entry to the method.
public boolean isHttpsEnabled(){ ProxyPreference preference=getProxyDao().get(ProxyKey.HTTPS_ENABLED); if ((preference == null) || StringUtils.isEmpty(preference.getValue())) { return false; } else { return Boolean.valueOf(preference.getValue()).booleanValue(); } }
Returns true if the HTTPS proxy must be enabled.
public boolean hasTitle(){ return super.hasElement(Source.TITLE); }
Returns whether it has the title.
public JSearchPanel createSearchPanel(){ return createSearchPanel(m_set instanceof PrefixSearchTupleSet); }
Create a new search text panel for searching over the data.
public ICalReader(InputStream in){ this(in,ICalVersion.V2_0); }
Creates a new iCalendar reader.
public int readEnum() throws IOException { return readRawVarint32(); }
Read an enum field value from the stream. Caller is responsible for converting the numeric value to an actual enum.
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); for (Node<K,V> n=findFirst(); n != null; n=n.next) { V v=n.getValidValue(); if (v != null) { s.writeObject(n.key); s.writeObject(v); } } s.writeObject(null); }
Saves this map to a stream (that is, serializes it).
private void createPackageDefinition(String className){ int i=className.lastIndexOf('.'); if (i != -1) { String pkgname=className.substring(0,i); Package pkg=getPackage(pkgname); if (pkg == null) { definePackage(pkgname,null,null,null,null,null,null,null); logger.info("Defined package (3): " + getPackage(pkgname) + ", "+ getPackage(pkgname).hashCode()); } } }
Before a new class is defined, we need to create a package definition for it
public static boolean isAnnotationPresent(Class c,Class<? extends Annotation> annotationType){ return getAnnotation(c,annotationType) != null; }
Returns true if an annotation for the specified type is present on this element, else false.
public boolean hasFeature(String s){ return FEATURES.contains(s); }
Tells whether the given feature is supported by this user agent.
public void updateAveragedOutlier(){ double totalXCoords=0.0; double totalYCoords=0.0; int size=getItemCount(); for (Iterator iterator=this.outliers.iterator(); iterator.hasNext(); ) { Outlier o=(Outlier)iterator.next(); totalXCoords+=o.getX(); totalYCoords+=o.getY(); } getAveragedOutlier().getPoint().setLocation(new Point2D.Double(totalXCoords / size,totalYCoords / size)); }
Updates the averaged outlier.
private static void openDefaultUnixBrowser(final String url) throws Exception { String cmd="xdg-open " + url; Process p=Runtime.getRuntime().exec(cmd); p.waitFor(); if (p.exitValue() != 0) { throw new RuntimeException("Unix Exec Error/xdg-open: " + errorResponse(p)); } }
Tries to open the default browser on Unix platform.
@Override public Object signature(final FormObject form){ final JButton sigBut=new JButton(); setupButton(sigBut,form); setupUniversalFeatures(sigBut,form); final boolean[] flags=form.getFieldFlags(); if (flags != null && flags[FormObject.READONLY_ID]) { sigBut.setEnabled(false); sigBut.setDisabledIcon(sigBut.getIcon()); sigBut.setDisabledSelectedIcon(sigBut.getSelectedIcon()); } if (!form.isAppearanceUsed()) { sigBut.setOpaque(false); final BufferedImage img=new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB); final Graphics2D imgG2=img.createGraphics(); imgG2.setPaint(new Color(221,228,255,175)); imgG2.fillRect(0,0,1,1); sigBut.setIcon(new FixImageIcon(form,img,0)); } return sigBut; }
setup and return a signature field component, <b>Note:</b> SKELETON METHOD FOR FUTURE UPGRADES.
public void xor(BitVector set){ int setLength=set.bits.length; for (int i=setLength; i-- > 0; ) { bits[i]^=set.bits[i]; } }
Logically XORs this bit set with the specified set of bits.
public ExceptionRule(Recurrence recur){ super(recur); }
Creates a new exception rule property.
public Graph<T> toMain(){ return to(new ThreadNode<>(true)); }
Transfers the execution to the main thread.
private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i=lruEntries.values().iterator(); i.hasNext(); ) { Entry entry=i.next(); if (entry.currentEditor == null) { for (int t=0; t < valueCount; t++) { size+=entry.lengths[t]; } } else { entry.currentEditor=null; for (int t=0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } }
Computes the initial size and collects garbage as a part of opening the cache. Dirty entries are assumed to be inconsistent and will be deleted.
public AnnotationVisitor visitAnnotation(String desc,boolean visible){ if (mv != null) { return mv.visitAnnotation(desc,visible); } return null; }
Visits an annotation of this method.
String readString() throws IOException { int utf16len=readUnsignedLeb128(); byte inBuf[]=new byte[utf16len * 3]; int idx; for (idx=0; idx < inBuf.length; idx++) { byte val=readByte(); if (val == 0) break; inBuf[idx]=val; } return new String(inBuf,0,idx,"UTF-8"); }
Reads a UTF-8 string. We don't know how long the UTF-8 string is, so we have to read one byte at a time. We could make an educated guess based on the utf16_size and seek back if we get it wrong, but seeking backward may cause the underlying implementation to reload I/O buffers.
public Object runSafely(Catbert.FastStack stack) throws Exception { long x=getLong(stack); return (x == 0) ? "" : Sage.tfjLong(x); }
Returns a formatted time string using the java.text.DateFormat.LONG formatting technique
protected File createTempFile() throws IOException { return createTempFile(""); }
Creates a file in the system's default folder for temporary files. The file/directory automatically gets removed during tearDown. The name of the created file begins with 'gerrit_test_', and is located in the system's default folder for temporary files.
public void update(long n){ uncounted.addAndGet(n); }
Update the moving average with a new value.
public T casePropertyAttribute(PropertyAttribute object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Property Attribute</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
public void addLongSelectionListener(SelectionListener listener){ if (listener == null) throw new IllegalArgumentException(); if (hexEditControl == null) { if (listOfLongListeners == null) listOfLongListeners=new ArrayList<>(); listOfLongListeners.add(listener); } else { hexEditControl.addLongSelectionListener(listener); } }
Adds a long selection listener. Events sent to the listener have long start and end points.
private void initialize(URI p_other){ m_scheme=p_other.getScheme(); m_userinfo=p_other.getUserinfo(); m_host=p_other.getHost(); m_port=p_other.getPort(); m_path=p_other.getPath(); m_queryString=p_other.getQueryString(); m_fragment=p_other.getFragment(); }
Initialize all fields of this URI from another URI.
public AbViewInfo(View view,int width,int height,int top,int bottom){ super(); this.view=view; this.width=width; this.height=height; this.top=top; this.bottom=bottom; }
Instantiates a new ab view info.
public TextMimeEncoder(){ }
Creates a TextMimeEncoder.
private void validateBusinessObjectDataStorageFilesCreateRequest(BusinessObjectDataStorageFilesCreateRequest businessObjectDataStorageFilesCreateRequest){ Assert.hasText(businessObjectDataStorageFilesCreateRequest.getNamespace(),"A namespace must be specified."); businessObjectDataStorageFilesCreateRequest.setNamespace(businessObjectDataStorageFilesCreateRequest.getNamespace().trim()); Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectDefinitionName(),"A business object definition name must be specified."); businessObjectDataStorageFilesCreateRequest.setBusinessObjectDefinitionName(businessObjectDataStorageFilesCreateRequest.getBusinessObjectDefinitionName().trim()); Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatUsage(),"A business object format usage must be specified."); businessObjectDataStorageFilesCreateRequest.setBusinessObjectFormatUsage(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatUsage().trim()); Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatFileType(),"A business object format file type must be specified."); businessObjectDataStorageFilesCreateRequest.setBusinessObjectFormatFileType(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatFileType().trim()); Assert.notNull(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatVersion(),"A business object format version must be specified."); Assert.hasText(businessObjectDataStorageFilesCreateRequest.getPartitionValue(),"A partition value must be specified."); businessObjectDataStorageFilesCreateRequest.setPartitionValue(businessObjectDataStorageFilesCreateRequest.getPartitionValue().trim()); int subPartitionValuesCount=CollectionUtils.size(businessObjectDataStorageFilesCreateRequest.getSubPartitionValues()); Assert.isTrue(subPartitionValuesCount <= BusinessObjectDataEntity.MAX_SUBPARTITIONS,String.format("Exceeded maximum number of allowed subpartitions: %d.",BusinessObjectDataEntity.MAX_SUBPARTITIONS)); for (int i=0; i < subPartitionValuesCount; i++) { Assert.hasText(businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().get(i),"A subpartition value must be specified."); businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().set(i,businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().get(i).trim()); } Assert.notNull(businessObjectDataStorageFilesCreateRequest.getBusinessObjectDataVersion(),"A business object data version must be specified."); Assert.hasText(businessObjectDataStorageFilesCreateRequest.getStorageName(),"A storage name must be specified."); businessObjectDataStorageFilesCreateRequest.setStorageName(businessObjectDataStorageFilesCreateRequest.getStorageName().trim()); if (BooleanUtils.isTrue(businessObjectDataStorageFilesCreateRequest.isDiscoverStorageFiles())) { Assert.isTrue(CollectionUtils.isEmpty(businessObjectDataStorageFilesCreateRequest.getStorageFiles()),"Storage files cannot be specified when discovery of storage files is enabled."); } else { Assert.notEmpty(businessObjectDataStorageFilesCreateRequest.getStorageFiles(),"At least one storage file must be specified when discovery of storage files is not enabled."); Set<String> storageFilePathValidationSet=new HashSet<>(); for ( StorageFile storageFile : businessObjectDataStorageFilesCreateRequest.getStorageFiles()) { Assert.hasText(storageFile.getFilePath(),"A file path must be specified."); storageFile.setFilePath(storageFile.getFilePath().trim()); Assert.notNull(storageFile.getFileSizeBytes(),"A file size must be specified."); if (storageFile.getRowCount() != null) { Assert.isTrue(storageFile.getRowCount() >= 0,"File \"" + storageFile.getFilePath() + "\" has a row count which is < 0."); } if (storageFilePathValidationSet.contains(storageFile.getFilePath())) { throw new IllegalArgumentException(String.format("Duplicate storage file found: %s",storageFile.getFilePath())); } storageFilePathValidationSet.add(storageFile.getFilePath()); } } }
Validates the given request without using any external dependencies (ex. DB). Throws appropriate exceptions when a validation error exists.
public boolean isHalted(){ synchronized (this) { return beenHalted; } }
returns true if someone has halted the thread.
void updateStyle(String ref,JSONObject style){ if (mDestroy || style == null) { return; } WXSDKInstance instance=WXSDKManager.getInstance().getSDKInstance(mInstanceId); WXDomObject domObject=mRegistry.get(ref); if (domObject == null) { if (instance != null) { instance.commitUTStab(IWXUserTrackAdapter.DOM_MODULE,WXErrorCode.WX_ERR_DOM_UPDATESTYLE); } return; } Map<String,Object> animationMap=WXDataStructureUtil.newHashMapWithExpectedSize(2); animationMap.put(WXDomObject.TRANSFORM,style.remove(WXDomObject.TRANSFORM)); animationMap.put(WXDomObject.TRANSFORM_ORIGIN,style.remove(WXDomObject.TRANSFORM_ORIGIN)); animations.add(new Pair<>(ref,animationMap)); if (!style.isEmpty()) { domObject.updateStyle(style); transformStyle(domObject,false); updateStyle(domObject,style); } mDirty=true; if (instance != null) { instance.commitUTStab(IWXUserTrackAdapter.DOM_MODULE,WXErrorCode.WX_SUCCESS); } }
Update styles according to the given style. Then creating a command object for updating corresponding view and put the command object in the queue.
public boolean isSignalMastAssignedAnywhere(SignalMast signalMast){ for ( PositionablePoint po : layoutEditor.pointList) { if ((po.getEastBoundSignalMast() != null) && po.getEastBoundSignalMast() == signalMast) { return true; } if ((po.getWestBoundSignalMast() != null) && po.getWestBoundSignalMast() == signalMast) { return true; } } for ( LayoutTurnout to : layoutEditor.turnoutList) { if ((to.getSignalAMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalBMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalCMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalDMast() != null) && to.getSignalDMast() == signalMast) { return true; } } for ( LayoutSlip to : layoutEditor.slipList) { if ((to.getSignalAMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalBMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalCMast() != null) && to.getSignalDMast() == signalMast) { return true; } if ((to.getSignalDMast() != null) && to.getSignalDMast() == signalMast) { return true; } } for ( LevelXing x : layoutEditor.xingList) { if ((x.getSignalAMast() != null) && x.getSignalAMast() == signalMast) { return true; } if ((x.getSignalBMast() != null) && x.getSignalAMast() == signalMast) { return true; } if ((x.getSignalCMast() != null) && x.getSignalAMast() == signalMast) { return true; } if ((x.getSignalDMast() != null) && x.getSignalAMast() == signalMast) { return true; } } return false; }
Returns true if the specified SignalMast is assigned to an object on the panel, regardless of whether an icon is displayed or not
private void visitBlock(BlockTree node,CollapseEmptyOrNot collapseEmptyOrNot,AllowLeadingBlankLine allowLeadingBlankLine,AllowTrailingBlankLine allowTrailingBlankLine){ sync(node); if (node.isStatic()) { token("static"); builder.space(); } if (collapseEmptyOrNot.isYes() && node.getStatements().isEmpty()) { if (builder.peekToken().equals(Optional.of(";"))) { token(";"); } else { tokenBreakTrailingComment("{",plusTwo); builder.blankLineWanted(BlankLineWanted.NO); token("}",plusTwo); } } else { builder.open(ZERO); builder.open(plusTwo); tokenBreakTrailingComment("{",plusTwo); if (allowLeadingBlankLine == AllowLeadingBlankLine.NO) { builder.blankLineWanted(BlankLineWanted.NO); } else { builder.blankLineWanted(BlankLineWanted.PRESERVE); } visitStatements(node.getStatements()); builder.close(); builder.forcedBreak(); builder.close(); if (allowTrailingBlankLine == AllowTrailingBlankLine.NO) { builder.blankLineWanted(BlankLineWanted.NO); } else { builder.blankLineWanted(BlankLineWanted.PRESERVE); } markForPartialFormat(); token("}",plusTwo); } }
Helper method for blocks.
private double naiveQuery(V obj,WritableDoubleDataStore scores,HashSetModifiableDBIDs cands){ if (obj instanceof SparseNumberVector) { return naiveQuerySparse((SparseNumberVector)obj,scores,cands); } else { return naiveQueryDense(obj,scores,cands); } }
Query the most similar objects, abstract version.
public final void deleteAllEntries(){ if (numEntries > 0) { Arrays.fill(entries,null); this.numEntries=0; } }
Deletes all entries in this node.
public void addGroupColumn(String groupColumnName){ m_groups.add(groupColumnName); }
Add Group Column
public AsyncResult DeleteSubscriptionsAsync(RequestHeader RequestHeader,UnsignedInteger... SubscriptionIds){ DeleteSubscriptionsRequest req=new DeleteSubscriptionsRequest(RequestHeader,SubscriptionIds); return channel.serviceRequestAsync(req); }
Asynchronous DeleteSubscriptions service request.
public Object runSafely(Catbert.FastStack stack) throws Exception { Channel c=getChannel(stack); return Boolean.valueOf((c == null) ? true : c.isViewable()); }
Returns true if there is a configured lineup for which this channel is viewable.
public static void printLibrary(String prefix,CoverageAttributeTable cat){ if (cat == null) { println(prefix,"Library doesn't exist"); return; } println(prefix); String[] coverages=cat.getCoverageNames(); println(prefix,"uses " + (cat.isTiledData() ? "tiled" : "untiled") + " data"); print(prefix,"Coverage names:"); for (int i=0; i < coverages.length; i++) { print(coverages[i]); print(" "); } println(); for (int i=0; i < coverages.length; i++) { printCoverage(prefix + coverages[i] + ":",cat,coverages[i]); } }
Prints a VPF Library
private void assertEventPropertyNull(ReplDBMSEvent event,String name){ String value=event.getDBMSEvent().getMetadataOptionValue(name); DBMSData rawData=event.getData().get(0); String query=((StatementData)rawData).getQuery(); Assert.assertNull("Expected property to be unset: query=" + query + " name="+ name,value); }
Ensures that a particular event property is unset.
public void addTransaction(final Transaction transaction){ this.transactions.add(transaction); }
Adds a new transaction to this block.
public void testIssue709() throws Exception { ObjectMapper mapper=new ObjectMapper(); byte[] inputData=new byte[]{1,2,3}; ObjectNode node=mapper.createObjectNode(); node.put("data",inputData); Issue709Bean result=mapper.readValue(node,Issue709Bean.class); String json=mapper.writeValueAsString(node); Issue709Bean resultFromString=mapper.readValue(json,Issue709Bean.class); Issue709Bean resultFromConvert=mapper.convertValue(node,Issue709Bean.class); Assert.assertArrayEquals(inputData,resultFromString.data); Assert.assertArrayEquals(inputData,resultFromConvert.data); Assert.assertArrayEquals(inputData,result.data); }
Simple test to verify that byte[] values can be handled properly when converting, as long as there is metadata (from POJO definitions).
@Override public boolean equals(Object obj){ if (!(obj instanceof RequestedAddressFamilyAttribute)) return false; if (obj == this) return true; RequestedAddressFamilyAttribute att=(RequestedAddressFamilyAttribute)obj; if (att.getAttributeType() != getAttributeType() || att.getDataLength() != getDataLength() || att.family != family) return false; return true; }
Compares two TURN Attributes. Attributes are considered equal when their type, length, and all data are the same.
public static void perspectiveM(float[] m,int offset,float fovy,float aspect,float zNear,float zFar){ float f=1.0f / (float)Math.tan(fovy * (Math.PI / 360.0)); float rangeReciprocal=1.0f / (zNear - zFar); m[offset + 0]=f / aspect; m[offset + 1]=0.0f; m[offset + 2]=0.0f; m[offset + 3]=0.0f; m[offset + 4]=0.0f; m[offset + 5]=f; m[offset + 6]=0.0f; m[offset + 7]=0.0f; m[offset + 8]=0.0f; m[offset + 9]=0.0f; m[offset + 10]=(zFar + zNear) * rangeReciprocal; m[offset + 11]=-1.0f; m[offset + 12]=0.0f; m[offset + 13]=0.0f; m[offset + 14]=2.0f * zFar * zNear* rangeReciprocal; m[offset + 15]=0.0f; }
Define a projection matrix in terms of a field of view angle, an aspect ratio, and z clip planes
@Override public void execute(String[] params,Server server,Conversation conversation,IRCService service) throws CommandException { if (params.length > 1) { String text=BaseHandler.mergeParams(params); Collection<Conversation> mConversations=server.getConversations(); for ( Conversation currentConversation : mConversations) { if (currentConversation.getType() == Conversation.TYPE_CHANNEL) { Message message=new Message(" " + service.getConnection(server.getId()).getNick() + " - "+ text); currentConversation.addMessage(message); Intent intent=Broadcast.createConversationIntent(Broadcast.CONVERSATION_MESSAGE,server.getId(),currentConversation.getName()); service.sendBroadcast(intent); service.getConnection(server.getId()).sendMessage(currentConversation.getName(),text); } } } else { throw new CommandException(service.getString(R.string.invalid_number_of_params)); } }
Execute /amsg
public Property era(){ return new Property(this,getChronology().era()); }
Get the era property which provides access to advanced functionality.
public String saveFile(String handleId,String relativeFile,InputStream inputStream){ String file=fileHandler.append(getWorkspaceDirectory(handleId),relativeFile); if (inputStream != null) { fileHandler.copy(inputStream,fileHandler.getOutputStream(file)); } return file; }
Saves the input stream to a file, relative to the workspace directory of a container.