code
stringlengths
10
174k
nl
stringlengths
3
129k
public Matrix4f scale(float x,float y,float z){ return scale(x,y,z,this); }
Apply scaling to this matrix by scaling the base axes by the given sx, sy and sz factors. <p> If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, then the new matrix will be <code>M * S</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first!
void stringConversion(Converter converter,String expected,Object value){ String valueType=(value == null ? "null" : value.getClass().getName()); String msg="Converting '" + valueType + "' value '"+ value+ "' to String"; try { Object result=converter.convert(String.class,value); Class<?> resultType=(result == null ? null : result.getClass()); Class<?> expectType=(expected == null ? null : expected.getClass()); assertEquals("TYPE " + msg,expectType,resultType); assertEquals("VALUE " + msg,expected,result); } catch ( Exception ex) { fail(msg + " threw " + ex.toString()); } }
Test Conversion to String
@Override public void close() throws IOException { synchronized (lock) { if (!isClosed()) { in.close(); buf=null; } } }
Closes this reader. This implementation closes the buffered source reader and releases the buffer. Nothing is done if this reader has already been closed.
public Object nextEntity(char ampersand) throws JSONException { StringBuffer sb=new StringBuffer(); for (; ; ) { char c=next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); } else if (c == ';') { break; } else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } String string=sb.toString(); Object object=entity.get(string); return object != null ? object : ampersand + string + ";"; }
Return the next entity. These entities are translated to Characters: <code>&amp; &apos; &gt; &lt; &quot;</code>.
public void testSerializeErrors() throws Throwable { CopycatError error; error=CopycatError.forId(new NoLeaderException("test").getType().id()); assertEquals(error,CopycatError.Type.NO_LEADER_ERROR); error=CopycatError.forId(new QueryException("test").getType().id()); assertEquals(error,CopycatError.Type.QUERY_ERROR); error=CopycatError.forId(new CommandException("test").getType().id()); assertEquals(error,CopycatError.Type.COMMAND_ERROR); error=CopycatError.forId(new ApplicationException("test").getType().id()); assertEquals(error,CopycatError.Type.APPLICATION_ERROR); error=CopycatError.forId(new IllegalMemberStateException("test").getType().id()); assertEquals(error,CopycatError.Type.ILLEGAL_MEMBER_STATE_ERROR); error=CopycatError.forId(new UnknownSessionException("test").getType().id()); assertEquals(error,CopycatError.Type.UNKNOWN_SESSION_ERROR); error=CopycatError.forId(new InternalException("test").getType().id()); assertEquals(error,CopycatError.Type.INTERNAL_ERROR); error=CopycatError.forId(new ConfigurationException("test").getType().id()); assertEquals(error,CopycatError.Type.CONFIGURATION_ERROR); }
Tests serializing exceptions.
public static String determineDescription(final INaviInstruction startInstruction,final String trackedRegister,final CInstructionResult result){ Preconditions.checkNotNull(startInstruction,"IE01680: Start instruction argument can not be null"); Preconditions.checkNotNull(trackedRegister,"IE01681: Tracked register argument can not be null"); Preconditions.checkNotNull(result,"IE01682: Result argument can not be null"); if (result.getInstruction() == startInstruction) { return "Start"; } else if (result.undefinesAll()) { return "Clears all effects"; } else if (result.clearsTrackedRegister(trackedRegister)) { return "Clears tracked register"; } else if (result.undefinesSome()) { return "Clears some effects"; } else if (result.defines()) { return "Depends on tracked register"; } else if (result.updates()) { return "Updates tainted register"; } else if (result.uses()) { return "Reads tainted register"; } else { return ""; } }
Determines the description text used to display a given instruction.
private MD5Legacy(InputStream in){ this.in=in; this.state=new int[4]; this.buffer=new byte[64]; this.count=0; state[0]=0x67452301; state[1]=0xefcdab89; state[2]=0x98badcfe; state[3]=0x10325476; }
Construct a digestifier for the given input stream.
public void testObjectMarshallingToJson(){ ToDoItem toDoItem=getToDoItem(REMINDER_ON); try { JSONObject json=toDoItem.toJSON(); assertEquals(TEXT_BODY,json.getString("todotext")); assertEquals(REMINDER_ON,json.getBoolean("todoreminder")); assertEquals(String.valueOf(CURRENT_DATE.getTime()),json.getString("tododate")); } catch ( JSONException e) { fail("Exception thrown during test execution: " + e.getMessage()); } }
Ensure we can marshall ToDoItem objects to Json
public String uploadId(){ return uploadId; }
Returns upload ID.
public SingleSignOnService(String location,String binding){ this.location=location; this.binding=binding; }
SingleSignOnService object. This object correspond to samlm:EndPointType
public AppletThreadGroup(String name){ this(Thread.currentThread().getThreadGroup(),name); }
Constructs a new thread group for an applet. The parent of this new group is the thread group of the currently running thread.
public void save(File file) throws IOException { IOUtils.writeBinary(file,quantiser); }
Save the quantiser to the specified file
private void addFeaturesToEncoder(Map<FeatureCollection,Style> featureCollectionStyleMap,double scaleDenominator){ for ( FeatureCollection featureCollection : featureCollectionStyleMap.keySet()) { String layerName=featureCollection.getSchema().getName().getLocalPart(); Style featureStyle=featureCollectionStyleMap.get(featureCollection); try (FeatureIterator<SimpleFeature> it=featureCollection.features()){ while (it.hasNext()) { SimpleFeature feature=it.next(); Collection<Property> propertiesList=feature.getProperties(); Map<String,Object> attributeMap=new HashMap<>(); for ( Property property : propertiesList) { if (!(property.getValue() instanceof Geometry)) { attributeMap.put(property.getName().toString(),property.getValue()); } } List<Geometry> geometryList=processSymbolizers(featureStyle,feature,scaleDenominator); for ( Geometry geometry : geometryList) { geometry=transFormGeometry(geometry); this.vectorTileEncoder.addFeature(layerName,attributeMap,geometry); } } } } }
Adds all features to the encoder and prepares it before. So geometries are removed from the attribute map and the geometry is transformed to the target tile local system
public boolean hasBPAccess(String BPAccessType,Object[] params){ if (isFullBPAccess()) return true; getBPAccess(false); for (int i=0; i < m_bpAccess.length; i++) { if (m_bpAccess[i].getBPAccessType().equals(BPAccessType)) { return true; } } return false; }
Has the user Access to BP info and resources
protected void processWindowEvent(WindowEvent e){ super.processWindowEvent(e); }
Window Events
public static boolean isExternalStorageReadable(){ String state=Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state); }
Check if external storage is readable or not
@Override public void run(){ amIActive=true; String streamsHeader=null; String pointerHeader=null; String outputHeader=null; int row, col, x, y; int progress=0; int i, c; 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}; boolean flag=false; double flowDir=0; double minStreamLength=0; boolean blnRemoveStream=false; int stopRow, stopCol; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (i=0; i < args.length; i++) { if (i == 0) { streamsHeader=args[i]; } else if (i == 1) { pointerHeader=args[i]; } else if (i == 2) { outputHeader=args[i]; } else if (i == 3) { minStreamLength=Double.parseDouble(args[i]); } } if ((streamsHeader == null) || (pointerHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster streams=new WhiteboxRaster(streamsHeader,"r"); int rows=streams.getNumberRows(); int cols=streams.getNumberColumns(); double noData=streams.getNoDataValue(); double gridResX=streams.getCellSizeX(); double gridResY=streams.getCellSizeY(); double diagGridRes=Math.sqrt(gridResX * gridResX + gridResY * gridResY); double[] gridLengths=new double[]{diagGridRes,gridResX,diagGridRes,gridResY,diagGridRes,gridResX,diagGridRes,gridResY}; double maxLinkID=streams.getMaximumValue(); minStreamLength=minStreamLength / ((gridResX + gridResY) / 2); WhiteboxRaster pntr=new WhiteboxRaster(pointerHeader,"r"); if (pntr.getNumberRows() != rows || pntr.getNumberColumns() != cols) { showFeedback("The input images must be of the same dimensions."); return; } WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",streamsHeader,WhiteboxRaster.DataType.FLOAT,0); output.setPreferredPalette("qual.pal"); output.setDataScale(WhiteboxRaster.DataScale.CATEGORICAL); updateProgress("Loop 1 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { output.setValue(row,col,streams.getValue(row,col)); } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 1 of 2:",progress); } byte numNeighbouringStreamCells=0; double linkLength=0; int x2, y2; updateProgress("Loop 2 of 2:",0); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { if (streams.getValue(row,col) > 0) { numNeighbouringStreamCells=0; for (c=0; c < 8; c++) { x=col + dX[c]; y=row + dY[c]; if (streams.getValue(y,x) > 0 && pntr.getValue(y,x) == inflowingVals[c]) { numNeighbouringStreamCells++; } } if (numNeighbouringStreamCells == 0) { linkLength=0; blnRemoveStream=false; x=col; y=row; stopRow=-1; stopCol=-1; flag=true; do { numNeighbouringStreamCells=0; for (c=0; c < 8; c++) { x2=x + dX[c]; y2=y + dY[c]; if (streams.getValue(y2,x2) > 0 && pntr.getValue(y2,x2) == inflowingVals[c]) { numNeighbouringStreamCells++; } } if (numNeighbouringStreamCells > 1) { if (linkLength < minStreamLength) { stopRow=y; stopCol=x; blnRemoveStream=true; } flag=false; break; } flowDir=pntr.getValue(y,x); if (flowDir > 0) { c=(int)(Math.log(flowDir) / LnOf2); if (c > 7) { showFeedback("An unexpected value has " + "been identified in the pointer " + "image. This tool requires a "+ "pointer grid that has been "+ "created using either the D8 "+ "or Rho8 tools."); return; } linkLength+=gridLengths[c]; if (linkLength > minStreamLength) { flag=false; } else { x+=dX[c]; y+=dY[c]; if (streams.getValue(y,x) <= 0) { flag=false; } } } else { flag=false; } } while (flag); if (blnRemoveStream) { x=col; y=row; flag=true; do { if (x == stopCol && y == stopRow) { flag=false; break; } output.setValue(y,x,noData); flowDir=pntr.getValue(y,x); if (flowDir > 0) { c=(int)(Math.log(flowDir) / LnOf2); x+=dX[c]; y+=dY[c]; if (streams.getValue(y,x) <= 0) { flag=false; } } else { flag=false; } } while (flag); } } } else { output.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(int)(100f * row / (rows - 1)); updateProgress("Loop 1 of 2:",progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); streams.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 static FileChannel open(String fileName,String mode) throws IOException { return FilePath.get(fileName).open(mode); }
Open a random access file object. This method is similar to Java 7 <code>java.nio.channels.FileChannel.open</code>.
public static void forceDelete(final File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { final boolean filePresent=file.exists(); if (!file.delete()) { if (!filePresent) { throw new FileNotFoundException("File does not exist: " + file); } final String message="Unable to delete file: " + file; throw new IOException(message); } } }
Deletes a file. If file is a directory, delete it and all sub-directories. <p> The difference between File.delete() and this method are: <ul> <li>A directory to be deleted does not have to be empty.</li> <li>You get exceptions when a file or directory cannot be deleted. (java.io.File methods returns a boolean)</li> </ul>
public void addReturn(CtClass type){ if (type == null) addOpcode(RETURN); else if (type.isPrimitive()) { CtPrimitiveType ptype=(CtPrimitiveType)type; addOpcode(ptype.getReturnOp()); } else addOpcode(ARETURN); }
Appends ARETURN, IRETURN, .., or RETURN.
public void clear(){ final int lastRow=data.size() - 1; data.clear(); if (lastRow >= 0) this.fireTableRowsDeleted(0,lastRow); }
Clears the table completely.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
@Override public int eBaseStructuralFeatureID(int derivedFeatureID,Class<?> baseClass){ if (baseClass == ReactiveElement.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__LOCAL_REACTIONS: return SGraphPackage.REACTIVE_ELEMENT__LOCAL_REACTIONS; default : return -1; } } if (baseClass == ScopedElement.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__SCOPES: return SGraphPackage.SCOPED_ELEMENT__SCOPES; case SGraphPackage.STATE__NAMESPACE: return SGraphPackage.SCOPED_ELEMENT__NAMESPACE; default : return -1; } } if (baseClass == NamedElement.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__NAME: return BasePackage.NAMED_ELEMENT__NAME; default : return -1; } } if (baseClass == Vertex.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__PARENT_REGION: return SGraphPackage.VERTEX__PARENT_REGION; case SGraphPackage.STATE__INCOMING_TRANSITIONS: return SGraphPackage.VERTEX__INCOMING_TRANSITIONS; case SGraphPackage.STATE__OUTGOING_TRANSITIONS: return SGraphPackage.VERTEX__OUTGOING_TRANSITIONS; default : return -1; } } if (baseClass == RegularState.class) { switch (derivedFeatureID) { default : return -1; } } if (baseClass == CompositeElement.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__REGIONS: return SGraphPackage.COMPOSITE_ELEMENT__REGIONS; default : return -1; } } if (baseClass == DocumentedElement.class) { switch (derivedFeatureID) { case SGraphPackage.STATE__DOCUMENTATION: return BasePackage.DOCUMENTED_ELEMENT__DOCUMENTATION; default : return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID,baseClass); }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected void skipTransform() throws IOException { loop: for (; ; ) { current=reader.read(); switch (current) { case ')': break loop; default : if (current == -1) { break loop; } } } }
Skips characters in the given reader until a ')' is encountered.
public void resetNotification(){ this.lastEmailAlertReason=null; this.lastEmailAlertTime=-1L; this.lastWebAlertTime=-1L; this.lastWebAlertReason=null; }
Reset if alert is resolved
public void loadSettings(JDialog dialog){ if (!dialog.getName().contains("dialog")) { Rectangle rect=getWindowBounds(dialog.getName()); if (rect.width > 0) { dialog.setBounds(rect); } } }
Load settings for a dialog
@Override public void clear(){ size=0; for (int i=0; i < elementData.length; i++) { elementData[i]=null; } modCount++; }
Removes all elements from this map, leaving it empty.
public void endDocument() throws IOException { writer.flush(); }
Output the text for the end of a document.
public void rotate(@Nonnull File file,int max,String extension) throws IOException { if (max < 1) { throw new IllegalArgumentException(); } String name=file.getName(); if (extension != null) { if (extension.length() > 0 && !extension.startsWith(".")) { extension="." + extension; } } else { extension=""; } File dir=file.getParentFile(); File source; int i=max; while (i > 1) { source=new File(dir,name + "." + (i - 1)+ extension); if (source.exists()) { this.copy(source,new File(dir,name + "." + i+ extension)); } i--; } this.copy(file,new File(dir,name + "." + i+ extension)); }
Rotate a file and its backups, retaining only a set number of backups.
public boolean updateAllTypes(){ return updateAllTypes; }
True if all fields that span multiple types should be updated, false otherwise
protected AbstractAtomicRowReadOrWrite(){ super(); }
De-serialization ctor.
@Override public void chartChanged(ChartChangeEvent event){ this.flag=true; }
Event handler.
@Override protected void addConvert(ConvertMetadata convert){ if (m_converts == null) { m_converts=new ArrayList<ConvertMetadata>(); } m_converts.add(convert); }
INTERNAL: Subclasses that support key converts need to override this method.
public static void bootstrapConf(SolrZkClient zkClient,CoreContainer cc,String solrHome) throws IOException { ZkConfigManager configManager=new ZkConfigManager(zkClient); List<CoreDescriptor> cds=cc.getCoresLocator().discover(cc); log.info("bootstrapping config for " + cds.size() + " cores into ZooKeeper using solr.xml from "+ solrHome); for ( CoreDescriptor cd : cds) { String coreName=cd.getName(); String confName=cd.getCollectionName(); if (StringUtils.isEmpty(confName)) confName=coreName; Path udir=cd.getInstanceDir().resolve("conf"); log.info("Uploading directory " + udir + " with name "+ confName+ " for SolrCore "+ coreName); configManager.uploadConfigDir(udir,confName); } }
If in SolrCloud mode, upload config sets for each SolrCore in solr.xml.
private void handleBrowse(){ containerText.setText(WorkspaceTools.selectProject(containingPage.getShell(),getContainerName())); }
Uses the standard container selection dialog to choose the new value for the container field.
private void addDiscussionItems(SteamGiftsUserData account,String mode){ if ("full".equals(mode)) { drawer.addItem(new SectionDrawerItem().withName(R.string.navigation_discussions).withDivider(true)); for ( DiscussionListFragment.Type type : DiscussionListFragment.Type.values()) { if (type == DiscussionListFragment.Type.CREATED && !account.isLoggedIn()) continue; drawer.addItem(new PrimaryDrawerItem().withName(type.getNavbarResource()).withIdentifier(type.getNavbarResource()).withIcon(type.getIcon())); } } else if ("compact".equals(mode)) { drawer.addItem(new PrimaryDrawerItem().withName(R.string.navigation_discussions).withIdentifier(DiscussionListFragment.Type.ALL.getNavbarResource()).withIcon(DiscussionListFragment.Type.ALL.getIcon())); } }
Add all discussion-related items.
private Point restoreWindowLocation(){ Point result=null; final String sizestr=preferences.get(prefnzPrefix + PREF_WINDOW_POSITION,null); if (sizestr != null) { int x=0; int y=0; final String[] sizes=sizestr.split("[,]"); try { x=Integer.parseInt(sizes[0].trim()); y=Integer.parseInt(sizes[1].trim()); } catch ( final Exception e) { } if (x > 0 && y > 0) { result=new Point(x,y); if (logger.isDebugEnabled()) logger.debug("Restoring preference " + PREF_WINDOW_POSITION + "="+ result.x+ ","+ result.y); this.setLocation(result); } } return result; }
Loads and set the saved position preferences for this frame.
@Deprecated Template(String name,TemplateElement root,Configuration cfg){ this(name,null,cfg,(ParserConfiguration)null); this.rootElement=root; DebuggerService.registerTemplate(this); }
Only meant to be used internally.
private void updateSortingIcons(){ for ( SortingType type : SortingType.values()) { SortingDirection direction=model.getSortingDirection(type); ImageIcon icon; switch (direction) { case DESCENDING: icon=ICON_ARROW_DOWN; break; case ASCENDING: icon=ICON_ARROW_UP; break; case UNDEFINED: icon=null; break; default : icon=null; } switch (type) { case NAME: sortingLabelAttName.setIcon(icon); break; case TYPE: sortingLabelAttType.setIcon(icon); break; case MISSING: sortingLabelAttMissings.setIcon(icon); break; default : sortingLabelAttName.setIcon(null); sortingLabelAttType.setIcon(null); sortingLabelAttMissings.setIcon(null); } } }
Updates the sorting icons.
@Override public void initialize(){ }
Rule featurizer.
public boolean isVlanTaggingSupported(){ return vlanTaggingSupported; }
Gets the value of the vlanTaggingSupported property.
public static String id8(UUID id){ return id.toString().substring(0,8); }
Gets 8-character substring of UUID (for terse logging).
public basefont addElement(Element element){ addElementToRegistry(element); return (this); }
Adds an Element to the element.
@Override public PartitionKeyGroup createPartitionKeyGroup(PartitionKeyGroupCreateRequest request){ partitionKeyGroupHelper.validatePartitionKeyGroupKey(request.getPartitionKeyGroupKey()); PartitionKeyGroupEntity partitionKeyGroupEntity=partitionKeyGroupDao.getPartitionKeyGroupByKey(request.getPartitionKeyGroupKey()); if (partitionKeyGroupEntity != null) { throw new AlreadyExistsException(String.format("Unable to create partition key group with name \"%s\" because it already exists.",request.getPartitionKeyGroupKey().getPartitionKeyGroupName())); } partitionKeyGroupEntity=createPartitionKeyGroupEntity(request); partitionKeyGroupEntity=partitionKeyGroupDao.saveAndRefresh(partitionKeyGroupEntity); return createPartitionKeyGroupFromEntity(partitionKeyGroupEntity); }
Creates a new partition key group.
public OptionsHttpSessionsPanel(){ super(); initialize(); }
Instantiates a new options panel for http sessions.
public boolean hasPurchase(String sku){ return mPurchaseMap.containsKey(sku); }
Returns whether or not there exists a purchase of the given product.
public void testGetNameWhenWarHasExtension(){ WAR war=new WAR("c:/some/path/to/war/test.war"); assertEquals("test",war.getName()); }
Test name when WAR has an extension.
public int updateByExampleSelective(User record,UserExample example) throws SQLException { UpdateByExampleParms parms=new UpdateByExampleParms(record,example); int rows=sqlMapClient.update("t_user.ibatorgenerated_updateByExampleSelective",parms); return rows; }
This method was generated by Apache iBATIS ibator. This method corresponds to the database table t_user
public soot.Local generateLocal(soot.Type type){ initLocalNames(); String name="v"; if (type instanceof soot.IntType) { while (true) { name=nextIntName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.ByteType) { while (true) { name=nextByteName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.ShortType) { while (true) { name=nextShortName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.BooleanType) { while (true) { name=nextBooleanName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.VoidType) { while (true) { name=nextVoidName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.CharType) { while (true) { name=nextCharName(); if (!bodyContainsLocal(name)) break; } type=soot.CharType.v(); } else if (type instanceof soot.DoubleType) { while (true) { name=nextDoubleName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.FloatType) { while (true) { name=nextFloatName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.LongType) { while (true) { name=nextLongName(); if (!bodyContainsLocal(name)) break; } } else if (type instanceof soot.RefLikeType) { while (true) { name=nextRefLikeTypeName(); if (!bodyContainsLocal(name)) break; } } else { localNames=null; throw new RuntimeException("Unhandled Type of Local variable to Generate - Not Implemented"); } localNames=null; return createLocal(name,type); }
generates a new soot local given the type
@Override protected EClass eStaticClass(){ return TypesPackage.Literals.TMEMBER_WITH_ACCESS_MODIFIER; }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void testManyEventsAfterLeaderShutdown(int nodes) throws Throwable { List<CopycatServer> servers=createServers(nodes); CopycatClient client=createClient(); client.onEvent("test",null); for (int i=0; i < 10; i++) { client.submit(new TestEvent(true)).thenAccept(null); await(30000,2); } CopycatServer leader=servers.stream().filter(null).findFirst().get(); leader.shutdown().get(10,TimeUnit.SECONDS); for (int i=0; i < 10; i++) { client.submit(new TestEvent(true)).thenAccept(null); await(30000,2); } }
Tests submitting a linearizable event that publishes to all sessions.
private static void addCurve(Path2D line,Point2D p0,Point2D p1,Point2D p2,Point2D p3,Point2D ctrl1,Point2D ctrl2,double smoothness){ if (p1 == null) { return; } if (line.getCurrentPoint() == null) { line.moveTo(p1.getX(),p1.getY()); } if (p2 == null) { return; } getControlsPoints(p0,p1,p2,p3,ctrl1,ctrl2,smoothness); line.curveTo(ctrl1.getX(),ctrl1.getY(),ctrl2.getX(),ctrl2.getY(),p2.getX(),p2.getY()); }
Utility method to add a smooth curve segment to a specified line path.
public int currentBaudNumber(String currentBaudRate){ String[] rates=validBaudRates(); int[] numbers=validBaudNumber(); if (numbers == null) { log.error("numbers array null in currentBaudNumber"); return -1; } if (rates == null) { log.error("rates array null in currentBaudNumber"); return -1; } if (numbers.length < 1 || (numbers.length != rates.length)) { log.error("arrays wrong length in currentBaudNumber: " + numbers.length + ","+ rates.length); return -1; } for (int i=0; i < numbers.length; i++) { if (rates[i].equals(currentBaudRate)) { return numbers[i]; } } log.error("no match to (" + currentBaudRate + ") in currentBaudNumber"); return -1; }
Convert a baud rate string to a number. Uses the validBaudNumber and validBaudRates methods to do this.
public XYDataItem(double x,double y){ this(new Double(x),new Double(y)); }
Constructs a new data item.
protected void fireItemStateChanged(ItemEvent e){ Object[] listeners=listenerList.getListenerList(); for (int i=listeners.length - 2; i >= 0; i-=2) { if (listeners[i] == ItemListener.class) { ((ItemListener)listeners[i + 1]).itemStateChanged(e); } } }
Notifies all listeners that have registered interest for notification on this event type.
public void startBridgeServer(int port,boolean notifyBySubscription) throws IOException { Cache cache=getCache(); CacheServer bridge=cache.addCacheServer(); bridge.setPort(port); bridge.setNotifyBySubscription(notifyBySubscription); bridge.start(); bridgeServerPort=bridge.getPort(); }
Starts a bridge server on the given port, using the given deserializeValues and notifyBySubscription to serve up the given region.
@Override public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch=false; } if (outputFormatPeek() != null) { convertInstance(instance); return true; } bufferInput(instance); return false; }
Input an instance for filtering. Ordinarily the instance is processed and made available for output immediately. Some filters require all instances be read before producing output.
public IntCharSet copy(){ IntCharSet result=new IntCharSet(); for ( Interval interval : intervals) result.intervals.add(interval.copy()); return result; }
Return a (deep) copy of this char set
public Builder put(String key,String customFileName,File file) throws FileNotFoundException { mParams.put(key,file,null,customFileName); return this; }
Adds a file to the request with custom provided file name
public PreferenceBuilder<PreferenceClass> prefKey(String prefKey){ this.prefKey=prefKey; return this; }
The key of the preference to retrieve
public ScReplay[] createConsistencyGroupSnapshots(String instanceId) throws StorageCenterAPIException { LOG.debug("Creating consistency group snapshots for '{}'",instanceId); String id=UUID.randomUUID().toString().substring(0,31); Parameters params=new Parameters(); params.add("description",id); params.add("expireTime",0); RestResult rr=restClient.post(String.format("StorageCenter/ScReplayProfile/%s/CreateReplay",instanceId),params.toJson()); if (!checkResults(rr)) { String msg=String.format("Error creating snapshots from CG %s: %s",instanceId,rr.getErrorMsg()); LOG.error(msg); throw new StorageCenterAPIException(msg); } rr=restClient.get(String.format("StorageCenter/ScReplayProfile/%s/ConsistencyGroupList",instanceId)); if (!checkResults(rr)) { String msg=String.format("Error getting consistent groups: %s",rr.getErrorMsg()); LOG.warn(msg); throw new StorageCenterAPIException(msg); } ScReplayConsistencyGroup consistentGroup=null; ScReplayConsistencyGroup[] cgs=gson.fromJson(rr.getResult(),ScReplayConsistencyGroup[].class); for ( ScReplayConsistencyGroup cg : cgs) { if (id.equals(cg.description)) { consistentGroup=cg; } } if (consistentGroup != null) { rr=restClient.get(String.format("StorageCenter/ScReplayConsistencyGroup/%s/ReplayList",consistentGroup.instanceId)); if (checkResults(rr)) { return gson.fromJson(rr.getResult(),ScReplay[].class); } } throw new StorageCenterAPIException("Unable to get replays created for consistency group."); }
Create snapshots for the consistency group.
private String computeSort(){ List<Book> books=DataModel.getMapOfBooksByAuthor().get(this); if (books != null) for ( Book book : books) { if (book.hasSingleAuthor()) { String authorSort=book.getAuthorSort(); if (Helper.isNotNullOrEmpty(authorSort) && authorSort.contains(",")) return authorSort; } } int posOfSpace=name.indexOf(','); if (posOfSpace >= 0) { guessedLastName=name.substring(0,posOfSpace); return name; } List<String> words=Helper.tokenize(name," "); switch (words.size()) { case 1: guessedLastName=name; return name; case 0: logger.warn("Problem computing Author sort for author: " + name); guessedLastName="[CALIBRE2OPDS] BAD_AUTHOR_SORT (" + name + ")"; return guessedLastName; default : guessedLastName=words.get(words.size() - 1); words.remove(words.size() - 1); return guessedLastName + ", " + Helper.concatenateList(" ",words); } }
Derive the value we are going to use for sorting by Author
public static String parseResourceId(String path){ String result=null; if (path != null && path.length() > 0) { int index=path.lastIndexOf("/"); String fileName=path.substring(index + 1); result=fileName.substring(0,fileName.lastIndexOf(".")); } return result; }
Parse path url, obtain database id from file name.
public void rectValueToPixel(RectF r){ mMatrixValueToPx.mapRect(r); mViewPortHandler.getMatrixTouch().mapRect(r); mMatrixOffset.mapRect(r); }
Transform a rectangle with all matrices.
public boolean hasViewAttached(){ return mView != null; }
Helper method to determine if View is attached at the moment
public final static byte[] toAsciiByteArray(CharSequence charSequence){ byte[] barr=new byte[charSequence.length()]; for (int i=0; i < barr.length; i++) { char c=charSequence.charAt(i); barr[i]=(byte)((int)(c <= 0xFF ? c : 0x3F)); } return barr; }
Converts char sequence into ASCII byte array.
public Text padLeft(int len,char c){ final int padSize=(len <= length()) ? 0 : len - length(); return insert(0,Text.valueOf(c,padSize)); }
Pads this text on the left to make the minimum total length as specified. Spaces or the given Unicode character are used to pad with. <br> The new length of the new text is equal to the original length plus <code>(length()-len)</code> pad characters.
public Criteria or(){ Criteria criteria=createCriteriaInternal(); oredCriteria.add(criteria); return criteria; }
This method was generated by MyBatis Generator. This method corresponds to the database table group
public void testPackageContainer() throws Exception { StandaloneLocalConfiguration configuration=(StandaloneLocalConfiguration)createConfiguration(ConfigurationType.STANDALONE); InstalledLocalContainer container=(InstalledLocalContainer)createContainer(configuration); Deployable war=new DefaultDeployableFactory().createDeployable(container.getId(),getTestData().getTestDataFileFor("simple-war"),DeployableType.WAR); configuration.addDeployable(war); configuration.configure(container); File targetLocation=new File(new File(getTestData().targetDir).getParentFile(),"package"); PackagerFactory factory=new DefaultPackagerFactory(); Packager packager=factory.createPackager(getTestData().containerId,PackagerType.DIRECTORY,targetLocation.getPath()); packager.packageContainer(container); InstalledLocalContainer assertContainer=(InstalledLocalContainer)new DefaultContainerFactory().createContainer(getTestData().containerId,getTestData().containerType,createConfiguration(ConfigurationType.EXISTING,targetLocation.getPath())); assertContainer.setLogger(getLogger()); assertContainer.setHome(targetLocation.getPath()); URL warPingURL=new URL("http://localhost:" + getTestData().port + "/simple-war/index.jsp"); assertContainer.start(); PingUtils.assertPingTrue("simple war not started",warPingURL,getLogger()); assertContainer.stop(); PingUtils.assertPingFalse("simple war not stopped",warPingURL,getLogger()); }
Create the packaging of a container and that it works when unpackaged.
public void increaseThis(){ addToThis(ONE((GF2nONBField)mField)); }
increases <tt>this</tt> element.
public SnapshotState state(){ return state; }
Returns snapshot state
protected SelectedSparseObjectMatrix1D(AbstractIntObjectMap elements,int[] offsets){ this(offsets.length,elements,0,1,offsets,0); }
Constructs a matrix view with the given parameters.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case ImPackage.DELEGATING_SETTER_DECLARATION__DELEGATION_BASE_TYPE: if (resolve) return getDelegationBaseType(); return basicGetDelegationBaseType(); case ImPackage.DELEGATING_SETTER_DECLARATION__DELEGATION_SUPER_CLASS_STEPS: return getDelegationSuperClassSteps(); case ImPackage.DELEGATING_SETTER_DECLARATION__DELEGATION_TARGET: if (resolve) return getDelegationTarget(); return basicGetDelegationTarget(); case ImPackage.DELEGATING_SETTER_DECLARATION__DELEGATION_TARGET_IS_ABSTRACT: return isDelegationTargetIsAbstract(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public ConjunctionOfClauses extend(Collection<Clause> additionalClauses){ Set<Clause> extendedClauses=new LinkedHashSet<Clause>(); extendedClauses.addAll(clauses); extendedClauses.addAll(additionalClauses); ConjunctionOfClauses result=new ConjunctionOfClauses(extendedClauses); return result; }
Create a new conjunction of clauses by taking the clauses from the current conjunction and adding additional clauses to it.
public static void main(String[] args){ exec(args); }
Run the benchmark algorithm.
public long lastseenTime(){ return time - lastseen() * 60000; }
get the absolute time when this peer was seen in the network
public void play(String mStreamURL){ sendBroadcast(new Intent(ACTION_RADIOPLAYER_STOP)); notifyPlayerLoading(); if (mState == State.PAUSED && this.mStreamURL.equals(mStreamURL)) { mediaPlayer.start(); mState=State.PLAYING; notifyPlayerStarted(mediaPlayer.getDuration(),mediaPlayer.getCurrentPosition()); } else { try { resetMediaPlayer(); this.mStreamURL=mStreamURL; mediaPlayer.setDataSource(mStreamURL); mediaPlayer.prepareAsync(); } catch ( IOException e) { e.printStackTrace(); } } }
Play music streaming
public Type1(){ }
needed so CIDFOnt0 can extend
public final int yystate(){ return zzLexicalState; }
Returns the current lexical state.
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter,java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix=xmlWriter.getPrefix(namespace); if (prefix == null) { prefix=generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix=org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } return prefix; }
Register a namespace prefix
public void testGetters8(){ LayoutBuilder b=builder().setText("This is a longer test").setIncludePad(true).setWidth(50).setSpacingAdd(2).setSpacingMult(.8f); FontMetricsInt fmi=b.paint.getFontMetricsInt(); Scaler s=new Scaler(b.spacingMult,b.spacingAdd); Layout l=b.build(); assertVertMetrics(l,fmi.top - fmi.ascent,fmi.bottom - fmi.descent,fmi.top,fmi.descent + s.scale(fmi.descent - fmi.top),fmi.ascent,fmi.descent + s.scale(fmi.descent - fmi.ascent),fmi.ascent,fmi.bottom + s.scale(fmi.bottom - fmi.ascent)); }
Basic test showing effect of includePad = true, spacingAdd = 0, spacingMult = 0.8 when wrapping to 3 lines.
public RetrieveAndRank(){ super("retrieve_and_rank"); if ((getEndPoint() == null) || getEndPoint().isEmpty()) { setEndPoint(URL); } }
Instantiates a new ranker client.
private <V>PCollection<KV<K,RawUnionValue>> makeUnionTable(final int index,PCollection<KV<K,V>> pCollection,KvCoder<K,RawUnionValue> unionTableEncoder){ return pCollection.apply("MakeUnionTable" + index,ParDo.of(new ConstructUnionTableFn<K,V>(index))).setCoder(unionTableEncoder); }
Returns a UnionTable for the given input PCollection, using the given union index and the given unionTableEncoder.
public void removeCalendarSelectionListener(CalendarSelectionListener listener){ calendarSelectionListeners.remove(listener); }
removeCalendarSelectionListener, This removes the specified calendar selection listener from this CalendarPanel.
public String readString() throws IOException { int firstByte=readByte(); int length=readInt(firstByte,PREFIX_8_BITS); byte[] encoded=new byte[length]; bytesLeft-=length; in.readFully(encoded); return new String(encoded,"UTF-8"); }
Reads a UTF-8 encoded string. Since ASCII is a subset of UTF-8, this method may be used to read strings that are known to be ASCII-only.
public static void showOptionSheet(Component parentComponent,Object message,int optionType,int messageType,@Nullable Icon icon,@Nullable Object[] options,@Nullable Object initialValue,SheetListener listener){ JOptionPane pane=new JOptionPane(message,messageType,optionType,icon,options,initialValue); pane.setInitialValue(initialValue); pane.setComponentOrientation(((parentComponent == null) ? JOptionPane.getRootFrame() : parentComponent).getComponentOrientation()); int style=styleFromMessageType(messageType); JSheet sheet=createSheet(pane,parentComponent,style); pane.selectInitialValue(); sheet.addSheetListener(listener); sheet.show(); sheet.toFront(); }
Brings up a sheet with a specified icon, where the initial choice is determined by the <code>initialValue</code> parameter and the number of choices is determined by the <code>optionType</code> parameter. <p> If <code>optionType</code> is <code>YES_NO_OPTION</code>, or <code>YES_NO_CANCEL_OPTION</code> and the <code>options</code> parameter is <code>null</code>, then the options are supplied by the look and feel. <p> The <code>messageType</code> parameter is primarily used to supply a default icon from the look and feel.
public ShortBuffer duplicate(){ ShortBuffer buf=new ShortBuffer(byteBuffer.duplicate()); buf.limit=limit; buf.position=position; buf.mark=mark; return buf; }
Returns a duplicated buffer that shares its content with this buffer. <p> The duplicated buffer's position, limit, capacity and mark are the same as this buffer. The duplicated buffer's read-only property and byte order are the same as this buffer's. </p> <p> The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the other. The two buffer's position, limit and mark are independent. </p>
@Override public String toString(){ return "CUarray[" + "nativePointer=0x" + Long.toHexString(getNativePointer()) + "]"; }
Returns a String representation of this object.
public Document parse(String content){ LagartoParser lagartoParser=new LagartoParser(content,true); return doParse(lagartoParser); }
Creates DOM tree from the provided content.
public DViewPrivateKey(JFrame parent,String title,PrivateKey privateKey,Provider provider) throws CryptoException { super(parent,title,Dialog.ModalityType.DOCUMENT_MODAL); this.privateKey=privateKey; this.provider=provider; initComponents(); }
Creates a new DViewPrivateKey dialog.
public int fetchPattern(String key){ for (int i=0; i < Cell.expressionPatterns.length; i++) if (Cell.expressionPatterns[i].equalsIgnoreCase(key)) return i; System.out.println("Unknown expression pattern: " + key); return 0; }
Fetches an expression pattern in the pattern dictionary by a given key, creating a new pattern if the key doesn't exist yet.
public void tableChanged(TableModelEvent e){ if (!loading) calculateSelection(); }
Table Model Listener
public void tickCube(boolean tryToTickFaster){ if (!this.isInitialLightingDone && this.isPopulated) { this.tryDoFirstLight(); } while (!this.tileEntityPosQueue.isEmpty()) { BlockPos blockpos=this.tileEntityPosQueue.poll(); IBlockState state=this.getBlockState(blockpos); Block block=state.getBlock(); if (this.getTileEntity(blockpos,Chunk.EnumCreateEntityType.CHECK) == null && block.hasTileEntity(state)) { TileEntity tileentity=this.createTileEntity(blockpos); this.world.setTileEntity(blockpos,tileentity); this.world.markBlockRangeForRenderUpdate(blockpos,blockpos); } } }
Tick this cube
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-25 15:47:15.465 -0400",hash_original_method="8B9C9DA5FC3E4B4973EEF627B10AB2C3",hash_generated_method="E5C48F7C4C445F8E9E1E390A2036B6DD") public void testEnable(){ int iterations=BluetoothTestRunner.sEnableIterations; if (iterations == 0) { return; } BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); mTestUtils.disable(adapter); for (int i=0; i < iterations; i++) { mTestUtils.writeOutput("enable iteration " + (i + 1) + " of "+ iterations); mTestUtils.enable(adapter); mTestUtils.disable(adapter); } }
Stress test for enabling and disabling Bluetooth.
protected Point2D _forward(double phi,double lambda,Point2D p,AzimuthVar azVar){ double c=hemisphere_distance(centerY,centerX,phi,lambda); if (c > HEMISPHERE_EDGE) { double az=GreatCircle.sphericalAzimuth(centerY,centerX,phi,lambda); if (azVar != null) { azVar.invalid_forward=true; azVar.current_azimuth=(float)az; } return edge_point(p,az); } double kPrime=1 / Math.cos(c); double cosPhi=Math.cos(phi); double sinPhi=Math.sin(phi); double lambdaMinusCtrLon=lambda - centerX; double cosLambdaMinusCtrLon=Math.cos(lambdaMinusCtrLon); double sinLambdaMinusCtrLon=Math.sin(lambdaMinusCtrLon); double x=(scaled_radius * kPrime * cosPhi* sinLambdaMinusCtrLon) + wx; double y=hy - (scaled_radius * kPrime * (cosCtrLat * sinPhi - sinCtrLat * cosPhi * cosLambdaMinusCtrLon)); p.setLocation(x,y); return p; }
Forward project a point. If the point is not within the viewable hemisphere, return flags in AzimuthVar variable if specified.
protected void addProgressBar(final JProgressBar pbar){ super.add(pbar); super.revalidate(); }
Add a new progress bar. Protected, so this can be called via invokeLater
public JaasConfiguration(String principal,File keytab,String appName){ this(principal,keytab,null,null); clientAppName=appName; serverAppName=null; }
Add an entry to the jaas configuration with the passed in principal and keytab, along with the app name.
private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); writePaintMap(this.tickLabelPaintMap,stream); }
Provides serialization support.
private void generateImportStatement(String importPackage){ PsiImportList psiImportList=psiFile.getImportList(); if (null == psiImportList.findOnDemandImportStatement(importPackage)) { psiImportList.add(factory.createImportStatementOnDemand(importPackage)); } }
Generate import statement.
@Override public void sendPrivateText(final NotificationType type,final String text){ this.addEvent(new PrivateTextEvent(type,text)); this.notifyWorldAboutChanges(); }
Sends a message that only this player can read.