code
stringlengths
10
174k
nl
stringlengths
3
129k
public static void main(final String[] args){ DOMTestCase.doMain(namednodemapsetnameditem.class,args); }
Runs this test from the command line.
public static void calibrateNanosConversion(){ long originalMillis=System.currentTimeMillis(); long updatedMillis=originalMillis; while (originalMillis == updatedMillis) { updatedMillis=System.currentTimeMillis(); } referenceNanos=System.nanoTime(); referenceMillis=updatedMillis; secondsOffset=millisToSeconds(referenceMillis) - (double)referenceNanos / (double)NANOS_IN_SECOND; }
Aligns the nano seconds to the start of a new millisecond. This should be called whenever device wakes up from sleep.
public void patch_splitMax(LinkedList<Patch> patches){ short patch_size=Match_MaxBits; String precontext, postcontext; Patch patch; int start1, start2; boolean empty; Operation diff_type; String diff_text; ListIterator<Patch> pointer=patches.listIterator(); Patch bigpatch=pointer.hasNext() ? pointer.next() : null; while (bigpatch != null) { if (bigpatch.length1 <= Match_MaxBits) { bigpatch=pointer.hasNext() ? pointer.next() : null; continue; } pointer.remove(); start1=bigpatch.start1; start2=bigpatch.start2; precontext=""; while (!bigpatch.diffs.isEmpty()) { patch=new Patch(); empty=true; patch.start1=start1 - precontext.length(); patch.start2=start2 - precontext.length(); if (precontext.length() != 0) { patch.length1=patch.length2=precontext.length(); patch.diffs.add(new Diff(Operation.EQUAL,precontext)); } while (!bigpatch.diffs.isEmpty() && patch.length1 < patch_size - Patch_Margin) { diff_type=bigpatch.diffs.getFirst().operation; diff_text=bigpatch.diffs.getFirst().text; if (diff_type == Operation.INSERT) { patch.length2+=diff_text.length(); start2+=diff_text.length(); patch.diffs.addLast(bigpatch.diffs.removeFirst()); empty=false; } else if (diff_type == Operation.DELETE && patch.diffs.size() == 1 && patch.diffs.getFirst().operation == Operation.EQUAL && diff_text.length() > 2 * patch_size) { patch.length1+=diff_text.length(); start1+=diff_text.length(); empty=false; patch.diffs.add(new Diff(diff_type,diff_text)); bigpatch.diffs.removeFirst(); } else { diff_text=diff_text.substring(0,Math.min(diff_text.length(),patch_size - patch.length1 - Patch_Margin)); patch.length1+=diff_text.length(); start1+=diff_text.length(); if (diff_type == Operation.EQUAL) { patch.length2+=diff_text.length(); start2+=diff_text.length(); } else { empty=false; } patch.diffs.add(new Diff(diff_type,diff_text)); if (diff_text.equals(bigpatch.diffs.getFirst().text)) { bigpatch.diffs.removeFirst(); } else { bigpatch.diffs.getFirst().text=bigpatch.diffs.getFirst().text.substring(diff_text.length()); } } } precontext=diff_text2(patch.diffs); precontext=precontext.substring(Math.max(0,precontext.length() - Patch_Margin)); if (diff_text1(bigpatch.diffs).length() > Patch_Margin) { postcontext=diff_text1(bigpatch.diffs).substring(0,Patch_Margin); } else { postcontext=diff_text1(bigpatch.diffs); } if (postcontext.length() != 0) { patch.length1+=postcontext.length(); patch.length2+=postcontext.length(); if (!patch.diffs.isEmpty() && patch.diffs.getLast().operation == Operation.EQUAL) { patch.diffs.getLast().text+=postcontext; } else { patch.diffs.add(new Diff(Operation.EQUAL,postcontext)); } } if (!empty) { pointer.add(patch); } } bigpatch=pointer.hasNext() ? pointer.next() : null; } }
Look through the patches and break up any which are longer than the maximum limit of the match algorithm. Intended to be called only from within patch_apply.
public TipOfTheDayAction(KseFrame kseFrame){ super(kseFrame); putValue(LONG_DESCRIPTION,res.getString("TipOfTheDayAction.statusbar")); putValue(NAME,res.getString("TipOfTheDayAction.text")); putValue(SHORT_DESCRIPTION,res.getString("TipOfTheDayAction.tooltip")); putValue(SMALL_ICON,new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource(res.getString("TipOfTheDayAction.image"))))); }
Construct action.
public boolean canWrite(){ return true; }
Returns true since StringWriter is for writing.
public static <T>T loadSpringBean(InputStream springXmlStream,String beanName) throws IgniteCheckedException { A.notNull(springXmlStream,"springXmlPath"); A.notNull(beanName,"beanName"); IgniteSpringHelper spring=SPRING.create(false); return spring.loadBean(springXmlStream,beanName); }
Loads spring bean by name.
public void printUsage(PrintWriter pw,int width,String app,Options options){ StringBuffer buff=new StringBuffer(defaultSyntaxPrefix).append(app).append(" "); final Collection processedGroups=new ArrayList(); Option option; List optList=new ArrayList(options.getOptions()); Collections.sort(optList,getOptionComparator()); for (Iterator i=optList.iterator(); i.hasNext(); ) { option=(Option)i.next(); OptionGroup group=options.getOptionGroup(option); if (group != null) { if (!processedGroups.contains(group)) { processedGroups.add(group); appendOptionGroup(buff,group); } } else { appendOption(buff,option,option.isRequired()); } if (i.hasNext()) { buff.append(" "); } } printWrapped(pw,width,buff.toString().indexOf(' ') + 1,buff.toString()); }
<p>Prints the usage statement for the specified application.</p>
public double squaredDistance(IntVector v){ double deltaX=v.x - x, deltaY=v.y - y, deltaZ=v.z - z; return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ; }
Calculates the squared distance between the point corresponding to this vector and the point corresponding to the vector v. This is faster than manually multiplying the distance by itself.
private void updateProgress(int progress){ if (myHost != null) { myHost.updateProgress(progress); } else { System.out.println("Progress: " + progress + "%"); } }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static Headers of(String... namesAndValues){ if (namesAndValues == null || namesAndValues.length % 2 != 0) { throw new IllegalArgumentException("Expected alternating header names and values"); } namesAndValues=namesAndValues.clone(); for (int i=0; i < namesAndValues.length; i++) { if (namesAndValues[i] == null) throw new IllegalArgumentException("Headers cannot be null"); namesAndValues[i]=namesAndValues[i].trim(); } for (int i=0; i < namesAndValues.length; i+=2) { String name=namesAndValues[i]; String value=namesAndValues[i + 1]; if (name.length() == 0 || name.indexOf('\0') != -1 || value.indexOf('\0') != -1) { throw new IllegalArgumentException("Unexpected header: " + name + ": "+ value); } } return new Headers(namesAndValues); }
Returns headers for the alternating header names and values. There must be an even number of arguments, and they must alternate between header names and values.
public boolean isLocal(){ return VPlexApiConstants.LOCAL_VIRTUAL_VOLUME.equals(getLocality()); }
Returns true if the virtual volume is a local volume.
public void testColumnMetaData() throws Exception { String sql="CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, bi bigint, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), "+ " txt text, ntxt ntext, b binary(8) not null, vb varbinary(8), img image, "+ " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " ui uniqueidentifier, sv sql_variant)"; String sql7="CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), "+ " txt text, ntxt ntext, b binary(8) not null, vb varbinary(8), img image, "+ " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " ui uniqueidentifier)"; String sql65="CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), "+ " txt text, b binary(8) not null, vb varbinary(8), img image, "+ " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname)"; String sql125="CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), "+ " txt text, b binary(8) not null, vb varbinary(8), img image, "+ " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " uc unichar(10), vuc univarchar(255), sydt date, syt time)"; try { dropTable("jTDSTYPETEST"); Statement stmt=con.createStatement(); DatabaseMetaData dbmd=con.getMetaData(); if (dbmd.getDatabaseProductName().startsWith("Microsoft")) { if (dbmd.getDatabaseProductVersion().startsWith("6.5")) stmt.execute(sql65); else if (dbmd.getDatabaseProductVersion().startsWith("7")) stmt.execute(sql7); else stmt.execute(sql); } else { if (dbmd.getDatabaseProductVersion().startsWith("12")) stmt.execute(sql125); else stmt.execute(sql65); } ResultSetMetaData rsmd=stmt.executeQuery("SELECT * FROM jTDSTYPETEST").getMetaData(); ResultSet rs=dbmd.getColumns(null,null,"jTDSTYPETEST","%"); while (rs.next()) { String cn=rs.getString("COLUMN_NAME"); int ord=rs.getInt("ORDINAL_POSITION"); Assert.assertEquals(cn + " typename",rs.getString("TYPE_NAME"),rsmd.getColumnTypeName(ord)); Assert.assertEquals(cn + " datatype",rs.getInt("DATA_TYPE"),rsmd.getColumnType(ord)); if (rs.getInt("DATA_TYPE") != Types.REAL && rs.getInt("DATA_TYPE") != Types.DOUBLE) { Assert.assertEquals(cn + " precision",rs.getInt("COLUMN_SIZE"),rsmd.getPrecision(ord)); } Assert.assertEquals(cn + " scale",rs.getInt("DECIMAL_DIGITS"),rsmd.getScale(ord)); Assert.assertEquals(cn + " nullable",rs.getInt("NULLABLE"),rsmd.isNullable(ord)); } } finally { dropTable("jTDSTYPETEST"); } }
Test to check DatabaseMetaData.getColumns and ResultSetMetaData is equivalent. This test also checks for bug [ 1074096 ] Incorrect data type determine on dataset meta data. This is because getColumns will return a typename of timestamp which should now also be returned by the result set meta data as well.
private void checkDepartureForStaging(int percent) throws BuildFailedException { if (percent != 100 || _departStageTrack == null) { return; } int carCount=0; StringBuffer buf=new StringBuffer(); for ( Car car : _carList) { if (car.getTrack() == _departStageTrack && (car.getDestination() == null || car.getDestinationTrack() == null || car.getTrain() == null)) { if (car.getKernel() != null) { for ( Car c : car.getKernel().getCars()) { carCount++; addCarToBuf(c,buf,carCount); } } else { carCount++; addCarToBuf(car,buf,carCount); } } } if (carCount > 0) { log.debug("{} cars stuck in staging",carCount); String msg=MessageFormat.format(Bundle.getMessage("buildStagingCouldNotFindDest"),new Object[]{carCount,_departStageTrack.getLocation().getName(),_departStageTrack.getName()}); throw new BuildFailedException(msg + buf.toString(),BuildFailedException.STAGING); } }
Checks to see if all cars on a staging track have been given a destination. Throws exception if there's a car without a destination.
public void faceEntity(Entity entity,float p_70625_2_,float p_70625_3_){ double d0=entity.posX - this.posX; double d2=entity.posZ - this.posZ; double d1; if (entity instanceof EntityLivingBase) { EntityLivingBase entitylivingbase=(EntityLivingBase)entity; d1=entitylivingbase.posY + (double)entitylivingbase.getEyeHeight() - (this.posY + (double)this.getEyeHeight()); } else { d1=(entity.boundingBox.minY + entity.boundingBox.maxY) / 2.0D - (this.posY + (double)this.getEyeHeight()); } double d3=(double)MathHelper.sqrt_double(d0 * d0 + d2 * d2); float f2=(float)(Math.atan2(d2,d0) * 180.0D / Math.PI) - 90.0F; float f3=(float)(-(Math.atan2(d1,d3) * 180.0D / Math.PI)); this.rotationPitch=this.updateRotation(this.rotationPitch,f3,p_70625_3_); this.rotationYaw=this.updateRotation(this.rotationYaw,f2,p_70625_2_); }
Changes pitch and yaw so that the entity calling the function is facing the entity provided as an argument.
public static String extractDuplexGroupName(LocoNetMessage m){ switch (getDuplexGroupIdentityMessageType(m)) { case DUPLEX_GROUP_NAME_ETC_REPORT_MESSAGE: case DUPLEX_GROUP_NAME_WRITE_MESSAGE: return extractGroupName(m); default : return null; } }
Checks that m is a message with a Duplex Group Name encoded inside, then extracts the Duplex Group Name. Note that the returned string is always 8 characters long. If m does not contain a Duplex Group Name, returns null.
public static void createEntriesK1andK2(){ try { Region r1=cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(r1); if (!r1.containsKey("key1")) { r1.create("key1","key-1"); } if (!r1.containsKey("key2")) { r1.create("key2","key-2"); } assertEquals(r1.getEntry("key1").getValue(),"key-1"); assertEquals(r1.getEntry("key2").getValue(),"key-2"); } catch ( Exception ex) { Assert.fail("failed while createEntriesK1andK2()",ex); } }
Creates entries on the server
public static void write(String filepath,Properties theProperties,String propComments) throws IOException { BufferedOutputStream bos=null; try { File file=new File(filepath); bos=new BufferedOutputStream(new FileOutputStream(file)); theProperties.store(bos,propComments); } finally { if (bos != null) { bos.close(); bos=null; } } }
Method write.
public void fireNeuronTypeChanged(final NeuronUpdateRule old,final NeuronUpdateRule changed){ for ( NeuronListener listener : neuronListeners) { listener.neuronTypeChanged(new NetworkEvent<NeuronUpdateRule>(this,old,changed)); } }
Fire a neuron type changed event to all registered model listeners.
protected static void validateConfigurationHierarchy(final Configuration c){ Map<String,Integer> hierarchyMap=new HashMap<>(); Set<String> multipleHierarchies=new HashSet<>(); for ( Configuration subConfig : c.getSubConfigurations()) { String hierarchy=subConfig.getHierarchy(); if (!hierarchyMap.containsKey(hierarchy)) { hierarchyMap.put(hierarchy,1); } else { int count=hierarchyMap.get(hierarchy); hierarchyMap.put(hierarchy,++count); multipleHierarchies.add(hierarchy); } } if (multipleHierarchies.size() > 0) { StringBuilder msg=new StringBuilder(); msg.append("Configuration for ").append(c.getHierarchy()).append(" contains multiple SubConfigurations with the same hierarchy id. "); for ( String hierarchy : multipleHierarchies) { msg.append(hierarchy).append(" ").append(hierarchyMap.get(hierarchy).toString()).append(" times "); } throw new IllegalArgumentException(msg.toString().trim()); } for ( Configuration subConfig : c.getSubConfigurations()) { validateConfigurationHierarchy(subConfig); } }
Validates the content of the provided configuration by checking for multiple hierarchy entries within one configuration. It traverses down the configuration tree.
public Matrix3f scaling(float x,float y,float z){ m00=x; m01=0.0f; m02=0.0f; m10=0.0f; m11=y; m12=0.0f; m20=0.0f; m21=0.0f; m22=z; return this; }
Set this matrix to be a simple scale matrix.
public void java_lang_System_initProperties(SootMethod method,ReferenceVariable thisVar,ReferenceVariable returnVar,ReferenceVariable params[]){ ReferenceVariable sysProps=helper.staticField("java.lang.System","props"); helper.assign(returnVar,sysProps); helper.assign(sysProps,params[0]); }
NOTE: this method is not documented, it should do following:
public InvoiceHistory(Dialog frame,int C_BPartner_ID,int M_Product_ID,int M_Warehouse_ID,int M_AttributeSetInstance_ID){ super(frame,Msg.getMsg(Env.getCtx(),"PriceHistory"),true); log.config("C_BPartner_ID=" + C_BPartner_ID + ", M_Product_ID="+ M_Product_ID+ ", M_Warehouse_ID="+ M_Warehouse_ID+ ", M_AttributeSetInstance_ID="+ M_AttributeSetInstance_ID); m_C_BPartner_ID=C_BPartner_ID; m_M_Product_ID=M_Product_ID; m_M_Warehouse_ID=M_Warehouse_ID; m_M_AttributeSetInstance_ID=M_AttributeSetInstance_ID; try { jbInit(); dynInit(); } catch ( Exception ex) { log.log(Level.SEVERE,"",ex); } mainPanel.setPreferredSize(new Dimension(700,400)); AEnv.positionCenterWindow(frame,this); }
Show History
public void update(){ super.fireContentsChanged(this,0,data.size() - 1); }
Mark all entries as changed, so they get repainted.
public boolean isExpanded(TreePath path){ if (path != null) { FHTreeStateNode lastNode=getNodeForPath(path,true,false); return (lastNode != null && lastNode.isExpanded()); } return false; }
Returns true if the value identified by row is currently expanded.
private void removeNode(final NaviNode node){ if (node.getRawNode() instanceof INaviGroupNode) { ((INaviGroupNode)node.getRawNode()).removeGroupListener(m_groupNodeListener); } m_selectedNodes.remove(node); m_graphInternals.removeNode(node); m_graph.updateViews(); }
Removes a node from the graph and cleans up all associated resources.
public void forceSnapGravity(int sSnapGravity){ refreshScreenSize(); if (sSnapGravity == 0) { MovableWindow.unsnap(); return; } mSnapWindowHolder.updateSnap(sSnapGravity); calculateSnap(); finishSnap(true); }
Forces the window to snap to this side programatically without user input
public void startSwitch(String filename,int uploadId){ synchronized (switchLock) { if (!switching && !new File(filename).equals(currentFile)) { switchFilename=filename; switchUploadId=uploadId; switchData=0; switching=true; doSwitch(); } } }
Checks the currently buffered write data to see if we can safely split it anywhere. <p/> If the data can be split, the data up to the split will be written out leaving the data that should be written to the new file still in the buffer. <p/> Calling this method also makes the remuxer aware that we are trying to switch and will check the bytes on each write for an opportunity. Once a switching point is detected, all new data will be buffered until switchOutput is called.
public int parseOptions(String[] args,int i){ for (int size=args.length; i < size; i++) { if (args[i].equals("-suppressDeclaration")) { setSuppressDeclaration(true); } else if (args[i].equals("-omitEncoding")) { setOmitEncoding(true); } else if (args[i].equals("-indent")) { setIndent(args[++i]); } else if (args[i].equals("-indentSize")) { setIndentSize(Integer.parseInt(args[++i])); } else if (args[i].startsWith("-expandEmpty")) { setExpandEmptyElements(true); } else if (args[i].equals("-encoding")) { setEncoding(args[++i]); } else if (args[i].equals("-newlines")) { setNewlines(true); } else if (args[i].equals("-lineSeparator")) { setLineSeparator(args[++i]); } else if (args[i].equals("-trimText")) { setTrimText(true); } else if (args[i].equals("-padText")) { setPadText(true); } else if (args[i].startsWith("-xhtml")) { setXHTML(true); } else { return i; } } return i; }
Parses command line arguments of the form <code>-omitEncoding -indentSize 3 -newlines -trimText</code>
public synchronized void disableExclusiveProcessing(String controllerId,String instanceId,PropertyHandler paramHandler) throws APPlatformException { logger.debug("disableExclusiveProcessing('{}')",instanceId); platformService.unlockServiceInstance(controllerId,instanceId,paramHandler.getTPAuthentication()); }
Disables exclusive processing.
@Override public boolean equals(final Object o){ if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t=(Type)o; if (sort != t.sort) { return false; } if (sort >= ARRAY) { if (len != t.len) { return false; } for (int i=off, j=t.off, end=i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; }
Tests if the given object is equal to this type.
public static BigdataSailRepository open(final String journalFile){ return open(getProperties(journalFile)); }
Open and initialize a BigdataSailRepository using the supplied journal file location. If the file does not exist or is empty, the repository will be created using the default property configuration below.
private void addSelfIntersectionNode(int argIndex,Coordinate coord,int loc){ if (isBoundaryNode(argIndex,coord)) return; if (loc == Location.BOUNDARY && useBoundaryDeterminationRule) insertBoundaryPoint(argIndex,coord); else insertPoint(argIndex,coord,loc); }
Add a node for a self-intersection. If the node is a potential boundary node (e.g. came from an edge which is a boundary) then insert it as a potential boundary node. Otherwise, just add it as a regular node.
public CompiledScript compileInternal(Script script,HasContextAndHeaders context){ if (script == null) { throw new IllegalArgumentException("The parameter script (Script) must not be null."); } String lang=script.getLang() == null ? defaultLang : script.getLang(); ScriptType type=script.getType(); String name=script.getScript(); if (logger.isTraceEnabled()) { logger.trace("Compiling lang: [{}] type: [{}] script: {}",lang,type,name); } ScriptEngineService scriptEngineService=getScriptEngineServiceForLang(lang); if (type == ScriptType.FILE) { String cacheKey=getCacheKey(scriptEngineService,name,null); CompiledScript compiledScript=staticCache.get(cacheKey); if (compiledScript == null) { throw new IllegalArgumentException("Unable to find on disk file script [" + name + "] using lang ["+ lang+ "]"); } return compiledScript; } String code=script.getScript(); if (type == ScriptType.INDEXED) { final IndexedScript indexedScript=new IndexedScript(lang,name); name=indexedScript.id; code=getScriptFromIndex(indexedScript.lang,indexedScript.id,context); } String cacheKey=getCacheKey(scriptEngineService,type == ScriptType.INLINE ? null : name,code); CompiledScript compiledScript=cache.getIfPresent(cacheKey); if (compiledScript == null) { try { compiledScript=new CompiledScript(type,name,lang,scriptEngineService.compile(code)); } catch ( Exception exception) { throw new ScriptException("Failed to compile " + type + " script ["+ name+ "] using lang ["+ lang+ "]",exception); } scriptMetrics.onCompilation(); cache.put(cacheKey,compiledScript); } return compiledScript; }
Compiles a script straight-away, or returns the previously compiled and cached script, without checking if it can be executed based on settings.
public FullSyncRequestMessage(FullSyncRequestMessage other){ if (other.isSetHeader()) { this.header=new AsyncMessageHeader(other.header); } }
Performs a deep copy on <i>other</i>.
public boolean intersects(Rectangle2D r){ Rectangle2D b=getBounds(); if (b != null) { return (b.intersects(r) && paintedArea != null && paintedArea.intersects(r)); } return false; }
Returns true if the interior of this node intersects the interior of a specified Rectangle2D, false otherwise.
@Override public float estimateCost(Rule rule){ float lmEstimate=0.0f; boolean considerIncompleteNgrams=true; int[] enWords=getRuleIds(rule); List<Integer> words=new ArrayList<>(); boolean skipStart=(enWords[0] == startSymbolId); for ( int currentWord : enWords) { if (FormatUtils.isNonterminal(currentWord)) { lmEstimate+=scoreChunkLogP(words,considerIncompleteNgrams,skipStart); words.clear(); skipStart=false; } else { words.add(currentWord); } } lmEstimate+=scoreChunkLogP(words,considerIncompleteNgrams,skipStart); final float oovEstimate=(withOovFeature) ? getOovs(enWords) : 0f; return weight * lmEstimate + oovWeight * oovEstimate; }
This function computes all the complete n-grams found in the rule, as well as the incomplete n-grams on the left-hand side.
public JimpleLocal(String name,Type t){ this.name=name; this.type=t; Scene.v().getLocalNumberer().add(this); }
Constructs a JimpleLocal of the given name and type.
public static boolean testAabSphere(Vector3fc min,Vector3fc max,Vector3fc center,float radiusSquared){ return testAabSphere(min.x(),min.y(),min.z(),max.x(),max.y(),max.z(),center.x(),center.y(),center.z(),radiusSquared); }
Test whether the axis-aligned box with minimum corner <code>min</code> and maximum corner <code>max</code> intersects the sphere with the given <code>center</code> and square radius <code>radiusSquared</code>. <p> Reference: <a href="http://stackoverflow.com/questions/4578967/cube-sphere-intersection-test#answer-4579069">http://stackoverflow.com</a>
@LargeTest public void testNavigationByHeading() throws Exception { sExecutedTestCount++; String html="<!DOCTYPE html>" + "<html>" + "<head>"+ "</head>"+ "<body>"+ "<h1>Heading one</h1>"+ "<p>"+ "This is some text"+ "</p>"+ "<h2>Heading two</h2>"+ "<p>"+ "This is some text"+ "</p>"+ "<h3>Heading three</h3>"+ "<p>"+ "This is some text"+ "</p>"+ "<h4>Heading four</h4>"+ "<p>"+ "This is some text"+ "</p>"+ "<h5>Heading five</h5>"+ "<p>"+ "This is some text"+ "</p>"+ "<h6>Heading six</h6>"+ "</body>"+ "</html>"; WebView webView=loadHTML(html); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_RIGHT,META_STATE_ALT_LEFT_ON); assertSelectionString("3"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h1>Heading one</h1>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h2>Heading two</h2>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h3>Heading three</h3>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h4>Heading four</h4>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h5>Heading five</h5>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h6>Heading six</h6>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString(null); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString("<h5>Heading five</h5>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString("<h4>Heading four</h4>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString("<h3>Heading three</h3>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString("<h2>Heading two</h2>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString("<h1>Heading one</h1>"); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_UP,0); assertSelectionString(null); sendKeyEvent(webView,KeyEvent.KEYCODE_DPAD_DOWN,0); assertSelectionString("<h2>Heading two</h2>"); }
Tests navigation by heading.
public IndexInvalidException(String msg,Throwable cause){ super(msg); initCause(cause); }
Construct an instance of IndexInvalidException
Optional<String> hostname(){ return Optional.ofNullable(hostname); }
Returns the hostname of an embedded Tomcat.
public void add(NamedRangeSet other){ List<NamedRange> newRanges=new ArrayList<NamedRange>(); int thisPos=0; int otherPos=0; while (thisPos < ranges.size() || otherPos < other.ranges.size()) { NamedRange toAdd; if (thisPos < ranges.size() && (otherPos >= other.ranges.size() || ranges.get(thisPos).start <= other.ranges.get(otherPos).start)) { toAdd=ranges.get(thisPos++); } else { toAdd=other.ranges.get(otherPos++); } if (newRanges.isEmpty() || toAdd.start > newRanges.get(newRanges.size() - 1).end + 1) { newRanges.add(new NamedRange(toAdd.start,toAdd.end,toAdd.name)); } else { newRanges.get(newRanges.size() - 1).end=toAdd.end; } } this.ranges=newRanges; }
Assumptions: ranges are disjoint, non-contiguous, and ordered. Names of ranges are not necessarily preserved.
public static double deviation(double[] x){ double deviation=0; double mean=mean(x); for ( double e : x) { deviation+=Math.pow(e - mean,2); } return Math.sqrt(deviation / (x.length - 1)); }
Compute the deviation of double values
public int read(byte b[],int off,int len) throws IOException { if (len == 0) return 0; if (in == null) in=owner.readNotify(); return in.read(b,off,len); }
Read into an array of bytes.
public static void extract(AzExecMessage message) throws Exception { List<LineageRecord> result=extractLineage(message); for ( LineageRecord lr : result) { message.databaseWriter.append(lr); } logger.debug("Find " + result.size() + " Lineage record in execution "+ message.toString()); message.databaseWriter.flush(); }
Extract and write to database
public CalibratedGyroscopeProvider(SensorManager sensorManager){ super(sensorManager); sensorList.add(sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)); }
Initialises a new CalibratedGyroscopeProvider
public static JPopupMenu leftShift(JPopupMenu self,String str){ self.add(str); return self; }
Overloads the left shift operator to provide an easy way to add components to a popupMenu.<p>
public String toString(){ final String TAB=" "; StringBuffer retValue=new StringBuffer(); retValue.append("HeaderCriterion ( ").append("headerName = ").append(this.headerName).append(TAB).append("operator = ").append(this.operator).append(TAB).append(" )"); return retValue.toString(); }
Constructs a <code>String</code> with all attributes in name = value format.
public boolean baseIsLeftToRight(){ return bidiBase.baseIsLeftToRight(); }
Return true if the base direction is left-to-right.
private Instances cleanseCross(Instances data) throws Exception { Instance inst; Instances crossSet=new Instances(data); Instances temp=new Instances(data,data.numInstances()); Instances inverseSet=new Instances(data,data.numInstances()); int count=0; double ans; int iterations=0; int classIndex=m_classIndex; if (classIndex < 0) { classIndex=data.classIndex(); } if (classIndex < 0) { classIndex=data.numAttributes() - 1; } while (count != crossSet.numInstances() && crossSet.numInstances() >= m_numOfCrossValidationFolds) { count=crossSet.numInstances(); iterations++; if (m_numOfCleansingIterations > 0 && iterations > m_numOfCleansingIterations) { break; } crossSet.setClassIndex(classIndex); if (crossSet.classAttribute().isNominal()) { crossSet.stratify(m_numOfCrossValidationFolds); } temp=new Instances(crossSet,crossSet.numInstances()); for (int fold=0; fold < m_numOfCrossValidationFolds; fold++) { Instances train=crossSet.trainCV(m_numOfCrossValidationFolds,fold); m_cleansingClassifier.buildClassifier(train); Instances test=crossSet.testCV(m_numOfCrossValidationFolds,fold); for (int i=0; i < test.numInstances(); i++) { inst=test.instance(i); ans=m_cleansingClassifier.classifyInstance(inst); if (crossSet.classAttribute().isNumeric()) { if (ans >= inst.classValue() - m_numericClassifyThreshold && ans <= inst.classValue() + m_numericClassifyThreshold) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } else { if (ans == inst.classValue()) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } } } crossSet=temp; } if (m_invertMatching) { inverseSet.setClassIndex(data.classIndex()); return inverseSet; } else { crossSet.setClassIndex(data.classIndex()); return crossSet; } }
Cleanses the data based on misclassifications when performing cross-validation.
protected Node deepCopyInto(Node n){ super.deepCopyInto(n); AbstractElementNS ae=(AbstractElementNS)n; ae.namespaceURI=namespaceURI; return n; }
Deeply copy the fields of the current node into the given node.
public static org.oscm.vo.VOEventDefinition convertToApi(org.oscm.internal.vo.VOEventDefinition oldVO){ if (oldVO == null) { return null; } org.oscm.vo.VOEventDefinition newVO=new org.oscm.vo.VOEventDefinition(); newVO.setKey(oldVO.getKey()); newVO.setVersion(oldVO.getVersion()); newVO.setEventType(EnumConverter.convert(oldVO.getEventType(),org.oscm.types.enumtypes.EventType.class)); newVO.setEventId(oldVO.getEventId()); newVO.setEventDescription(oldVO.getEventDescription()); return newVO; }
Convert source version VO to target version VO.
@Override public boolean contains(Point2D.Double p){ return getBounds().contains(p); }
Tests if a point is contained in the connector.
@Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); drawDarkenSurroundingArea(canvas); drawCircleBorder(canvas); if (mHandleMode == HANDLE_DOWN || mHandleMode == HANDLE_MOVE) { if (mDragDirection == SIDE) { drawHandles(canvas); } if (mHasGuideLine && (mDragDirection == SIDE || mDragDirection == CENTER)) { drawGuideLine(canvas); } } }
drawing the view.
public QueryFirstRequest clone(){ QueryFirstRequest result=new QueryFirstRequest(); result.RequestHeader=RequestHeader == null ? null : RequestHeader.clone(); result.View=View == null ? null : View.clone(); if (NodeTypes != null) { result.NodeTypes=new NodeTypeDescription[NodeTypes.length]; for (int i=0; i < NodeTypes.length; i++) result.NodeTypes[i]=NodeTypes[i].clone(); } result.Filter=Filter == null ? null : Filter.clone(); result.MaxDataSetsToReturn=MaxDataSetsToReturn; result.MaxReferencesToReturn=MaxReferencesToReturn; return result; }
Deep clone
private EditReviewHolder editReview(boolean scroll){ ListView list=getListView(); View view=a.getLayoutInflater().inflate(R.layout.reviews_edit,list,false); EditReviewHolder r=ViewHolder.get(view,EditReviewHolder.class); r.mTitle.setText(mReviewId == 0 ? R.string.add_review_title : R.string.edit_review_title); r.mRatings.setAdapter(ArrayAdapter.createFromResource(a,R.array.ratings,R.layout.rating)); r.mRatings.setSelection(mRatingPos >= 0 ? mRatingPos : DEFAULT_RATING_POS); r.mComments.setText(mComments); list.addHeaderView(view); ((BaseAdapter)getListAdapter()).notifyDataSetChanged(); if (scroll) { list.smoothScrollToPositionFromTop(1,Themes.getActionBarSize(a) * 2 + mDividerHeight); r.mComments.requestFocus(); if (a instanceof RestaurantActivity && ((RestaurantActivity)a).getCurrentTabFragment() == this) { InputMethods.show(r.mComments); } } mEditing=true; a.invalidateOptionsMenu(); return r; }
Add a header View for adding or editing a review and, optionally, scroll to it.
public GroovyClassLoader(GroovyClassLoader parent){ this(parent,parent.config,false); }
creates a GroovyClassLoader using the given GroovyClassLoader as parent. This loader will get the parent's CompilerConfiguration
public RecognizeOptions build(){ return new RecognizeOptions(this); }
Builds the profile options.
public void testBug41448() throws Exception { createTable("testBug41448","(pk INT PRIMARY KEY AUTO_INCREMENT, field1 VARCHAR(4))"); this.stmt.executeUpdate("INSERT INTO testBug41448 (field1) VALUES ('abc')",Statement.RETURN_GENERATED_KEYS); this.stmt.getGeneratedKeys(); this.stmt.executeUpdate("INSERT INTO testBug41448 (field1) VALUES ('def')",new int[]{1}); this.stmt.getGeneratedKeys(); this.stmt.executeUpdate("INSERT INTO testBug41448 (field1) VALUES ('ghi')",new String[]{"pk"}); this.stmt.getGeneratedKeys(); this.stmt.executeUpdate("INSERT INTO testBug41448 (field1) VALUES ('ghi')"); try { this.stmt.getGeneratedKeys(); fail("Expected a SQLException here"); } catch ( SQLException sqlEx) { } this.stmt.execute("INSERT INTO testBug41448 (field1) VALUES ('jkl')",Statement.RETURN_GENERATED_KEYS); this.stmt.getGeneratedKeys(); this.stmt.execute("INSERT INTO testBug41448 (field1) VALUES ('mno')",new int[]{1}); this.stmt.getGeneratedKeys(); this.stmt.execute("INSERT INTO testBug41448 (field1) VALUES ('pqr')",new String[]{"pk"}); this.stmt.getGeneratedKeys(); this.stmt.execute("INSERT INTO testBug41448 (field1) VALUES ('stu')"); try { this.stmt.getGeneratedKeys(); fail("Expected a SQLException here"); } catch ( SQLException sqlEx) { } this.pstmt=this.conn.prepareStatement("INSERT INTO testBug41448 (field1) VALUES (?)",Statement.RETURN_GENERATED_KEYS); this.pstmt.setString(1,"abc"); this.pstmt.executeUpdate(); this.pstmt.getGeneratedKeys(); this.pstmt.execute(); this.pstmt.getGeneratedKeys(); this.pstmt=this.conn.prepareStatement("INSERT INTO testBug41448 (field1) VALUES (?)",new int[]{1}); this.pstmt.setString(1,"abc"); this.pstmt.executeUpdate(); this.pstmt.getGeneratedKeys(); this.pstmt.execute(); this.pstmt.getGeneratedKeys(); this.pstmt=this.conn.prepareStatement("INSERT INTO testBug41448 (field1) VALUES (?)",new String[]{"pk"}); this.pstmt.setString(1,"abc"); this.pstmt.executeUpdate(); this.pstmt.getGeneratedKeys(); this.pstmt.execute(); this.pstmt.getGeneratedKeys(); this.pstmt=this.conn.prepareStatement("INSERT INTO testBug41448 (field1) VALUES (?)"); this.pstmt.setString(1,"abc"); this.pstmt.executeUpdate(); try { this.pstmt.getGeneratedKeys(); fail("Expected a SQLException here"); } catch ( SQLException sqlEx) { } this.pstmt.execute(); try { this.pstmt.getGeneratedKeys(); fail("Expected a SQLException here"); } catch ( SQLException sqlEx) { } }
Ensures that cases listed in Bug#41448 actually work - we don't think there's a bug here right now
@Override public boolean equals(Object object){ if (!(object instanceof HttpMessage)) { return false; } HttpMessage msg=(HttpMessage)object; boolean result=false; if (!this.getRequestHeader().getMethod().equalsIgnoreCase(msg.getRequestHeader().getMethod())) { return false; } URI uri1=this.getRequestHeader().getURI(); URI uri2=msg.getRequestHeader().getURI(); if (uri1 == null) { if (uri2 != null) { return false; } return true; } else if (uri2 == null) { return false; } try { if (uri1.getHost() == null || uri2.getHost() == null || !uri1.getHost().equalsIgnoreCase(uri2.getHost())) { return false; } if (uri1.getPort() != uri2.getPort()) { return false; } String pathQuery1=uri1.getPathQuery(); String pathQuery2=uri2.getPathQuery(); if (pathQuery1 == null && pathQuery2 == null) { return true; } else if (pathQuery1 != null && pathQuery2 != null) { return pathQuery1.equalsIgnoreCase(pathQuery2); } else if (pathQuery1 == null || pathQuery2 == null) { return false; } if (this.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST)) { return this.getRequestBody().equals(msg.getRequestBody()); } result=true; } catch ( URIException e) { try { result=this.getRequestHeader().getURI().toString().equalsIgnoreCase(msg.getRequestHeader().getURI().toString()); } catch ( Exception e1) { log.error(e.getMessage(),e); } } return result; }
Compare if 2 message is the same. 2 messages are the same if: Host, port, path and query param and VALUEs are the same. For POST request, the body must be the same.
public boolean isIdle(){ return deltaQueue.isEmpty() || deltaQueue.delay() > 0; }
Gets whether the queue is idle.
public static java.lang.String toString(int i){ return null; }
Returns a new String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the method.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case RegularExpressionPackage.REGULAR_EXPRESSION_BODY__PATTERN: return basicSetPattern(null,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void tryClaimAnt(){ try { antInterface.requestForceClaimInterface(context.getString(R.string.my_tracks_app_name)); } catch ( AntInterfaceException e) { handleAntError(); } }
Tries to claim the ant interface.
private static void checkDebug(){ try { if (Boolean.getBoolean("gfAgentDebug")) { mx4j.log.Log.setDefaultPriority(mx4j.log.Logger.TRACE); } } catch ( VirtualMachineError err) { SystemFailure.initiateFailure(err); throw err; } catch ( Throwable t) { SystemFailure.checkFailure(); } }
Enables mx4j tracing if Agent debugging is enabled.
public SequencesReader single(){ assert !mIsPaired; return mSingle; }
The single reader.
public ConnectionConfig(){ super(); }
Ctor for a functional Swing object with no prexisting adapter
@Override protected boolean playVideoItem(){ if (super.playVideoItem()) { updateVideoControls(); return true; } return false; }
Overridden to allow updating the Title, SubTitle, and description in the EMVideoView (VideoControls)
public final Mono<T> otherwiseReturn(final T fallback){ return otherwise(null); }
Subscribe to a returned fallback value when any error occurs. <p> <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwisereturn.png" alt=""> <p>
static Register findOrCreateRegister(Object heapType,int v1,int v2,HashMap<UseRecord,Register> registers,GenericRegisterPool pool,TypeReference type){ UseRecord key=new UseRecord(heapType,v1,v2); Register result=registers.get(key); if (result == null) { result=pool.makeTemp(type).getRegister(); registers.put(key,result); } return result; }
Given a pair of value numbers, return the temporary register allocated for that pair. Create one if necessary.
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException { in.defaultReadObject(); setBeforeCaretText(this.beforeCaret); setAfterCaretText(this.afterCaret); }
Called when reading a serialized version of this document. This is overridden to initialize the transient members of this class.
@Override public boolean load(URL url,boolean registerDeferred) throws JmriConfigureXmlException { if (javax.swing.SwingUtilities.isEventDispatchThread()) { return loadOnSwingThread(url,registerDeferred); } else { final java.util.concurrent.atomic.AtomicReference<Boolean> result=new java.util.concurrent.atomic.AtomicReference<>(); try { javax.swing.SwingUtilities.invokeAndWait(null); } catch ( InterruptedException e) { throw new JmriConfigureXmlException(e); } catch ( java.lang.reflect.InvocationTargetException e) { throw new JmriConfigureXmlException(e); } return result.get(); } }
Load a file. <p> Handles problems locally to the extent that it can, by routing them to the creationErrorEncountered method. <p> Always processes on Swing thread
public static BigDecimal calculateAveragePO(MProduct product,int M_AttributeSetInstance_ID,MAcctSchema as,int AD_Org_ID){ String sql="SELECT t.MovementQty, mp.Qty, ol.QtyOrdered, ol.PriceCost, ol.PriceActual," + " o.C_Currency_ID, o.DateAcct, o.C_ConversionType_ID," + " o.AD_Client_ID, o.AD_Org_ID, t.M_Transaction_ID "+ "FROM M_Transaction t"+ " INNER JOIN M_MatchPO mp ON (t.M_InOutLine_ID=mp.M_InOutLine_ID)"+ " INNER JOIN C_OrderLine ol ON (mp.C_OrderLine_ID=ol.C_OrderLine_ID)"+ " INNER JOIN C_Order o ON (ol.C_Order_ID=o.C_Order_ID) "+ "WHERE t.M_Product_ID=?"; if (AD_Org_ID != 0) sql+=" AND t.AD_Org_ID=?"; else if (M_AttributeSetInstance_ID != 0) sql+=" AND t.M_AttributeSetInstance_ID=?"; sql+=" ORDER BY t.M_Transaction_ID"; PreparedStatement pstmt=null; ResultSet rs=null; BigDecimal newStockQty=Env.ZERO; BigDecimal newAverageAmt=Env.ZERO; int oldTransaction_ID=0; try { pstmt=DB.prepareStatement(sql,null); pstmt.setInt(1,product.getM_Product_ID()); if (AD_Org_ID != 0) pstmt.setInt(2,AD_Org_ID); else if (M_AttributeSetInstance_ID != 0) pstmt.setInt(2,M_AttributeSetInstance_ID); rs=pstmt.executeQuery(); while (rs.next()) { BigDecimal oldStockQty=newStockQty; BigDecimal movementQty=rs.getBigDecimal(1); int M_Transaction_ID=rs.getInt(11); if (M_Transaction_ID != oldTransaction_ID) newStockQty=oldStockQty.add(movementQty); M_Transaction_ID=oldTransaction_ID; BigDecimal matchQty=rs.getBigDecimal(2); if (matchQty == null) { s_log.finer("Movement=" + movementQty + ", StockQty="+ newStockQty); continue; } BigDecimal price=rs.getBigDecimal(4); if (price == null || price.signum() == 0) price=rs.getBigDecimal(5); int C_Currency_ID=rs.getInt(6); Timestamp DateAcct=rs.getTimestamp(7); int C_ConversionType_ID=rs.getInt(8); int Client_ID=rs.getInt(9); int Org_ID=rs.getInt(10); BigDecimal cost=MConversionRate.convert(product.getCtx(),price,C_Currency_ID,as.getC_Currency_ID(),DateAcct,C_ConversionType_ID,Client_ID,Org_ID); BigDecimal oldAverageAmt=newAverageAmt; BigDecimal averageCurrent=oldStockQty.multiply(oldAverageAmt); BigDecimal averageIncrease=matchQty.multiply(cost); BigDecimal newAmt=averageCurrent.add(averageIncrease); newAmt=newAmt.setScale(as.getCostingPrecision(),BigDecimal.ROUND_HALF_UP); newAverageAmt=newAmt.divide(newStockQty,as.getCostingPrecision(),BigDecimal.ROUND_HALF_UP); s_log.finer("Movement=" + movementQty + ", StockQty="+ newStockQty+ ", Match="+ matchQty+ ", Cost="+ cost+ ", NewAvg="+ newAverageAmt); } } catch ( SQLException e) { throw new DBException(e,sql); } finally { DB.close(rs,pstmt); rs=null; pstmt=null; } if (newAverageAmt != null && newAverageAmt.signum() != 0) { s_log.finer(product.getName() + " = " + newAverageAmt); return newAverageAmt; } return null; }
Calculate Average PO
public boolean isClosedOrPartial(){ return ((ConsCell)getTerm()).isClosedOrPartial(); }
Returns true if this cons object is a closed or a partial cons list.<br>
@Override public boolean isShowing(){ return trayIsShowing; }
Signifies if the tray is current showing
public static final double transposeTimes(final double[] v1,final double[] v2){ assert (v2.length == v1.length) : ERR_MATRIX_INNERDIM; double s=0; for (int k=0; k < v1.length; k++) { s+=v1[k] * v2[k]; } return s; }
Linear algebraic matrix multiplication, v1<sup>T</sup> * v2
public static double L_LogLoss(double y,double rpred,double C){ double ans=Math.min(Utils.eq(y,rpred) ? 0.0 : -((y * Math.log(rpred)) + ((1.0 - y) * Math.log(1.0 - rpred))),C); return (Double.isNaN(ans) ? 0.0 : ans); }
L_LogLoss - the log loss between real-valued confidence rpred and true prediction y.
public boolean addGpsTags(double latitude,double longitude){ ExifTag latTag=buildTag(TAG_GPS_LATITUDE,toExifLatLong(latitude)); ExifTag longTag=buildTag(TAG_GPS_LONGITUDE,toExifLatLong(longitude)); ExifTag latRefTag=buildTag(TAG_GPS_LATITUDE_REF,latitude >= 0 ? ExifInterface.GpsLatitudeRef.NORTH : ExifInterface.GpsLatitudeRef.SOUTH); ExifTag longRefTag=buildTag(TAG_GPS_LONGITUDE_REF,longitude >= 0 ? ExifInterface.GpsLongitudeRef.EAST : ExifInterface.GpsLongitudeRef.WEST); if (latTag == null || longTag == null || latRefTag == null || longRefTag == null) { return false; } setTag(latTag); setTag(longTag); setTag(latRefTag); setTag(longRefTag); return true; }
Creates and sets all to the GPS tags for a give latitude and longitude.
final public static String toString(final byte[] key){ if (key == null) return NULL; return toString(key,0,key.length); }
Formats a key as a series of comma delimited unsigned bytes.
@Override public void flush() throws IOException { synchronized (lock) { out.flush(); } }
Flushes this writer to ensure all pending data is sent out to the target writer. This implementation flushes the target writer.
public String globalInfo(){ return "Class for performing a Bias-Variance decomposition on any classifier " + "using the method specified in:\n\n" + getTechnicalInformation().toString(); }
Returns a string describing this object
public double slideSubtree(MutableTree tree){ double logHastingsRatio; NodeRef i, newParent, newChild; do { i=tree.getNode(MathUtils.nextInt(tree.getNodeCount())); } while (tree.getRoot() == i); NodeRef iP=tree.getParent(i); NodeRef CiP=getOtherChild(tree,iP,i); NodeRef PiP=tree.getParent(iP); double delta=getDelta(); double oldHeight=tree.getNodeHeight(iP); double newHeight=oldHeight + delta; if (delta > 0) { if (PiP != null && tree.getNodeHeight(PiP) < newHeight) { newParent=PiP; newChild=iP; while (tree.getNodeHeight(newParent) < newHeight) { newChild=newParent; newParent=tree.getParent(newParent); if (newParent == null) break; } tree.beginTreeEdit(); if (tree.isRoot(newChild)) { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.setRoot(iP); } else { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.addChild(newParent,iP); } tree.setNodeHeight(iP,newHeight); tree.endTreeEdit(); int possibleSources=intersectingEdges(tree,newChild,oldHeight,null); logHastingsRatio=Math.log(1.0 / (double)possibleSources); } else { tree.setNodeHeight(iP,newHeight); logHastingsRatio=0.0; } } else { if (tree.getNodeHeight(i) > newHeight) { return Double.NEGATIVE_INFINITY; } if (tree.getNodeHeight(CiP) > newHeight) { ArrayList newChildren=new ArrayList(); int possibleDestinations=intersectingEdges(tree,CiP,newHeight,newChildren); if (newChildren.size() == 0) { return Double.NEGATIVE_INFINITY; } int childIndex=MathUtils.nextInt(newChildren.size()); newChild=(NodeRef)newChildren.get(childIndex); newParent=tree.getParent(newChild); tree.beginTreeEdit(); if (tree.isRoot(iP)) { tree.removeChild(iP,CiP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(newParent,iP); tree.setRoot(CiP); } else { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.addChild(newParent,iP); } tree.setNodeHeight(iP,newHeight); tree.endTreeEdit(); logHastingsRatio=Math.log((double)possibleDestinations); } else { tree.setNodeHeight(iP,newHeight); logHastingsRatio=0.0; } } return logHastingsRatio; }
Do a probablistic subtree slide move.
private Vector2 rotatePoint(Vector2 point,Vector2 rotationCenter,float angle){ angle=(float)(angle * (Math.PI / 180f)); float rotatedX=(float)(Math.cos(angle) * (point.x - rotationCenter.x) - Math.sin(angle) * (point.y - rotationCenter.y) + rotationCenter.x); float rotatedY=(float)(Math.sin(angle) * (point.x - rotationCenter.x) + Math.cos(angle) * (point.y - rotationCenter.y) + rotationCenter.y); return new Vector2(rotatedX,rotatedY); }
Rotate one point "point" around the other point "rotationCenter" by an given angle.
@Deprecated private List<CharSequence> buildLimitedNetworksList(){ final Context context=getActivity(); final ArrayList<CharSequence> limited=Lists.newArrayList(); if (hasSubscription(context)) { final String subscriberId=getActiveSubscriberId(context); if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobileAll(subscriberId))) { limited.add(getText(R.string.data_usage_list_mobile)); } if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobile3gLower(subscriberId))) { limited.add(getText(R.string.data_usage_tab_3g)); } if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobile4g(subscriberId))) { limited.add(getText(R.string.data_usage_tab_4g)); } } if (mPolicyEditor.hasLimitedPolicy(buildTemplateWifiWildcard())) { limited.add(getText(R.string.data_usage_tab_wifi)); } if (mPolicyEditor.hasLimitedPolicy(buildTemplateEthernet())) { limited.add(getText(R.string.data_usage_tab_ethernet)); } return limited; }
Build list of currently limited networks, which defines when background data is restricted.
public GuacamoleClientTooManyException(String message){ super(message); }
Creates a new GuacamoleClientTooManyException with the given message.
private String augmentDataObjectName(DataObject dataObject){ if (dataObject instanceof Host) { URI clusterResource=((Host)dataObject).getCluster(); if (clusterResource != null) { Cluster cluster=client.findById(Cluster.class,clusterResource); if (cluster != null) { return String.format("%s [cluster: %s]",dataObject.getLabel(),cluster.getLabel()); } } } return dataObject.getLabel(); }
Allows manipulation of the string returned from the DataObjectResponse.getName()
private Optional<IN4JSProject> findRuntimeEnvironemtnWithName(final String projectId){ for ( IN4JSProject project : n4jsCore.findAllProjects()) { if (project.getProjectType() == ProjectType.RUNTIME_ENVIRONMENT && project.getProjectId().equals(projectId)) { return Optional.of(project); } } return Optional.absent(); }
Looks up all runtime environment with provided name.
int readEntry(int position,int offset) throws ArrayIndexOutOfBoundsException { { if (offset >= slotsize) throw new ArrayIndexOutOfBoundsException(XMLMessages.createXMLMessage(XMLErrorResources.ER_OFFSET_BIGGER_THAN_SLOT,null)); position*=slotsize; int chunkpos=position >> lowbits; int slotpos=position & lowmask; int[] chunk=chunks.elementAt(chunkpos); return chunk[slotpos + offset]; } }
Retrieve an integer from the CIA by record number and column within the record, both 0-based (though position 0 is reserved for special purposes).
public boolean insert(int val){ Integer v=val; if (list.contains(v)) { return false; } list.add(v); return true; }
Inserts a value to the set. Returns true if the set did not already contain the specified element.
public double distance(final java.awt.geom.Point2D p){ final double dx=(double)this.x - p.getX(); final double dy=(double)this.y - p.getY(); return Math.sqrt(dx * dx + dy * dy); }
Returns the distance FROM this Double2D TO the specified point.
private String createColumnMethods(StringBuffer mandatory,String columnName,boolean isUpdateable,boolean isMandatory,int displayType,int AD_Reference_ID,int fieldLength,String defaultValue,String ValueMin,String ValueMax,String VFormat,String Callout,String Name,String Description,boolean virtualColumn,boolean IsEncrypted,boolean IsKey,int AD_Table_ID){ Class<?> clazz=ModelInterfaceGenerator.getClass(columnName,displayType,AD_Reference_ID); String dataType=ModelInterfaceGenerator.getDataTypeName(clazz,displayType); if (defaultValue == null) defaultValue=""; if (DisplayType.isLOB(displayType)) fieldLength=0; String setValue="\t\tset_Value"; if (IsEncrypted) setValue="\t\tset_ValueE"; if (!isUpdateable) { setValue="\t\tset_ValueNoCheck"; if (IsEncrypted) setValue="\t\tset_ValueNoCheckE"; } StringBuffer sb=new StringBuffer(); if (DisplayType.isID(displayType) && !IsKey) { String fieldName=ModelInterfaceGenerator.getFieldName(columnName); String referenceClassName=ModelInterfaceGenerator.getReferenceClassName(AD_Table_ID,columnName,displayType,AD_Reference_ID); if (fieldName != null && referenceClassName != null) { sb.append(NL).append("\tpublic " + referenceClassName + " get").append(fieldName).append("() throws RuntimeException").append(NL).append(" {").append(NL).append("\t\treturn (" + referenceClassName + ")MTable.get(getCtx(), "+ referenceClassName+ ".Table_Name)").append(NL).append("\t\t\t.getPO(get" + columnName + "(), get_TrxName());").append("\t}").append(NL); addImportClass(clazz); } } generateJavaSetComment(columnName,Name,Description,sb); sb.append("\tpublic void set").append(columnName).append(" (").append(dataType).append(" ").append(columnName).append(")").append(NL).append("\t{").append(NL); if (AD_Reference_ID != 0 && String.class == clazz) { String staticVar=addListValidation(sb,AD_Reference_ID,columnName); sb.insert(0,staticVar); } if (virtualColumn) { sb.append("\t\tthrow new IllegalArgumentException (\"").append(columnName).append(" is virtual column\");"); } else if (clazz.equals(Integer.class)) { if (columnName.endsWith("_ID")) { int firstOK=1; if (columnName.equals("AD_Client_ID") || columnName.equals("AD_Org_ID") || columnName.equals("Record_ID")|| columnName.equals("C_DocType_ID")|| columnName.equals("Node_ID")|| columnName.equals("AD_Role_ID")|| columnName.equals("M_AttributeSet_ID")|| columnName.equals("M_AttributeSetInstance_ID")) firstOK=0; sb.append("\t\tif (").append(columnName).append(" < ").append(firstOK).append(") ").append(NL).append("\t").append(setValue).append(" (").append("COLUMNNAME_").append(columnName).append(", null);").append(NL).append("\t\telse ").append(NL).append("\t"); } sb.append(setValue).append(" (").append("COLUMNNAME_").append(columnName).append(", Integer.valueOf(").append(columnName).append("));").append(NL); } else if (clazz.equals(Boolean.class)) sb.append(setValue).append(" (").append("COLUMNNAME_").append(columnName).append(", Boolean.valueOf(").append(columnName).append("));").append(NL); else { sb.append(setValue).append(" (").append("COLUMNNAME_").append(columnName).append(", ").append(columnName).append(");").append(NL); } sb.append("\t}").append(NL); if (isMandatory) { mandatory.append("\t\t\tset").append(columnName).append(" ("); if (clazz.equals(Integer.class)) mandatory.append("0"); else if (clazz.equals(Boolean.class)) { if (defaultValue.indexOf('Y') != -1) mandatory.append(true); else mandatory.append("false"); } else if (clazz.equals(BigDecimal.class)) mandatory.append("Env.ZERO"); else if (clazz.equals(Timestamp.class)) mandatory.append("new Timestamp( System.currentTimeMillis() )"); else mandatory.append("null"); mandatory.append(");").append(NL); if (defaultValue.length() > 0) mandatory.append("// ").append(defaultValue).append(NL); } generateJavaGetComment(Name,Description,sb); String getValue="get_Value"; if (IsEncrypted) getValue="get_ValueE"; sb.append("\tpublic ").append(dataType); if (clazz.equals(Boolean.class)) { sb.append(" is"); if (columnName.toLowerCase().startsWith("is")) sb.append(columnName.substring(2)); else sb.append(columnName); } else { sb.append(" get").append(columnName); } sb.append(" () ").append(NL).append("\t{").append(NL).append("\t\t"); if (clazz.equals(Integer.class)) { sb.append("Integer ii = (Integer)").append(getValue).append("(").append("COLUMNNAME_").append(columnName).append(");").append(NL).append("\t\tif (ii == null)").append(NL).append("\t\t\t return 0;").append(NL).append("\t\treturn ii.intValue();").append(NL); } else if (clazz.equals(BigDecimal.class)) { sb.append("BigDecimal bd = (BigDecimal)").append(getValue).append("(").append("COLUMNNAME_").append(columnName).append(");").append(NL).append("\t\tif (bd == null)").append(NL).append("\t\t\t return Env.ZERO;").append(NL).append("\t\treturn bd;").append(NL); addImportClass(java.math.BigDecimal.class); addImportClass(org.compiere.util.Env.class); } else if (clazz.equals(Boolean.class)) { sb.append("Object oo = ").append(getValue).append("(").append("COLUMNNAME_").append(columnName).append(");").append(NL).append("\t\tif (oo != null) ").append(NL).append("\t\t{").append(NL).append("\t\t\t if (oo instanceof Boolean) ").append(NL).append("\t\t\t\t return ((Boolean)oo).booleanValue(); ").append(NL).append("\t\t\treturn \"Y\".equals(oo);").append(NL).append("\t\t}").append(NL).append("\t\treturn false;").append(NL); } else if (dataType.equals("Object")) { sb.append("\t\treturn ").append(getValue).append("(").append("COLUMNNAME_").append(columnName).append(");").append(NL); } else { sb.append("return (").append(dataType).append(")").append(getValue).append("(").append("COLUMNNAME_").append(columnName).append(");").append(NL); addImportClass(clazz); } sb.append("\t}").append(NL); return sb.toString(); }
Create set/get methods for column
public final static byte[] stream2Byte(InputStream is) throws IOException { ByteArrayOutputStream baos=new ByteArrayOutputStream(); int len=0; byte[] b=new byte[1024]; while ((len=is.read(b,0,b.length)) != -1) { baos.write(b,0,len); } byte[] buffer=baos.toByteArray(); return buffer; }
Read an input stream into a byte[]
public double num(XPathContext xctxt) throws javax.xml.transform.TransformerException { return (m_left.num(xctxt) % m_right.num(xctxt)); }
Evaluate this operation directly to a double.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public void indexDocument(Document doc){ indexDocuments(Arrays.asList(new Document[]{doc})); }
Indexes a document
static int[] convertMidTerms(int[] k){ int[] res=new int[3]; if (k.length == 1) { res[0]=k[0]; } else { if (k.length != 3) { throw new IllegalArgumentException("Only Trinomials and pentanomials supported"); } if (k[0] < k[1] && k[0] < k[2]) { res[0]=k[0]; if (k[1] < k[2]) { res[1]=k[1]; res[2]=k[2]; } else { res[1]=k[2]; res[2]=k[1]; } } else if (k[1] < k[2]) { res[0]=k[1]; if (k[0] < k[2]) { res[1]=k[0]; res[2]=k[2]; } else { res[1]=k[2]; res[2]=k[0]; } } else { res[0]=k[2]; if (k[0] < k[1]) { res[1]=k[0]; res[2]=k[1]; } else { res[1]=k[1]; res[2]=k[0]; } } } return res; }
Returns a sorted array of middle terms of the reduction polynomial.
public static String valueFor(String key,String defaultVal){ Configuration conf=instance(); String val=conf.properties.getProperty(key); val=(val == null ? defaultVal : val); if (val == null) { conf.warning("CONFIGURATION: no value found for key " + key + " and no default given."); } return val; }
Returns the value for key in the Configuration, or the default provided value if not found. A warning is issued to the log if the property is not defined, and if the default is null.
public synchronized void removeActionListener(ActionListener l){ if ((l != null) && (getAction() == l)) { setAction(null); } else { listenerList.remove(ActionListener.class,l); } }
Removes the specified action listener so that it no longer receives action events from this textfield.
@Override public boolean eIsSet(int featureID){ switch (featureID) { case SexecPackage.STATE_VECTOR__SIZE: return size != SIZE_EDEFAULT; case SexecPackage.STATE_VECTOR__OFFSET: return offset != OFFSET_EDEFAULT; } return super.eIsSet(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static long[] toPrimitive(final Long[] array,final long valueForNull){ if (array == null) { return null; } else if (array.length == 0) { return ArrayUtils.EMPTY_LONG_ARRAY; } final long[] result=new long[array.length]; for (int i=0; i < array.length; i++) { Long b=array[i]; result[i]=b == null ? valueForNull : b.longValue(); } return result; }
<p>Converts an array of object Long to primitives handling <code>null</code>.</p> <p>This method returns <code>null</code> for a <code>null</code> input array.</p>