code
stringlengths
10
174k
nl
stringlengths
3
129k
public boolean merge_stringbuffer(){ return soot.PhaseOptions.getBoolean(options,"merge-stringbuffer"); }
Merge String Buffer -- Represent all StringBuffers as one object. When this option is set to true, all allocation sites creating java.lang.StringBuffer objects are grouped together as a single allocation site.
public void addFactor(String factor){ if (!NamingProtocol.isLegalName(factor)) { throw new IllegalArgumentException(NamingProtocol.getProtocolDescription()); } if (!existsFactor(factor)) { try { lagGraph.addFactor(factor); getPropertyChangeManager().firePropertyChange("nodeAdded",null,factor); } catch ( Exception e) { } } }
Attempts to add a factor to the graph. Will throw a propertyChange event of (null, (String) factor).
private void switchToRegularCapture(){ SettingsManager settingsManager=mAppController.getSettingsManager(); settingsManager.set(SettingsManager.SCOPE_GLOBAL,Keys.KEY_CAMERA_HDR_PLUS,false); ButtonManager buttonManager=mAppController.getButtonManager(); buttonManager.disableButtonClick(ButtonManager.BUTTON_HDR_PLUS); mAppController.getCameraAppUI().freezeScreenUntilPreviewReady(); mAppController.onModeSelected(mContext.getResources().getInteger(R.integer.camera_mode_photo)); buttonManager.enableButtonClick(ButtonManager.BUTTON_HDR_PLUS); }
Switches to PhotoModule to do regular photo captures. <p> TODO: Remove this once we use CaptureModule for photo taking.
public Key min(){ if (isEmpty()) throw new NoSuchElementException("called min() with empty set"); return set.first(); }
Returns the smallest key in this set.
public static ComponentUI createUI(JComponent a){ ComponentUI mui=new MultiComboBoxUI(); return MultiLookAndFeel.createUIs(mui,((MultiComboBoxUI)mui).uis,a); }
Returns a multiplexing UI instance if any of the auxiliary <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the UI object obtained from the default <code>LookAndFeel</code>.
protected void appendDetail(StringBuffer buffer,String fieldName,float[] array){ buffer.append(arrayStart); for (int i=0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer,fieldName,array[i]); } buffer.append(arrayEnd); }
<p>Append to the <code>toString</code> the detail of a <code>float</code> array.</p>
public void appendLine(final String propertyName,final String rawValue){ appendLine(propertyName,rawValue,false,false); }
Appends one line with a given property name and value.
@Override public double cloudletSubmit(Cloudlet cl,double fileTransferTime){ ResCloudlet rcl=new ResCloudlet(cl); rcl.setCloudletStatus(Cloudlet.INEXEC); for (int i=0; i < cl.getNumberOfPes(); i++) { rcl.setMachineAndPeId(0,i); } getCloudletExecList().add(rcl); return getEstimatedFinishTime(rcl,getPreviousTime()); }
Receives an cloudlet to be executed in the VM managed by this scheduler.
public boolean isAnonymous(){ if (keyExchange == KEY_EXCHANGE_DH_anon || keyExchange == KEY_EXCHANGE_DH_anon_EXPORT || keyExchange == KEY_EXCHANGE_ECDH_anon) { return true; } return false; }
Returns true if cipher suite is anonymous
public void testGetDumpParserForSunLogfile() throws FileNotFoundException { System.out.println("getDumpParserForVersion"); InputStream dumpFileStream=new FileInputStream("test/none/test.log"); Map threadStore=null; DumpParserFactory instance=DumpParserFactory.get(); DumpParser result=instance.getDumpParserForLogfile(dumpFileStream,threadStore,false,0); assertNotNull(result); assertTrue(result instanceof com.pironet.tda.SunJDKParser); }
Test of getDumpParserForVersion method, of class com.pironet.tda.DumpParserFactory.
public XmlTextBuilder(){ m_textBuf=new StringBuffer(DEFAULT_CAPACITY); m_auxBuf=new StringBuffer(AUX_CAPACITY); }
Construye un objeto de la clase.
public static void storeResult(final Message message,final Object result) throws Exception { String resultString; if (result != null) { JsonArray jsonArray=JsonUtil.toJSONArray(new Object[]{result}); resultString=jsonArray.toString(); } else { resultString=null; } message.getBodyBuffer().writeNullableSimpleString(SimpleString.toSimpleString(resultString)); }
Used by ActiveMQ Artemis management service.
public AnnotationList createAnnotationList(){ AnnotationListImpl annotationList=new AnnotationListImpl(); return annotationList; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public boolean isSetTriggerName(){ return this.triggerName != null; }
Returns true if field triggerName is set (has been assigned a value) and false otherwise
private Transaction tx(long id){ Transaction tx=txMap.get(id); assert tx != null : "Transaction not found for ID: " + id; return tx; }
Get transaction by ID.
public void checkFollowers(){ if (!getAutoFollow() && getWelcomeMessage().isEmpty()) { return; } try { log("Checking followers",Level.FINE); long[] followerIds=getConnection().getFollowersIDs(-1).getIDs(); long[] friends=getConnection().getFriendsIDs(-1).getIDs(); int friendCount=friends.length; int count=0; boolean welcomeOnly=false; if (friendCount >= getMaxFriends()) { if (!getWelcomeMessage().isEmpty()) { welcomeOnly=true; } else { log("Max friend limit",Level.FINE,getMaxFriends()); return; } } for (int index=0; index < followerIds.length; index++) { boolean found=false; long followerId=followerIds[index]; for ( long friend : friends) { if (followerId == friend) { found=true; break; } } if (!found) { log("Checking new follower",Level.FINE,followerId); boolean isNewFriend=checkFriendship(followerId,welcomeOnly); if (!isNewFriend) { break; } friendCount++; if (friendCount >= getMaxFriends()) { if (!getWelcomeMessage().isEmpty()) { welcomeOnly=true; } else { return; } } count++; if (count >= this.maxFriendsPerCycle) { if (!getWelcomeMessage().isEmpty() && count < this.maxWelcomesPerCycle) { welcomeOnly=true; } else { log("Max friend per cycle limit",Level.FINE,this.maxFriendsPerCycle); return; } } if (!welcomeOnly && getAutoFollowFriendsFriends()) { log("Checking friends friends",Level.FINE,followerId); long[] friendsFriends=getConnection().getFriendsIDs(followerId,-1).getIDs(); for ( long friendsFriend : friendsFriends) { if (checkFriendship(friendsFriend,welcomeOnly)) { friendCount++; if (friendCount >= getMaxFriends()) { log("Max friend limit",Level.FINE,getMaxFriends()); return; } count++; if (count >= this.maxFriendsPerCycle) { log("Max friend per cycle limit",Level.FINE,this.maxFriendsPerCycle); return; } } } } if (!welcomeOnly && getAutoFollowFriendsFollowers()) { log("Checking friends followers",Level.FINE,followerId); long[] friendsFollowers=getConnection().getFollowersIDs(followerId,-1).getIDs(); for ( long friendsFollower : friendsFollowers) { if (checkFriendship(friendsFollower,welcomeOnly)) { friendCount++; if (friendCount >= getMaxFriends()) { log("Max friend limit",Level.FINE,getMaxFriends()); return; } count++; if (count >= this.maxFriendsPerCycle) { log("Max friend per cycle limit",Level.FINE,this.maxFriendsPerCycle); return; } } } } } } checkAutoFollowSearch(friendCount); } catch ( Exception exception) { log(exception); } }
Check followers.
public Range(int lower,int upper){ this.lower=lower; this.upper=upper; }
Constructs a range with a specified lower bound and upper bound.
public RelRoot convertQuery(SqlNode query,final boolean needsValidation,final boolean top){ if (needsValidation) { query=validator.validate(query); } RelMetadataQuery.THREAD_PROVIDERS.set(JaninoRelMetadataProvider.of(cluster.getMetadataProvider())); RelNode result=convertQueryRecursive(query,top,null).rel; if (top) { if (isStream(query)) { result=new LogicalDelta(cluster,result.getTraitSet(),result); } } RelCollation collation=RelCollations.EMPTY; if (!query.isA(SqlKind.DML)) { if (isOrdered(query)) { collation=requiredCollation(result); } } checkConvertedType(query,result); if (SQL2REL_LOGGER.isDebugEnabled()) { SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after converting SqlNode to RelNode",result,false,SqlExplainLevel.EXPPLAN_ATTRIBUTES)); } final RelDataType validatedRowType=validator.getValidatedNodeType(query); return RelRoot.of(result,validatedRowType,query.getKind()).withCollation(collation); }
Converts an unvalidated query's parse tree into a relational expression.
public static void unzip(File zip,String outputFolder){ byte[] buffer=new byte[1024]; try { File folder=new File(outputFolder); if (!folder.exists()) { folder.mkdir(); } ZipInputStream zis=new ZipInputStream(new FileInputStream(zip)); ZipEntry ze=zis.getNextEntry(); while (ze != null) { String fileName=ze.getName(); File newFile=new File(outputFolder + File.separator + fileName); new File(newFile.getParent()).mkdirs(); FileOutputStream fos=new FileOutputStream(newFile); int len; while ((len=zis.read(buffer)) > 0) { fos.write(buffer,0,len); } fos.close(); ze=zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch ( IOException ex) { ex.printStackTrace(); } }
Unzip it
@ObjectiveCName("probablyEndCall") public void probablyEndCall(){ if (modules.getCallsModule() != null) { modules.getCallsModule().probablyEndCall(); } }
Call this method when user is pobabbly want to end call. For example when power button was pressed on iOS device
public int tableLength(){ return ByteArray.readU16bit(get(),0); }
Returns <code>number_of_classes</code>.
public BaseDateTime(int year,int monthOfYear,int dayOfMonth,int hourOfDay,int minuteOfHour,int secondOfMinute,int millisOfSecond,DateTimeZone zone){ this(year,monthOfYear,dayOfMonth,hourOfDay,minuteOfHour,secondOfMinute,millisOfSecond,ISOChronology.getInstance(zone)); }
Constructs an instance from datetime field values using <code>ISOChronology</code> in the specified time zone. <p> If the specified time zone is null, the default zone is used.
public void addItemSet(Collection<BinaryItem> itemSet,Map<BinaryItem,FPTreeRoot.Header> headerTable,int incr){ Iterator<BinaryItem> i=itemSet.iterator(); if (i.hasNext()) { BinaryItem first=i.next(); FPTreeNode aChild; if (!m_children.containsKey(first)) { aChild=new FPTreeNode(this,first); m_children.put(first,aChild); if (!headerTable.containsKey(first)) { headerTable.put(first,new FPTreeRoot.Header()); } headerTable.get(first).addToList(aChild); } else { aChild=m_children.get(first); } headerTable.get(first).getProjectedCounts().increaseCount(0,incr); aChild.increaseProjectedCount(0,incr); itemSet.remove(first); aChild.addItemSet(itemSet,headerTable,incr); } }
Insert an item set into the tree at this node. Removes the first item from the supplied item set and makes a recursive call to insert the remaining items.
public void removeVariable(String varId){ variables.remove(varId); discreteCache=null; continuousCache=null; for ( Assignment s : samples) { s.removePair(varId); } }
Removes a particular variable from the sampled assignments
public void println(Object x){ String line; Throwable t; StackTraceElement[] trace; int i; if (x instanceof Throwable) { t=(Throwable)x; trace=t.getStackTrace(); line=t.toString() + "\n"; for (i=0; i < trace.length; i++) line+="\t" + trace[i].toString() + "\n"; x=line; } printHeader(); for (i=0; i < size(); i++) ((PrintStream)m_Streams.get(i)).println(x); flush(); }
prints the given object to the streams (for Throwables we print the stack trace).
public static Map<Integer,String> generateMapOfValueNameInteger(Class<?> clazz){ Map<Integer,String> valuesName=new HashMap<>(); try { for ( Field field : clazz.getFields()) { valuesName.put((Integer)field.get(int.class),field.getName()); } } catch ( IllegalAccessException e) { e.printStackTrace(); } return valuesName; }
Used to generate map of class fields where key is field value and value is field name.
public static void closeQuietly(Closeable closeable){ if (closeable != null) { try { closeable.close(); } catch ( RuntimeException rethrown) { throw rethrown; } catch ( Exception ignored) { } } }
Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
public GridStripedLock(int concurrencyLevel){ locks=new Lock[concurrencyLevel]; for (int i=0; i < concurrencyLevel; i++) locks[i]=new ReentrantLock(); }
Creates new instance with the given concurrency level (number of locks).
public Quaternionf add(float x,float y,float z,float w){ return add(x,y,z,w,this); }
Add the quaternion <tt>(x, y, z, w)</tt> to this quaternion.
private void ensureLastUsedServerInList(URI serverURI){ if (serverURI == null) { serverURI=UIConnectionPersistence.getInstance().getLastUsedServerURI(); } final ServerList serversList=ServerListManagerFactory.getServerListProvider(DefaultPersistenceStoreProvider.INSTANCE).getServerList(); if (!serversList.contains(serverURI)) { final ServerListConfigurationEntry configEntry=new ServerListConfigurationEntry(serverURI.getHost(),ServerListEntryType.TEAM_PROJECT_COLLECTION,serverURI); serversList.add(configEntry); ServerListManagerFactory.getServerListProvider(DefaultPersistenceStoreProvider.INSTANCE).setServerList(serversList); } }
adds the currently connected server to the server list used in populating the dialog in case it is not there
private static final String toXml(Filter filter){ StringBuilder sb=new StringBuilder(); sb.append("<Filter xsi:type=\""); if (filter == Filter.DEFAULT_FILTER) { sb.append("DefaultFilter\" />"); } else if (filter instanceof CategoryFilter) { sb.append("CategoryFilter\">"); CategoryFilter cf=(CategoryFilter)filter; sb.append("<PartOfGroups>"); sb.append(XmlGenerator.toXml((int)cf.getCategory())); sb.append("</PartOfGroups>"); sb.append("<CollideWithGroups>"); sb.append(XmlGenerator.toXml((int)cf.getMask())); sb.append("</CollideWithGroups>"); sb.append("</Filter>"); } else { throw new UnsupportedOperationException(MessageFormat.format(Messages.getString("exception.persist.unknownClass"),filter.getClass().getName())); } return sb.toString(); }
Returns the xml for the given filter object.
public final void rewind(){ finishWriting(); this.size=0; if (this.chunks != null) { for ( ByteBuffer bb : this.chunks) { bb.rewind(); size+=bb.remaining(); } } this.buffer.rewind(); size+=this.buffer.remaining(); }
Prepare the contents for sending again
synchronized protected void timeout(){ if (progState != NOTPROGRAMMING) { if (log.isDebugEnabled()) { log.debug("timeout!"); } progState=NOTPROGRAMMING; controller().sendSprogMessage(SprogMessage.getExitProgMode(),this); notifyProgListenerEnd(_val,jmri.ProgListener.FailedTimeout); } }
Internal routine to handle a timeout
public ActionTargetOnline(String targetAttribute,boolean tellAboutPostman){ this.targetAttribute=targetAttribute; this.tellAboutPostman=tellAboutPostman; }
creates a new ActionTargetOnline
public ConstantValue(){ }
Create a null object. Normally only used for tests and to pre-load classes.
public static Method declineCounter(){ return create(DECLINECOUNTER); }
Constructs a METHOD property whose value is "DECLINECOUNTER".
protected void drawGridBackground(Canvas c){ if (mDrawGridBackground) { c.drawRect(mViewPortHandler.getContentRect(),mGridBackgroundPaint); } if (mDrawBorders) { c.drawRect(mViewPortHandler.getContentRect(),mBorderPaint); } }
draws the grid background
@BeforeClass public static void deleteIndicationsFile(){ boolean wasException=false; try { StringBuffer fileNameBuff=new StringBuffer(System.getProperty(FileCimIndicationConsumer.WORKING_DIR_SYSTEM_VARIABLE)); fileNameBuff.append(File.separator); fileNameBuff.append(FileCimIndicationConsumer.INDICATIONS_FILE_NAME); File outFile=new File(fileNameBuff.toString()); if (outFile.exists()) { Assert.assertTrue(outFile.delete()); Assert.assertFalse(outFile.exists()); } } catch ( Exception e) { wasException=true; } finally { Assert.assertFalse(wasException); } }
Make sure indication file doesn't exist.
public boolean parsePriority(String source) throws CSSException, IOException { return parser.parsePriority(new InputSource(new StringReader(source))); }
Parse a CSS priority value (e&#x2e;g&#x2e; "&#x21;important").
public void addStandaloneRule(){ int start=numStates; int end=numStates + 1; for (int c=0; c < classes.getNumClasses(); c++) addTransition(start,c,end); for (int i=0; i < numLexStates * 2; i++) addEpsilonTransition(i,start); action[end]=new Action("System.out.print(yytext());",Integer.MAX_VALUE); isFinal[end]=true; }
Add a standalone rule that has minimum priority, fires a transition on all single input characters and has a "print yytext" action.
protected void removeContenidoExecuteLogic(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception { String path=""; logger.info("Inicio de removeContenidoExecuteLogic"); String id=request.getParameter(Constants.ID); if (logger.isInfoEnabled()) logger.info("Id Clasificador: " + id); String idObjeto=request.getParameter("idObjeto"); if (logger.isInfoEnabled()) logger.info("Id Objeto: " + idObjeto); int tipoObjeto=TypeConverter.toInt(request.getParameter("tipoObjeto"),TipoObjeto.DESCRIPTOR); if (logger.isInfoEnabled()) logger.info("Tipo Objeto: " + tipoObjeto); DocumentosTreeView treeView=(DocumentosTreeView)getFromTemporalSession(request,DocumentosConstants.DOCUMENT_TREE_KEY); TreeNode parentNode=treeView.getSelectedNode(); try { DataClfDocYRepEcm dataClfDocYRepEcm=null; String[] listaIdClasificadores=request.getParameterValues("eliminarClasificador"); boolean eliminarClasificador=listaIdClasificadores != null && listaIdClasificadores.length > 0; String[] listaIdDocumentos=request.getParameterValues("eliminarDocumento"); GestionDocumentosElectronicosBI docElecBI=getGestionDocumentosElectronicosBI(request); int motivoRepEcmExcepcion=0; if (tipoObjeto == TipoObjeto.DESCRIPTOR) { motivoRepEcmExcepcion=DocElectronicosException.XNO_SE_PUEDE_ELIMINAR_DOCUMENTO_XFALTA_REPOSITORIO_ECM_DESCRIPTOR; dataClfDocYRepEcm=docElecBI.getIdFichaClfDocYRepEcmDescriptor(idObjeto); } else { motivoRepEcmExcepcion=DocElectronicosException.XNO_SE_PUEDE_ELIMINAR_DOCUMENTO_XFALTA_REPOSITORIO_ECM_ELEMENTO_CUADRO; dataClfDocYRepEcm=docElecBI.getIdFichaClfDocYRepEcmElementoCF(idObjeto); } if (eliminarClasificador) { int i=0; while (i < listaIdClasificadores.length) { if (docElecBI.tieneDescendientes(tipoObjeto,idObjeto,listaIdClasificadores[i])) throw new DocElectronicosException(DocElectronicosException.XNO_SE_PUEDE_ELIMINAR_CLASIFICADOR_XTIENE_DESCENDIENTES); TreeNode node=null; if (parentNode != null) node=treeView.getNode(parentNode.getNodePath() + "/item" + listaIdClasificadores[i]); else node=treeView.getNode("item" + listaIdClasificadores[i]); treeView.removeNode(node); i++; } } else { int i=0; while (i < listaIdDocumentos.length) { DocDocumentoVO documentoVO=docElecBI.getDocumento(tipoObjeto,idObjeto,listaIdDocumentos[i]); if (documentoVO != null && StringUtils.isEmpty(documentoVO.getIdExtDeposito())) { if (StringUtils.isEmpty(dataClfDocYRepEcm.getIdRepEcm())) throw new DocElectronicosException(motivoRepEcmExcepcion); } i++; } } getGestionDocumentosElectronicosBI(request).removeContenidoClasificador(tipoObjeto,idObjeto,request.getParameterValues("eliminarClasificador"),request.getParameterValues("eliminarDocumento")); updateRelacionRechazada(request); if (parentNode != null) path=parentNode.getNodePath(); setReturnActionFordward(request,redirectForwardMethod(request,"/clasificador","method","retrieve" + (id != null ? "&id=" + id : "") + (idObjeto != null ? "&idObjeto=" + idObjeto : "")+ "&tipoObjeto="+ tipoObjeto+ "&node="+ path+ "&refresh=1")); } catch ( DocElectronicosException e) { guardarError(request,e); setReturnActionFordward(request,redirectForwardMethod(request,"/clasificador","method","retrieve" + (id != null ? "&id=" + id : "") + (idObjeto != null ? "&idObjeto=" + idObjeto : "")+ "&tipoObjeto="+ tipoObjeto+ "&node="+ path+ "&refresh=1")); } }
Elimina el contenido seleccionado del clasificador.
public List<UserStat> findByCoins(long minCoins,long maxCoins){ List<User> allUsers=userService.findAll(); int userListSize=allUsers.size(); List<UserStat> result=new ArrayList<>(userListSize); for ( User user : allUsers) { long coins=coinService.totalCoinsMinedBy(user); if (coins >= minCoins && (maxCoins < 0 || coins <= maxCoins)) { result.add(new UserStat(user,-1d,coins)); } } return result; }
Find users according to their number of coins found.
public static void doSetup(){ new UnicodeStandaloneSetup().createInjectorAndDoEMFRegistration(); }
Perform the setup and register at global EMF singletons.
public static void requestTimeoutMS(Intent intentToHost,int timeoutMS){ if (timeoutMS < 0) Log.w(TAG,"requestTimeoutMS: ignoring negative timeout (" + timeoutMS + ")"); else { if ((timeoutMS > REQUESTED_TIMEOUT_MS_MAX) && (timeoutMS != REQUESTED_TIMEOUT_MS_NEVER)) { Log.w(TAG,"requestTimeoutMS: requested timeout " + timeoutMS + " exceeds maximum, setting to max ("+ REQUESTED_TIMEOUT_MS_MAX+ ")"); timeoutMS=REQUESTED_TIMEOUT_MS_MAX; } intentToHost.putExtra(EXTRA_REQUESTED_TIMEOUT,timeoutMS); } }
Request the host to wait the specified number of milliseconds before continuing. Note that the host may choose to ignore the request. Maximum value is REQUESTED_TIMEOUT_MS_MAX. Also available are REQUESTED_TIMEOUT_MS_NONE (continue immediately without waiting for the plugin to finish) and REQUESTED_TIMEOUT_MS_NEVER (wait forever for a result). Used in EditActivity, before setResult().
protected void drawFilledCheckboxes(DrawContext dc,Iterable<NodeLayout> nodes){ Dimension selectedSymbolSize=this.getSelectedSymbolSize(); TreeAttributes attributes=this.getActiveAttributes(); GL2 gl=dc.getGL().getGL2(); Color[] colors=attributes.getCheckBoxColor(); try { gl.glLineWidth(1f); gl.glPolygonMode(GL2.GL_FRONT,GL2.GL_FILL); gl.glBegin(GL2.GL_QUADS); for ( NodeLayout layout : nodes) { int vertAdjust=layout.bounds.height - selectedSymbolSize.height - (this.lineHeight - selectedSymbolSize.height) / 2; int x=layout.drawPoint.x; int y=layout.drawPoint.y + vertAdjust; String selected=layout.node.isTreeSelected(); boolean filled=TreeNode.PARTIALLY_SELECTED.equals(selected); if (filled) { OGLUtil.applyColor(gl,colors[0],1,false); gl.glVertex2f(x + selectedSymbolSize.width,y + selectedSymbolSize.height); gl.glVertex2f(x,y + selectedSymbolSize.height); gl.glVertex2f(x,y); OGLUtil.applyColor(gl,colors[1],1,false); gl.glVertex2f(x + selectedSymbolSize.width,y); } } } finally { gl.glEnd(); } }
Draw squares filled with a gradient for partially selected checkboxes.
@Override public void mouseExited(MouseEvent e){ }
This method cannot be called directly.
public static char toCharValue(String str) throws PageException { if (str.length() > 0) return str.charAt(0); throw new ExpressionException("can't cast empty string to a char"); }
cast a Object to a char value (primitive value type)
private boolean findAndRemove(Object e){ if (e != null) { for (Node pred=null, p=head; p != null; ) { Object item=p.item; if (p.isData) { if (item != null && item != p && e.equals(item) && p.tryMatchData()) { unsplice(pred,p); return true; } } else if (item == null) break; pred=p; if ((p=p.next) == pred) { pred=null; p=head; } } } return false; }
Main implementation of remove(Object)
public WFG2(int k,int l,int M){ super(k,l,M); }
Constructs a WFG2 problem instance with the specified number of position-related and distance-related variables and the specified number of objectives.
public final static byte[] extractChallengeFromType2Message(byte[] msg){ byte[] challenge=new byte[8]; System.arraycopy(msg,24,challenge,0,8); return challenge; }
Extracts the NTLM challenge from the type 2 message as an 8 byte array.
@Override protected void initViews(Bundle savedInstanceState){ }
Initialize the view in the layout
protected Border createRolloverBorder(){ Object border=UIManager.get("ToolBar.rolloverBorder"); if (border != null) { return (Border)border; } UIDefaults table=UIManager.getLookAndFeelDefaults(); return new CompoundBorder(new BasicBorders.RolloverButtonBorder(table.getColor("controlShadow"),table.getColor("controlDkShadow"),table.getColor("controlHighlight"),table.getColor("controlLtHighlight")),new BasicBorders.RolloverMarginBorder()); }
Creates a rollover border for toolbar components. The rollover border will be installed if rollover borders are enabled. <p> Override this method to provide an alternate rollover border.
public static void close(boolean keepAlive){ PoolManagerImpl.getPMI().close(keepAlive); }
Unconditionally destroys all created pools that are in this manager.
public DOMNodeIterator(AbstractDocument doc,Node n,int what,NodeFilter nf,boolean exp){ document=doc; root=n; whatToShow=what; filter=nf; expandEntityReferences=exp; referenceNode=root; }
Creates a new NodeIterator object.
public static <E>ImmutableList<E> of(E e1,E e2,E e3,E e4,E e5){ return construct(e1,e2,e3,e4,e5); }
Returns an immutable list containing the given elements, in order.
private void initializeDefault(){ McElieceKeyGenerationParameters mcParams=new McElieceKeyGenerationParameters(new SecureRandom(),new McElieceParameters()); initialize(mcParams); }
Default initialization of the key pair generator.
public BermudanExercise(final Date[] dates,final boolean payoffAtExpiry){ super(Exercise.Type.Bermudan,payoffAtExpiry); QL.require(dates != null && dates.length > 0,"empty exercise dates"); if (dates.length == 1) { super.type=Exercise.Type.European; super.payoffAtExpiry=false; } for ( final Date date : dates) { super.dates.add(date); } Arrays.sort(dates); }
Constructs a BermudanExercise with a list of exercise dates and the default payoff
public static void computeSingleComponentStatus(ComponentStatus componentStatus){ Map<StatusType,Long> stats=componentStatus.getInstances().stream().filter(null).collect(Collectors.groupingBy(null,Collectors.counting())); componentStatus.setStats(stats.entrySet().stream().collect(Collectors.toMap(null,null))); componentStatus.setStatus(getSingleComponentStatus(stats.keySet())); }
This method is used by StatusFeClient to compute status of an component using status of all the instances.
public static void assertJQ(String request,String... tests) throws Exception { assertJQ(request,JSONTestUtil.DEFAULT_DELTA,tests); }
Validates a query matches some JSON test expressions using the default double delta tolerance.
public MovieTreeNode(Object userObject){ super(userObject); }
Instantiates a new movie tree node.
public ColumnItem(final ColumnBrowserWidget widget,final int index){ if (widget == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (widget.isDisposed()) { SWT.error(SWT.ERROR_WIDGET_DISPOSED); } this.widget=widget; this.parent=null; this.children=new ArrayList<ColumnItem>(); widget.getRootItem().children.add(index,this); widget.updateContent(); }
Constructs a new instance of this class given its parent. The item is added at a given position in the items'list maintained by its parent.
public String canopyMinimumCanopyDensityTipText(){ return "If using canopy clustering for initialization and/or speedup " + "this is the minimum T2-based density " + "below which a canopy will be pruned during periodic pruning"; }
Returns the tip text for this property.
public static <T>T eachWithIndex(T self,Closure closure){ final Object[] args=new Object[2]; int counter=0; for (Iterator iter=InvokerHelper.asIterator(self); iter.hasNext(); ) { args[0]=iter.next(); args[1]=counter++; closure.call(args); } return self; }
Iterates through an aggregate type or data structure, passing each item and the item's index (a counter starting at zero) to the given closure.
SortableProperty(ConnectionRecordSet.SortableProperty recordProperty){ this.recordProperty=recordProperty; }
Creates a new SortableProperty which associates the property name string (identical to its own name) with the given ConnectionRecordSet.SortableProperty value.
private void notifyNewTabCreated(Tab tab){ for ( TabModelSelectorObserver listener : mObservers) { listener.onNewTabCreated(tab); } }
Notifies all the listeners that a new tab has been created.
public int numDecodingsB(String s){ if (s == null || s.length() == 0) { return 0; } int len=s.length(); int prev1=1; int prev2=s.charAt(0) == '0' ? 0 : 1; for (int i=2; i <= len; i++) { int code1=Integer.valueOf(s.substring(i - 1,i)); int code2=Integer.valueOf(s.substring(i - 2,i)); int temp=prev2; prev2=(code1 != 0 ? prev2 : 0) + (code2 <= 26 && code2 > 9 ? prev1 : 0); prev1=temp; } return prev2; }
DP. O(n) Time, O(1) Space. Don't need an array since we only need previous two results. Remember to update those results.
public boolean isUseful(Result current,LinkedList<Result> otherResults,int criterion,ExampleSet exampleSet,int min_model_number){ boolean result=true; switch (criterion) { case IteratingGSS.TYPE_WORST_UTILITY: double worstUtility=current.getUtility() - current.getConfidence(); if (worstUtility < this.min_utility_useful) { result=false; } else { result=true; } break; case IteratingGSS.TYPE_UTILITY: double utility=current.getUtility(); if (utility < this.min_utility_useful) { result=false; } else { result=true; } break; case IteratingGSS.TYPE_BEST_UTILITY: double bestUtility=current.getUtility() + current.getConfidence(); if (bestUtility < this.min_utility_useful) { result=false; } else { result=true; } break; case IteratingGSS.TYPE_EXAMPLE: if (otherResults.size() == 0 || otherResults.size() < min_model_number) { return true; } double sum=0.0d; Iterator it=otherResults.iterator(); while (it.hasNext()) { Result r=(Result)it.next(); sum=sum + r.getTotalWeight(); } double average=sum / otherResults.size(); if (current.getTotalWeight() < this.exampleFactor * average) { result=true; } else { result=false; } break; } return result; }
Test if the model is useful according to the given criterion.
public boolean isValidTree(){ int nnodes=getNodeCount(); int nedges=getEdgeCount(); if (nnodes != nedges + 1) { s_logger.warning("Node/edge counts incorrect."); return false; } int root=getRootRow(); IntIterator nodes=getNodeTable().rows(); while (nodes.hasNext()) { int n=nodes.nextInt(); int id=getInDegree(n); if (n == root && id > 0) { s_logger.warning("Root node has a parent."); return false; } else if (id > 1) { s_logger.warning("Node " + n + " has multiple parents."); return false; } } int[] counts=new int[]{0,nedges}; isValidHelper(getRootRow(),counts); if (counts[0] > nedges) { s_logger.warning("The tree has non-tree edges in it."); return false; } if (counts[0] < nedges) { s_logger.warning("Not all of the tree was visited. " + "Only " + counts[0] + "/"+ nedges+ " edges encountered"); return false; } return true; }
Check that the underlying graph structure forms a valid tree.
public void applyCurrentUser(){ FacesContext facesContext=getContext(); HttpSession session=(HttpSession)facesContext.getExternalContext().getSession(false); String userId="" + session.getAttribute("loggedInUserId"); String password="" + session.getAttribute("loggedInUserPassword"); String userKey="" + session.getAttribute("loggedInUserKey"); getConfigurationItem(ControllerConfigurationKey.BSS_USER_ID.name()).setValue(userId); getConfigurationItem(ControllerConfigurationKey.BSS_USER_PWD.name()).setValue(password); getConfigurationItem(ControllerConfigurationKey.BSS_USER_KEY.name()).setValue(userKey); }
Stores the currently logged-in user as administrator
@Override public boolean mutate(TestCase test,TestFactory factory){ if (Randomness.nextDouble() >= Properties.P_CHANGE_PARAMETER) return false; if (!isStatic()) { VariableReference source=getSource(); List<VariableReference> objects=test.getObjects(source.getType(),getPosition()); objects.remove(source); if (!objects.isEmpty()) { setSource(Randomness.choice(objects)); return true; } } return false; }
Try to replace source of field with all possible choices
public SVGFeTurbulenceElementBridge(){ }
Constructs a new bridge for the &lt;feTurbulence> element.
public static void verifyDatastore(Datastore datastore,VCenterAPI vCenterApi) throws Exception { DatastoreSummary summary=datastore.getSummary(); if (summary == null) { throw new Exception("Summary unavailable for datastore " + datastore.getName()); } if (!summary.isAccessible()) { throw new Exception("Datastore " + datastore.getName() + " is not accessible"); } checkMaintenanceMode(datastore,summary); checkVirtualMachines(datastore); }
Verify that datastore can be unmounted
public List<ShardRouting> allShards(){ List<ShardRouting> shards=new ArrayList<>(); String[] indices=indicesRouting.keySet().toArray(new String[indicesRouting.keySet().size()]); for ( String index : indices) { List<ShardRouting> allShardsIndex=allShards(index); shards.addAll(allShardsIndex); } return shards; }
All the shards (replicas) for all indices in this routing table.
public static void validateNonNegativeNumber(long fieldValue,String fieldName){ if (fieldValue < 0) { logAndThrow(String.format("%s should be a non-negative number: %d",fieldName,fieldValue)); } }
Validate the the given value is a non-negative number.
public boolean isIncludeNullsUserElement2(){ Object oo=get_Value(COLUMNNAME_IsIncludeNullsUserElement2); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
Get Include Nulls in User Element 2.
public Topic(final Queue<T> q){ distributor.addQueue(q); }
Construct a Topic using the Queue provided
protected static void postProcessDeepFreeze(IHex[] hexSet,int modifier){ int n; IHex field; ITerrainFactory f=Terrains.getTerrainFactory(); for (n=0; n < hexSet.length; n++) { field=hexSet[n]; if (field.containsTerrain(Terrains.WATER)) { int level=field.terrainLevel(Terrains.WATER); if (modifier != 0) { level-=modifier; field.removeTerrain(Terrains.WATER); if (level > 0) { field.addTerrain(f.createTerrain(Terrains.WATER,level)); } } field.addTerrain(f.createTerrain(Terrains.ICE,1)); } else if (field.containsTerrain(Terrains.SWAMP)) { field.removeTerrain(Terrains.SWAMP); if (field.terrainsPresent() == 0) { if (Compute.randomInt(100) < 30) { field.addTerrain(f.createTerrain(Terrains.ROUGH,1)); } else { field.addTerrain(f.createTerrain(Terrains.ICE,1)); } } } } }
Converts water hexes to ice hexes. Works best with snow&ice theme.
public static Bitmap imageWithTextNoLayout(Context context,Bitmap bitmap,GenerateParams params){ Paint paint=new Paint(); paint.setColor(params.color); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(applyDimension(COMPLEX_UNIT_SP,20,context.getResources().getDisplayMetrics())); paint.setTypeface(Typeface.DEFAULT_BOLD); Canvas canvas=new Canvas(bitmap); canvas.drawColor(params.background); canvas.drawText(params.text,canvas.getWidth() / 2,canvas.getHeight() / 2,paint); return bitmap; }
Generate centered text without creating a View, more lightweight. Consider http://stackoverflow.com/a/8369690/253468 for multiline support.
static Instruction instanceOfNotNull(Instruction s,IR ir){ RegisterOperand result=InstanceOf.getClearResult(s); TypeReference LHStype=InstanceOf.getType(s).getTypeRef(); Operand ref=InstanceOf.getClearRef(s); Operand guard=InstanceOf.getClearGuard(s); Instruction next=s.nextInstructionInCodeOrder(); if (next.operator() == INT_IFCMP && IfCmp.getVal1(next) instanceof RegisterOperand && result.similar(IfCmp.getVal1(next))) { Operand val2=IfCmp.getVal2(next); if (VM.VerifyAssertions) { VM._assert(val2.isIntConstant()); } int ival2=((IntConstantOperand)val2).value; ConditionOperand cond=IfCmp.getCond(next); boolean branchCondition=(((ival2 == 0) && (cond.isNOT_EQUAL() || cond.isLESS_EQUAL())) || ((ival2 == 1) && (cond.isEQUAL() || cond.isGREATER_EQUAL()))); BasicBlock branchBB=next.getBranchTarget(); RegisterOperand oldGuard=IfCmp.getGuardResult(next); next.remove(); BasicBlock fallThroughBB=fallThroughBB(s,ir); Operand RHStib=getTIB(s,ir,ref,guard); if (branchCondition) { return generateBranchingTypeCheck(s,ir,ref.copy(),LHStype,RHStib,branchBB,fallThroughBB,oldGuard.copyRO(),IfCmp.getClearBranchProfile(next).flip()); } else { return generateBranchingTypeCheck(s,ir,ref.copy(),LHStype,RHStib,fallThroughBB,branchBB,oldGuard.copyRO(),IfCmp.getClearBranchProfile(next)); } } else { Operand RHStib=getTIB(s,ir,ref,guard); return generateValueProducingTypeCheck(s,ir,ref.copy(),LHStype,RHStib,result); } }
Expand an instanceof instruction into the LIR sequence that implements the dynamic type check. Ref is known to never contain a null ptr at runtime.
private void showErrorOnField(List<RegisterResponseFieldError> errors,@NonNull IRegistrationFieldView fieldView){ if (errors != null && !errors.isEmpty()) { StringBuffer buffer=new StringBuffer(); for ( RegisterResponseFieldError e : errors) { buffer.append(e.getUserMessage() + " "); } fieldView.handleError(buffer.toString()); } }
Displays given errors on the given registration field.
protected boolean afterDelete(boolean success){ updateEntry(); return success; }
After Delete
@Override public Object callableStatement_getObject(FilterChain chain,CallableStatementProxy statement,String parameterName,java.util.Map<String,Class<?>> map) throws SQLException { Object obj=chain.callableStatement_getObject(statement,parameterName,map); if (obj instanceof ResultSetProxy) { resultSetOpenAfter((ResultSetProxy)obj); } return obj; }
Description: <br>
public static byte[] messageRowKey(HBaseId mailboxUid,MessageUid uid){ return Bytes.add(mailboxUid.toBytes(),Bytes.toBytes(Long.MAX_VALUE - uid.asLong())); }
Utility method to build row keys from mailbox UUID and message uid. The message uid's are stored in reverse order by substracting the uid value from Long.MAX_VALUE.
public static void e(String string,Exception exception){ if (sIsLogEnabled) { Log.e(sApplicationTag,getContent(getCurrentStackTraceElement()) + "\n>" + exception.getMessage()+ "\n>"+ exception.getStackTrace()+ " "+ string); exception.printStackTrace(); } }
Send an ERROR log message.
@EventHandler(ignoreCancelled=true,priority=EventPriority.MONITOR) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event){ String[] split=event.getMessage().split(" "); if (split.length > 0) { split[0]=split[0].substring(1); split=WorldEdit.getInstance().getPlatformManager().getCommandManager().commandDetection(split); } final String newMessage="/" + StringUtil.joinString(split," "); if (!newMessage.equals(event.getMessage())) { event.setMessage(newMessage); plugin.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { if (!event.getMessage().isEmpty()) { plugin.getServer().dispatchCommand(event.getPlayer(),event.getMessage().substring(1)); } event.setCancelled(true); } } }
Called when a player attempts to use a command
public ShareRequest(final String requestUrl,final IOneDriveClient client,final List<Option> options){ super(requestUrl,client,options); }
The request for the Share
public boolean deleteJob(JobKey jobKey) throws SchedulerException { validateState(); boolean result=false; List<? extends Trigger> triggers=getTriggersOfJob(jobKey); for ( Trigger trigger : triggers) { if (!unscheduleJob(trigger.getKey())) { StringBuilder sb=new StringBuilder().append("Unable to unschedule trigger [").append(trigger.getKey()).append("] while deleting job [").append(jobKey).append("]"); throw new SchedulerException(sb.toString()); } result=true; } result=resources.getJobStore().removeJob(jobKey) || result; if (result) { notifySchedulerThread(0L); notifySchedulerListenersJobDeleted(jobKey); } return result; }
<p> Delete the identified <code>Job</code> from the Scheduler - and any associated <code>Trigger</code>s. </p>
@DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:47.625 -0500",hash_original_method="BB9DACD07ED93D41347C3772C10021CB",hash_generated_method="DA2DCBE5F00DBE7618C1F279A9CD37FF") public InterruptedIOException(){ }
Constructs a new instance.
public GeoPoint(final double magnitude,final double x,final double y,final double z){ super(x * magnitude,y * magnitude,z * magnitude); this.magnitude=magnitude; }
Construct a GeoPoint from a unit (x,y,z) vector and a magnitude.
public boolean similar(Object other){ if (!(other instanceof JSONArray)) { return false; } int len=this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i=0; i < len; i+=1) { Object valueThis=this.get(i); Object valueOther=((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; }
Determine if two JSONArrays are similar. They must contain similar sequences.
public String toString(){ StringBuffer sb=new StringBuffer(); char[] separator={'[',' '}; int n=rows(); int m=columns(); for (int i=0; i < n; i++) { separator[0]='{'; for (int j=0; j < m; j++) { sb.append(separator); sb.append(components[i][j]); separator[0]=' '; } sb.append('}'); sb.append('\n'); } return sb.toString(); }
Returns a string representation of the system.
public boolean insert(int val){ if (map.containsKey(val)) { return false; } map.put(val,list.size()); list.add(val); return true; }
Inserts a value to the set. Returns true if the set did not already contain the specified element.
protected ImportScopeImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
@AfterClass public static void tearDownAfterClass() throws Exception { }
Method tearDownAfterClass.
private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException { final RippleState state=mState; state.mChangingConfigurations|=TypedArrayCompat.getChangingConfigurations(a); state.mTouchThemeAttrs=TypedArrayCompat.extractThemeAttrs(a); final ColorStateList color=a.getColorStateList(R.styleable.RippleDrawable_android_color); if (color != null) { mState.mColor=color; } mState.mMaxRadius=a.getDimensionPixelSize(R.styleable.RippleDrawable_android_radius,mState.mMaxRadius); verifyRequiredAttributes(a); }
Initializes the constant state from the values in the typed array.
public static CheckIndex.Status checkIndex(Directory dir) throws IOException { return checkIndex(dir,true); }
This runs the CheckIndex tool on the index in. If any issues are hit, a RuntimeException is thrown; else, true is returned.
public int write(OutputStream out) throws IOException { writeId(out,"RIFF"); writeInt(out,36 + mNumBytes); writeId(out,"WAVE"); writeId(out,"fmt "); writeInt(out,16); writeShort(out,mFormat); writeShort(out,mNumChannels); writeInt(out,mSampleRate); writeInt(out,mNumChannels * mSampleRate * mBitsPerSample / 8); writeShort(out,(short)(mNumChannels * mBitsPerSample / 8)); writeShort(out,mBitsPerSample); writeId(out,"data"); writeInt(out,mNumBytes); return HEADER_LENGTH; }
Write a WAVE file header.
public void verifyHeader() throws VerificationException { maybeParseHeader(); checkProofOfWork(true); checkTimestamp(); }
Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically, throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be. This is <b>not</b> everything that is required for a block to be valid, only what is checkable independent of the chain and without a transaction index.
public Builder byDay(DayOfWeek... days){ return byDay(Arrays.asList(days)); }
Adds one or more BYDAY rule parts.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.