code
stringlengths
10
174k
nl
stringlengths
3
129k
public static short[] subarray(final short[] array,int startIndexInclusive,int endIndexExclusive){ if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive=0; } if (endIndexExclusive > array.length) { endIndexExclusive=array.length; } int newSize=endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return ArrayUtils.EMPTY_SHORT_ARRAY; } short[] subarray=new short[newSize]; System.arraycopy(array,startIndexInclusive,subarray,0,newSize); return subarray; }
<p>Produces a new <code>short</code> array containing the elements between the start and end indices.</p> <p>The start index is inclusive, the end index exclusive. Null array input produces null output.</p>
public CSVFormat withRecordSeparator(final char recordSeparator){ return withRecordSeparator(String.valueOf(recordSeparator)); }
Sets the record separator of the format to the specified character.
protected CacheConfiguration dataConfiguration(){ CacheConfiguration cfg=defaultCacheConfiguration(); cfg.setName(DATA_CACHE_NAME); cfg.setCacheMode(PARTITIONED); cfg.setBackups(0); cfg.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(IGFS_GROUP_SIZE)); cfg.setNearConfiguration(null); cfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cfg.setAtomicityMode(TRANSACTIONAL); return cfg; }
Gets data cache configuration.
@Override public StreamImpl openAppendImpl() throws IOException { StreamImpl stream=getWritePath().openAppendImpl(); return stream; }
Opens the best path for appending. XXX: If the best path doesn't exist, this should probably create the file in the first path.
public Blade interceptor(String packageName){ applicationConfig.setInterceptorPackage(packageName); return this; }
Setting the path where the interceptor, e.g:com.bladejava.interceptor
protected void pretendCommit(){ if (fStart > -1) { fText=fDocumentUndoManager.fTextBuffer.toString(); fPreservedText=fDocumentUndoManager.fPreservedTextBuffer.toString(); } }
Updates the text from the buffers without resetting the buffers or adding anything to the stack.
@Override public String toString(){ if (eIsProxy()) return super.toString(); StringBuffer result=new StringBuffer(super.toString()); result.append(" (op: "); result.append(op); result.append(')'); return result.toString(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static SipRequest createSubscribe(SipDialogPath dialog,long expirePeriod) throws PayloadException { try { URI requestURI=SipUtils.ADDR_FACTORY.createURI(dialog.getTarget()); CallIdHeader callIdHeader=SipUtils.HEADER_FACTORY.createCallIdHeader(dialog.getCallId()); CSeqHeader cseqHeader=SipUtils.HEADER_FACTORY.createCSeqHeader(dialog.getCseq(),Request.SUBSCRIBE); Address fromAddress=SipUtils.ADDR_FACTORY.createAddress(dialog.getLocalParty()); FromHeader fromHeader=SipUtils.HEADER_FACTORY.createFromHeader(fromAddress,dialog.getLocalTag()); Address toAddress=SipUtils.ADDR_FACTORY.createAddress(dialog.getRemoteParty()); ToHeader toHeader=SipUtils.HEADER_FACTORY.createToHeader(toAddress,dialog.getRemoteTag()); Request subscribe=SipUtils.MSG_FACTORY.createRequest(requestURI,Request.SUBSCRIBE,callIdHeader,cseqHeader,fromHeader,toHeader,dialog.getSipStack().getViaHeaders(),SipUtils.buildMaxForwardsHeader()); Vector<String> route=dialog.getRoute(); for (int i=0; i < route.size(); i++) { Header routeHeader=SipUtils.HEADER_FACTORY.createHeader(RouteHeader.NAME,route.elementAt(i)); subscribe.addHeader(routeHeader); } ExpiresHeader expHeader=SipUtils.HEADER_FACTORY.createExpiresHeader((int)(expirePeriod / SECONDS_TO_MILLISECONDS_CONVERSION_RATE)); subscribe.addHeader(expHeader); subscribe.addHeader(SipUtils.buildUserAgentHeader()); subscribe.addHeader(dialog.getSipStack().getContact()); SipUtils.buildAllowHeader(subscribe); ViaHeader viaHeader=(ViaHeader)subscribe.getHeader(ViaHeader.NAME); viaHeader.setRPort(); return new SipRequest(subscribe); } catch ( ParseException|InvalidArgumentException e) { throw new PayloadException("Can't create SIP message!",e); } }
Create a SIP SUBSCRIBE request
public static StringBuilder describeParameterizable(StringBuilder buf,Class<?> pcls,int width,String indent){ try { println(buf,width,"Description for class " + pcls.getName(),""); String title=DocumentationUtil.getTitle(pcls); if (title != null && title.length() > 0) { println(buf,width,title,""); } String desc=DocumentationUtil.getDescription(pcls); if (desc != null && desc.length() > 0) { println(buf,width,desc," "); } Reference ref=DocumentationUtil.getReference(pcls); if (ref != null) { if (ref.prefix().length() > 0) { println(buf,width,ref.prefix(),""); } println(buf,width,ref.authors() + ":",""); println(buf,width,ref.title()," "); println(buf,width,"in: " + ref.booktitle(),""); if (ref.url().length() > 0) { println(buf,width,"see also: " + ref.url(),""); } } SerializedParameterization config=new SerializedParameterization(); TrackParameters track=new TrackParameters(config); @SuppressWarnings("unused") Object p=ClassGenericsUtil.tryInstantiate(Object.class,pcls,track); Collection<TrackedParameter> options=track.getAllParameters(); if (!options.isEmpty()) { OptionUtil.formatForConsole(buf,width,indent,options); } return buf; } catch ( Exception e) { LoggingUtil.exception("Error instantiating class to describe.",e.getCause()); buf.append("No description available: ").append(e); return buf; } }
Format a description of a Parameterizable (including recursive options).
public boolean matches(Entry other){ return matches(other.spec); }
Returns whether or not this instance matches the spec in the given instance.
private static ProcessingResult tryToIndentToRight(@NotNull ChangeIndentContext context){ int targetLineIndent=getLineIndent(context,context.targetLine); List<LineInfo> lineInfos=collectIndentsGreaterOrEqualToCurrent(context,context.targetLine); int newIndent=-1; for (int i=lineInfos.size() - 1; i >= 0; i--) { LineInfo lineInfo=lineInfos.get(i); if (lineInfo.indent == targetLineIndent) { continue; } newIndent=lineInfo.indent; break; } if (newIndent == targetLineIndent || newIndent < 0) { return ProcessingResult.CONTINUE; } changeIndent(context,newIndent); return ProcessingResult.STOP_SUCCESSFUL; }
Tries to indent active line to the right.
public MultiClassificationPerformance(int type){ this.type=type; }
Creates a MultiClassificationPerformance with the given type.
protected void restoreState() throws MqttException { final String methodName="restoreState"; Enumeration messageKeys=persistence.keys(); MqttPersistable persistable; String key; int highestMsgId=nextMsgId; Vector orphanedPubRels=new Vector(); log.fine(CLASS_NAME,methodName,"600"); while (messageKeys.hasMoreElements()) { key=(String)messageKeys.nextElement(); persistable=persistence.get(key); MqttWireMessage message=restoreMessage(key,persistable); if (message != null) { if (key.startsWith(PERSISTENCE_RECEIVED_PREFIX)) { log.fine(CLASS_NAME,methodName,"604",new Object[]{key,message}); inboundQoS2.put(new Integer(message.getMessageId()),message); } else if (key.startsWith(PERSISTENCE_SENT_PREFIX)) { MqttPublish sendMessage=(MqttPublish)message; highestMsgId=Math.max(sendMessage.getMessageId(),highestMsgId); if (persistence.containsKey(getSendConfirmPersistenceKey(sendMessage))) { MqttPersistable persistedConfirm=persistence.get(getSendConfirmPersistenceKey(sendMessage)); MqttPubRel confirmMessage=(MqttPubRel)restoreMessage(key,persistedConfirm); if (confirmMessage != null) { log.fine(CLASS_NAME,methodName,"605",new Object[]{key,message}); outboundQoS2.put(new Integer(confirmMessage.getMessageId()),confirmMessage); } else { log.fine(CLASS_NAME,methodName,"606",new Object[]{key,message}); } } else { sendMessage.setDuplicate(true); if (sendMessage.getMessage().getQos() == 2) { log.fine(CLASS_NAME,methodName,"607",new Object[]{key,message}); outboundQoS2.put(new Integer(sendMessage.getMessageId()),sendMessage); } else { log.fine(CLASS_NAME,methodName,"608",new Object[]{key,message}); outboundQoS1.put(new Integer(sendMessage.getMessageId()),sendMessage); } } MqttDeliveryToken tok=tokenStore.restoreToken(sendMessage); tok.internalTok.setClient(clientComms.getClient()); inUseMsgIds.put(new Integer(sendMessage.getMessageId()),new Integer(sendMessage.getMessageId())); } else if (key.startsWith(PERSISTENCE_SENT_BUFFERED_PREFIX)) { MqttPublish sendMessage=(MqttPublish)message; highestMsgId=Math.max(sendMessage.getMessageId(),highestMsgId); if (sendMessage.getMessage().getQos() == 2) { log.fine(CLASS_NAME,methodName,"607",new Object[]{key,message}); outboundQoS2.put(new Integer(sendMessage.getMessageId()),sendMessage); } else if (sendMessage.getMessage().getQos() == 1) { log.fine(CLASS_NAME,methodName,"608",new Object[]{key,message}); outboundQoS1.put(new Integer(sendMessage.getMessageId()),sendMessage); } else { log.fine(CLASS_NAME,methodName,"511",new Object[]{key,message}); outboundQoS0.put(new Integer(sendMessage.getMessageId()),sendMessage); persistence.remove(key); } MqttDeliveryToken tok=tokenStore.restoreToken(sendMessage); tok.internalTok.setClient(clientComms.getClient()); inUseMsgIds.put(new Integer(sendMessage.getMessageId()),new Integer(sendMessage.getMessageId())); } else if (key.startsWith(PERSISTENCE_CONFIRMED_PREFIX)) { MqttPubRel pubRelMessage=(MqttPubRel)message; if (!persistence.containsKey(getSendPersistenceKey(pubRelMessage))) { orphanedPubRels.addElement(key); } } } } messageKeys=orphanedPubRels.elements(); while (messageKeys.hasMoreElements()) { key=(String)messageKeys.nextElement(); log.fine(CLASS_NAME,methodName,"609",new Object[]{key}); persistence.remove(key); } nextMsgId=highestMsgId; }
Restores the state information from persistence.
public List registerInterestList(List keys,InterestResultPolicy policy,boolean isDurable,boolean receiveUpdatesAsInvalidates,final byte regionDataPolicy){ final RegisterInterestTracker rit=this.pool.getRITracker(); List result=null; boolean finished=false; try { rit.addInterestList(this.region,keys,policy,isDurable,receiveUpdatesAsInvalidates); result=RegisterInterestListOp.execute(this.pool,this.regionName,keys,policy,isDurable,receiveUpdatesAsInvalidates,regionDataPolicy); finished=true; if (PoolImpl.AFTER_REGISTER_CALLBACK_FLAG) { ClientServerObserver bo=ClientServerObserverHolder.getInstance(); bo.afterInterestRegistration(); } return result; } finally { if (!finished) { rit.removeInterestList(this.region,keys,isDurable,receiveUpdatesAsInvalidates); } } }
Does a region registerInterestList on a server
public static String toString(boolean value){ return String.valueOf(value); }
Converts the specified boolean to its string representation.
public RasterPlotComponent(final String name){ super(name); model=new RasterModel(); initializeAttributes(); addListener(); model.defaultInit(); }
Create new raster plot component.
public void declareExtensions(ExtensionProfile extProfile){ extProfile.declare(CodeSearchEntry.class,File.getDefaultDescription()); extProfile.declare(CodeSearchEntry.class,Package.getDefaultDescription()); extProfile.declare(CodeSearchEntry.class,Match.getDefaultDescription()); }
Initializes an ExtensionProfile based upon the extensions expected by a CodeSearchEntry.
public static int calcTextWidth(Paint paint,String demoText){ return (int)paint.measureText(demoText); }
calculates the approximate width of a text, depending on a demo text avoid repeated calls (e.g. inside drawing methods)
public SecretKey engineLookupAndResolveSecretKey(Element element,String baseURI,StorageResolver storage) throws KeyResolverException { KeyResolverSpi tmp=cloneIfNeeded(); if (!tmp.engineCanResolve(element,baseURI,storage)) { return null; } return tmp.engineResolveSecretKey(element,baseURI,storage); }
Method engineLookupAndResolveSecretKey
private Organization createOrganization(String organizationId) throws NonUniqueBusinessKeyException { Organization org=new Organization(); org.setOrganizationId(organizationId); org.setName("The supplier organization"); org.setAddress("my address is a very long string, which is stored in the database \n with line delimiters\n."); org.setEmail("organization@organization.com"); org.setPhone("012345/678"); org.setLocale(Locale.ENGLISH.toString()); org.setCutOffDay(1); mgr.persist(org); return org; }
create and persist organization
public static ConfigurationJMX newInstance(){ return new ConfigurationJMX(); }
Obtiene una instancia del MBean.
public float dot(float x,float y,float z){ return this.x * x + this.y * y + this.z * z; }
Returns the dot product between this and the given vector.
public void mark(){ mark(1); }
Mark the occurrence of an event.
public TFloatDoubleHashMapDecorator(TFloatDoubleHashMap map){ super(); this._map=map; }
Creates a wrapper that decorates the specified primitive map.
public TermsBuilder valueType(Terms.ValueType valueType){ this.valueType=valueType; return this; }
When using scripts, the value type indicates the types of the values the script is generating.
public boolean isDirty(){ return this.dirty; }
Returns whether the data is dirty
public static Object[] polar2CartesianArray(Double r,Double alpha){ double x=r.doubleValue() * Math.cos(alpha.doubleValue()); double y=r.doubleValue() * Math.sin(alpha.doubleValue()); return new Object[]{new Double(x),new Double(y)}; }
Convert polar coordinates to cartesian coordinates. The function may be called twice, once to retrieve the result columns (with null parameters), and the second time to return the data.
public IndentingWriter(Writer out,int indentStep){ this(out,indentStep,8); }
Creates a new IndentingWriter that writes indented text to the given Writer and uses the supplied indent step.
public void addDataSource(){ Integer currentSize=dataset.getSeriesCount(); dataset.addSeries(new XYSeries(currentSize + 1)); this.fireDataSourceAdded(currentSize); }
Adds a data source to the chart.
public static XMLTreeLocation afterAnyOf(String... names){ if (names.length == 0) { throw new IllegalArgumentException("Required not empty elements names"); } return disjunctionChain(LocationType.AFTER,names); }
Indicates position after any of elements with given names
public KernelGaussian(double sigma){ if (sigma <= 0) throw new IllegalArgumentException("Sigma must be > 0"); this.sigma=sigma; }
Creates a new Gaussian kernel with the given bandwidth
public int mergeTable(String TableName,String ColumnName,int from_ID,int to_ID){ log.fine(TableName + "." + ColumnName+ " - From="+ from_ID+ ",To="+ to_ID); String sql="UPDATE " + TableName + " SET "+ ColumnName+ "="+ to_ID+ " WHERE "+ ColumnName+ "="+ from_ID; boolean delete=false; for (int i=0; i < m_deleteTables.length; i++) { if (m_deleteTables[i].equals(TableName)) { delete=true; sql="DELETE " + TableName + " WHERE "+ ColumnName+ "="+ from_ID; } } if (delete && X_M_Cost.Table_Name.equals(TableName) && M_PRODUCT_ID.equals(ColumnName)) { sql+=" AND " + X_M_Cost.COLUMNNAME_CurrentCostPrice + "=0"+ " AND "+ X_M_Cost.COLUMNNAME_CurrentQty+ "=0"+ " AND "+ X_M_Cost.COLUMNNAME_CumulatedAmt+ "=0"+ " AND "+ X_M_Cost.COLUMNNAME_CumulatedQty+ "=0"; } int count=DB.executeUpdate(sql,m_trx.getTrxName()); if (count < 0) { count=-1; m_errorLog.append(Env.NL).append(delete ? "DELETE " : "UPDATE ").append(TableName).append(" - ").append(" - ").append(sql); log.config(m_errorLog.toString()); m_trx.rollback(); } log.fine(count + (delete ? " -Delete- " : " -Update- ") + TableName); return count; }
Merge Table
private CodeSwitchLanguageModel reestimateLM(int[] languageCounts,CodeSwitchLanguageModel lm){ long nanoTime=System.nanoTime(); List<Tuple2<SingleLanguageModel,Double>> newSubModelsAndPriors=new ArrayList<Tuple2<SingleLanguageModel,Double>>(); double languageCountSum=0; for (int language=0; language < languageCounts.length; ++language) { double newPrior=languageCounts[language]; newSubModelsAndPriors.add(Tuple2(lm.get(language),newPrior)); languageCountSum+=newPrior; } CodeSwitchLanguageModel newLM=new BasicCodeSwitchLanguageModel(newSubModelsAndPriors,lm.getCharacterIndexer(),lm.getLanguageIndexer(),lm.getProbKeepSameLanguage(),lm.getMaxOrder()); StringBuilder sb=new StringBuilder("Updating language probabilities: "); for (int language=0; language < languageCounts.length; ++language) sb.append(lm.getLanguageIndexer().getObject(language)).append("->").append(languageCounts[language] / languageCountSum).append(" "); System.out.println(sb); System.out.println("New LM: " + (System.nanoTime() - nanoTime) / 1000000 + "ms"); return newLM; }
Hard-EM update on language model probabilities
public boolean removeThirdPartyIDPUser(String tenantName,PrincipalId userId) throws Exception { return getService().removeThirdPartyIDPUser(tenantName,userId,this.getServiceContext()); }
Remove a external IDP user registration in the system provider of the tenant
private ITuple processOneInputTuple(ITuple inputTuple) throws DataFlowException { if (inputTuple == null) { return null; } List<Span> matchingResults=new ArrayList<>(); for ( Attribute attribute : attributeList) { String fieldName=attribute.getFieldName(); FieldType fieldType=attribute.getFieldType(); String fieldValue=inputTuple.getField(fieldName).getValue().toString(); if (fieldType != FieldType.STRING && fieldType != FieldType.TEXT) { throw new DataFlowException("KeywordMatcher: Fields other than STRING and TEXT are not supported yet"); } switch (regexEngine) { case JavaRegex: matchingResults.addAll(javaRegexMatch(fieldValue,fieldName)); break; case RE2J: matchingResults.addAll(re2jRegexMatch(fieldValue,fieldName)); break; } } if (matchingResults.isEmpty()) { return null; } List<Span> spanList=(List<Span>)inputTuple.getField(SchemaConstants.SPAN_LIST).getValue(); spanList.addAll(matchingResults); return inputTuple; }
This function returns a list of spans in the given tuple that match the regex For example, given tuple ("george watson", "graduate student", 23, "(949)888-8888") and regex "g[^\s]*", this function will return [Span(name, 0, 6, "g[^\s]*", "george watson"), Span(position, 0, 8, "g[^\s]*", "graduate student")]
public ReasonFlags(DerValue derVal) throws IOException { this.bitString=derVal.getUnalignedBitString(true).toBooleanArray(); }
Create the object from the passed DER encoded value.
public void clear(){ oredCriteria.clear(); orderByClause=null; distinct=false; }
This method was generated by MyBatis Generator. This method corresponds to the database table dependency
public void removeAll(Collection<? extends Figure> figures){ willChange(); for ( Figure f : new LinkedList<Figure>(figures)) { remove(f); } changed(); }
Removes all specified children.
public void onFailure(int statusCode,Header[] headers,Throwable throwable,JSONObject errorResponse){ Log.w(LOG_TAG,"onFailure(int, Header[], Throwable, JSONObject) was not overriden, but callback was received",throwable); }
Returns when request failed
public byte loadByte(Offset offset){ return (byte)0; }
Loads a byte from the memory location pointed to by the current instance.
public SQLiteCustomFunction(String name,int numArgs,SQLiteDatabase.CustomFunction callback){ if (name == null) { throw new IllegalArgumentException("name must not be null."); } this.name=name; this.numArgs=numArgs; this.callback=callback; }
Create custom function.
private void generateBlackPixels(){ log.info("Converting image to monochrome"); BufferedImage bi=bufferedImage; int h=bi.getHeight(); int w=bi.getWidth(); int[] rgbPixels=bi.getRGB(0,0,w,h,null,0,w); int i=0; boolean[] pixels=new boolean[rgbPixels.length]; for ( int rgbpixel : rgbPixels) { pixels[i++]=languageType.requiresImageOutputInverted() ? !isBlack(rgbpixel) : isBlack(rgbpixel); } setImageAsBooleanArray(pixels); }
Sets ImageAsBooleanArray. boolean is used instead of int for memory considerations.
@Override public String toString(){ return String.format(FMT_TO_STRING,Integer.valueOf(System.identityHashCode(this)),String.valueOf(getObject())); }
Returns a string representation for this object. This string also contains a string representation of the object managed by this initializer.
public static ConfigUtils instance(){ if (!instance.isInitialized) { synchronized (ConfigUtils.class) { if (!instance.isInitialized) { throw new IllegalStateException("ConfigUtils is not initialized."); } } } return instance; }
Singleton accessor method.
public void addSharedContextUser(Context sharedContext,User user){ this.getContextPanel(sharedContext.getIndex()).getUsersTableModel().addUser(user); }
Add a new user shown in the UI (for the Users context panel) that corresponds to a particular shared Context.
public Configuration loadConfiguration(String configPath){ Configuration config=null; try { int p=configPath.lastIndexOf("/dert/"); String landPath=configPath.substring(0,p); File file=new File(configPath).getCanonicalFile(); if (file.exists()) { Console.getInstance().println("Loading configuration from " + file.getAbsolutePath()); ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file)); Object obj=ois.readObject(); ois.close(); if (obj instanceof HashMap<?,?>) { config=new Configuration((HashMap<String,Object>)obj); config.setLandscapePath(landPath); addRecent(configPath); } else { JOptionPane.showMessageDialog(null,"Configuration for " + landPath + " is invalid."); } } else { JOptionPane.showMessageDialog(null,"Configuration for " + landPath + " does not exist."); } } catch ( Exception e) { Console.getInstance().println("Unable to load configuration " + configPath + ", see log."); e.printStackTrace(); } return (config); }
Load a Configuration file
private static void skipMemoryAccess(final OperandOrderIterator iter){ do { if (iter.current().getType() == ExpressionType.MEMDEREF) { iter.next(); while (iter.current().getType() != ExpressionType.IMMEDIATE_INTEGER) { iter.next(); } return; } } while (iter.next()); }
Skips all the nodes that should not be printed in simplified variable access mode.
void implCompress(byte[] buf,int ofs){ b2iBig64(buf,ofs,W); for (int t=16; t <= 79; t++) { int temp=W[t - 3] ^ W[t - 8] ^ W[t - 14]^ W[t - 16]; W[t]=(temp << 1) | (temp >>> 31); } int a=state[0]; int b=state[1]; int c=state[2]; int d=state[3]; int e=state[4]; for (int i=0; i < 20; i++) { int temp=((a << 5) | (a >>> (32 - 5))) + ((b & c) | ((~b) & d)) + e+ W[i]+ round1_kt; e=d; d=c; c=((b << 30) | (b >>> (32 - 30))); b=a; a=temp; } for (int i=20; i < 40; i++) { int temp=((a << 5) | (a >>> (32 - 5))) + (b ^ c ^ d) + e+ W[i]+ round2_kt; e=d; d=c; c=((b << 30) | (b >>> (32 - 30))); b=a; a=temp; } for (int i=40; i < 60; i++) { int temp=((a << 5) | (a >>> (32 - 5))) + ((b & c) | (b & d) | (c & d)) + e+ W[i]+ round3_kt; e=d; d=c; c=((b << 30) | (b >>> (32 - 30))); b=a; a=temp; } for (int i=60; i < 80; i++) { int temp=((a << 5) | (a >>> (32 - 5))) + (b ^ c ^ d) + e+ W[i]+ round4_kt; e=d; d=c; c=((b << 30) | (b >>> (32 - 30))); b=a; a=temp; } state[0]+=a; state[1]+=b; state[2]+=c; state[3]+=d; state[4]+=e; }
Compute a the hash for the current block. This is in the same vein as Peter Gutmann's algorithm listed in the back of Applied Cryptography, Compact implementation of "old" NIST Secure Hash Algorithm.
public WeakValueHashMap(int capacity){ references=new HashMap<>(capacity); gcQueue=new ReferenceQueue<>(); }
Creates a WeakValueHashMap with a desired initial capacity
protected boolean haveSharedCellsRaw(DoubleMatrix2D other){ if (other instanceof SelectedSparseDoubleMatrix2D) { SelectedSparseDoubleMatrix2D otherMatrix=(SelectedSparseDoubleMatrix2D)other; return this.elements == otherMatrix.elements; } else if (other instanceof SparseDoubleMatrix2D) { SparseDoubleMatrix2D otherMatrix=(SparseDoubleMatrix2D)other; return this.elements == otherMatrix.elements; } return false; }
Returns <tt>true</tt> if both matrices share common cells. More formally, returns <tt>true</tt> if <tt>other != null</tt> and at least one of the following conditions is met <ul> <li>the receiver is a view of the other matrix <li>the other matrix is a view of the receiver <li><tt>this == other</tt> </ul>
private void persistServerURI(String serverURI){ File fileDir=newConnection.getFilesDir(); File presited=new File(fileDir,"hosts.txt"); BufferedWriter bfw=null; try { bfw=new BufferedWriter(new FileWriter(presited)); bfw.write(serverURI); bfw.newLine(); } catch ( IOException e) { e.printStackTrace(); } finally { try { if (bfw != null) { bfw.close(); } } catch ( IOException e) { e.printStackTrace(); } } }
Add a server URI to the persisted file
public int hashCode(){ if (this.affineX != null) { return affineX.hashCode() * 31 + affineY.hashCode(); } return 11; }
Returns the hashcode of this elliptic curve point.
public <T>JsonStringMap<T> createMapDtoFromJson(String json,Class<T> dtoInterface){ final DtoProvider<T> dtoProvider=getDtoProvider(dtoInterface); final Map<String,JsonElement> map=gson.fromJson(json,mapTypeCache.getUnchecked(JsonElement.class)); final Map<String,T> result=new LinkedHashMap<>(map.size()); for ( Map.Entry<String,JsonElement> e : map.entrySet()) { result.put(e.getKey(),dtoProvider.fromJson(e.getValue())); } return new JsonStringMapImpl<>(result); }
Parses the JSON data from the specified sting into map of objects of the specified type.
public static <T>T[] toArray(Iterable<? extends T> iterable,Class<T> type){ Collection<? extends T> collection=toCollection(iterable); T[] array=ObjectArrays.newArray(type,collection.size()); return collection.toArray(array); }
Copies an iterable's elements into an array.
void attribTypeVariables(List<JCTypeParameter> typarams,Env<AttrContext> env){ for ( JCTypeParameter tvar : typarams) { TypeVar a=(TypeVar)tvar.type; a.tsym.flags_field|=UNATTRIBUTED; a.bound=Type.noType; if (!tvar.bounds.isEmpty()) { List<Type> bounds=List.of(attribType(tvar.bounds.head,env)); for ( JCExpression bound : tvar.bounds.tail) bounds=bounds.prepend(attribType(bound,env)); types.setBounds(a,bounds.reverse()); } else { types.setBounds(a,List.of(syms.objectType)); } a.tsym.flags_field&=~UNATTRIBUTED; } for ( JCTypeParameter tvar : typarams) { chk.checkNonCyclic(tvar.pos(),(TypeVar)tvar.type); } }
Attribute type variables (of generic classes or methods). Compound types are attributed later in attribBounds.
public DrawerBuilder withDrawerGravity(int gravity){ this.mDrawerGravity=gravity; return this; }
Set the gravity for the drawer. START, LEFT | RIGHT, END
public static String innerClassString(int flags){ return humanHelper(flags,INNER_CLASS_FLAGS,CONV_CLASS); }
Returns a human-oriented string representing the given access flags, as defined on inner classes.
public void testResourcesAvailable(){ new DanishAnalyzer().close(); }
This test fails with NPE when the stopwords file is missing in classpath
protected OMGraphic createLine(MysqlLine myLine){ OMPoly ompoly=new OMPoly(myLine.getCoordinateArray(),OMGraphic.DECIMAL_DEGREES,OMGraphic.LINETYPE_STRAIGHT); drawingAttributes.setTo(ompoly); return ompoly; }
Method createLine. Renders a Linestring Geometry. ToDo: Holes
@Override public void keyTyped(char par1,int par2){ super.keyTyped(par1,par2); this.textFieldFrequency.textboxKeyTyped(par1,par2); try { int newFrequency=Math.max(0,Integer.parseInt(this.textFieldFrequency.getText())); this.textFieldFrequency.setText(newFrequency + ""); if (((IItemFrequency)this.itemStack.getItem()).getFrequency(this.itemStack) != newFrequency) { ((IItemFrequency)this.itemStack.getItem()).setFrequency(newFrequency,this.itemStack); ArrayList data=new ArrayList(); data.add(newFrequency); DefenseTech.netHandler.sendToServer(new ItemMessage(data)); } } catch ( NumberFormatException e) { } }
Call this method from you GuiScreen to process the keys into textbox.
public T caseStructuralTypeRef(StructuralTypeRef object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Structural Type Ref</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
private String generateSignatureBaseString(String httpsURL,String requestMethod,Map<String,SortedSet<String>> baseParameters){ URI requestUri=parseUrl(httpsURL); String encodedBaseString; encodedBaseString=encode(requestMethod.toUpperCase()) + AMP + encode(normalizeUrl(requestUri))+ AMP+ encode(normalizeParameters(httpsURL,baseParameters)); return encodedBaseString; }
Calculates the signature base url as per section 9.1 of the OAuth Spec. This is a concatenation of http method, request url, and other request parameters.
public ConnectException(String detailMessage){ super(detailMessage); }
Constructs a new instance with the given detail message.
public XhtmlFrameSetDocument appendHead(String value){ head.addElement(value); return (this); }
Append to the head element for this XhtmlFrameSetDocument container.
boolean canRunInCurrentRunState(boolean periodic){ return isRunningOrShutdown(periodic ? continueExistingPeriodicTasksAfterShutdown : executeExistingDelayedTasksAfterShutdown); }
Returns true if can run a task given current run state and run-after-shutdown parameters.
public void doWindowClose(){ okToAbandon(); }
doWindowClose() -
public void add(double x,double y,double yLow,double yHigh,boolean notify){ super.add(new YIntervalDataItem(x,y,yLow,yHigh),notify); }
Adds a data item to the series.
@Inline @Entrypoint public static byte byteArrayRead(byte[] ref,int index){ if (NEEDS_BYTE_GC_READ_BARRIER) { ObjectReference array=ObjectReference.fromObject(ref); Offset offset=Offset.fromIntZeroExtend(index); return Selected.Mutator.get().byteRead(array,array.toAddress().plus(offset),offset.toWord(),Word.zero(),ARRAY_ELEMENT); } else if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); return 0; }
Barrier for loads of bytes from fields of arrays (i.e. baload).
public boolean implies(Permission p){ if (!(p instanceof ExecPermission)) return false; ExecPermission that=(ExecPermission)p; return fp.implies(that.fp); }
Checks if this ExecPermission object "implies" the specified permission. <P> More specifically, this method returns true if:<p> <ul> <li> <i>p</i> is an instanceof ExecPermission,<p> and <li> <i>p</i>'s pathname is implied by this object's pathname. For example, "/tmp/*" implies "/tmp/foo", since "/tmp/*" encompasses the "/tmp" directory and all files in that directory, including the one named "foo". </ul>
public void addMacro(String name) throws LexerException { addMacro(name,"1"); }
Defines the given name as a macro, with the value <code>1</code>. This is a convnience method, and is equivalent to <code>addMacro(name, "1")</code>.
public void clearAnimation(){ rotationAnimator.cancel(); }
Cancel circular loader animation.
public void updatePlayers(){ String introduction="The best maze runners:\n"; SignFromHallOfFameLoader loader=new SignFromHallOfFameLoader(this,introduction,"M",SIGN_LENGTH,false,true); TurnNotifier.get().notifyInTurns(0,loader); }
Update the player list written on the sign.
boolean isAlpha(char ch){ return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')); }
Test if a character is alpha (A-Z,a-z).
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception { LookupTables.setupItypes(request,true); LookupTables.setupPrefLevels(request); return mapping.findForward(mapping.getInput()); }
Method execute
public Object visit(ASTText node,Object data){ return showNode(node,data); }
Display an ASTText node
public NioDatagramAcceptor(Executor executor){ this(new DefaultDatagramSessionConfig(),executor); }
Creates a new instance.
public void remove(DocumentFilter.FilterBypass fb,int offset,int length) throws BadLocationException { if (offset == 0 && length != fb.getDocument().getLength()) { fb.replace(0,length,"\n",lexer.defaultStyle); parseDocument(offset,2); fb.remove(offset,1); } else { fb.remove(offset,length); if (offset + 1 < fb.getDocument().getLength()) { parseDocument(offset,1); } else if (offset - 1 > 0) { parseDocument(offset - 1,1); } else { mlTextRunSet.clear(); } } }
Remove a string from the document, and then parse it if the parser has been set.
public InterruptedException(){ }
Constructs an InterruptedException with no detail message.
public void requestAllContactsCapabilities() throws RcsServiceNotRegisteredException, RcsServiceNotAvailableException, RcsGenericException { try { mApi.requestAllContactsCapabilities(); } catch ( Exception e) { RcsServiceNotRegisteredException.assertException(e); throw new RcsGenericException(e); } }
Requests capabilities for all contacts existing in the local address book. This method initiates in background new capability requests for each contact of the address book by sending SIP OPTIONS. The result of a capability request is sent asynchronously via callback method of the capabilities listener. The result of the capability refresh request is provided to all the clients that have registered the listener for this event.
public TFloatDoubleHashMap(int initialCapacity,float loadFactor){ super(initialCapacity,loadFactor); }
Creates a new <code>TFloatDoubleHashMap</code> instance with a prime capacity equal to or greater than <tt>initialCapacity</tt> and with the specified load factor.
public void addEntry(EntryEventImpl ev){ this.putAllData[this.putAllDataSize]=new PutAllEntryData(ev); this.putAllDataSize+=1; }
Add an entry that this putall operation should distribute.
protected void atCastToRtype(CastExpr expr) throws CompileError { CtClass returnType=codeGen.returnType; expr.getOprand().accept(this); if (exprType == VOID || CodeGen.isRefType(exprType) || arrayDim > 0) compileUnwrapValue(returnType); else if (returnType instanceof CtPrimitiveType) { CtPrimitiveType pt=(CtPrimitiveType)returnType; int destType=MemberResolver.descToType(pt.getDescriptor()); exprType=destType; arrayDim=0; className=null; } }
Inserts a cast operator to the return type. If the return type is void, this does nothing.
public long append(Entry entry){ Assert.notNull(entry,"entry"); Assert.stateNot(isFull(),"segment is full"); long index=nextIndex(); Assert.index(index == entry.getIndex(),"inconsistent index: %s",entry.getIndex()); long offset=relativeOffset(index); long term=entry.getTerm(); long lastTerm=termIndex.term(); Assert.arg(term > 0 && term >= lastTerm,"term must be monotonically increasing"); long position=buffer.mark().position(); boolean skipTerm=term == lastTerm; int headerLength=Bytes.INTEGER + Bytes.LONG + Bytes.BOOLEAN+ (skipTerm ? 0 : Bytes.LONG); serializer.writeObject(entry,buffer.skip(headerLength)); int length=(int)(buffer.position() - (position + headerLength)); entry.setSize(length); buffer.reset().writeInt(length).writeLong(offset); if (skipTerm) { buffer.writeBoolean(false).skip(length); } else { buffer.writeBoolean(true).writeLong(entry.getTerm()).skip(length); } offsetIndex.index(offset,position); if (term > lastTerm) { termIndex.index(offset,term); } skip=0; return index; }
Commits an entry to the segment.
private void doLoad(HttpServletRequest request,InstructorEditForm frm,DepartmentalInstructor inst,String instructorId){ frm.setInstructorId(instructorId); frm.setName(Constants.toInitialCase(inst.getFirstName(),"-".toCharArray()) + " " + ((inst.getMiddleName() == null) ? "" : Constants.toInitialCase(inst.getMiddleName(),"-".toCharArray()))+ " "+ Constants.toInitialCase(inst.getLastName(),"-".toCharArray())); if (inst.getExternalUniqueId() != null) { frm.setPuId(inst.getExternalUniqueId()); } frm.setDeptName(inst.getDepartment().getName().trim()); if (inst.getPositionType() != null) { frm.setPosType(inst.getPositionType().getUniqueId().toString()); } if (inst.getCareerAcct() != null) { frm.setCareerAcct(inst.getCareerAcct().trim()); } frm.setEmail(inst.getEmail()); if (inst.getNote() != null) { frm.setNote(inst.getNote().trim()); } try { DepartmentalInstructor previous=inst.getPreviousDepartmentalInstructor(sessionContext,Right.InstructorPreferences); frm.setPreviousId(previous == null ? null : previous.getUniqueId().toString()); DepartmentalInstructor next=inst.getNextDepartmentalInstructor(sessionContext,Right.InstructorPreferences); frm.setNextId(next == null ? null : next.getUniqueId().toString()); } catch ( Exception e) { Debug.error(e); } }
Loads the non-editable instructor info into the form
@Override public boolean isRunning(){ return !paused; }
Returns true if the module is running, and false otherwise.
public boolean isCompressionLossless(){ if (!canWriteCompressed()) { throw new UnsupportedOperationException("Compression not supported"); } if (getCompressionMode() != MODE_EXPLICIT) { throw new IllegalStateException("Compression mode not MODE_EXPLICIT!"); } if ((getCompressionTypes() != null) && (getCompressionType() == null)) { throw new IllegalStateException("No compression type set!"); } return true; }
Returns <code>true</code> if the current compression type provides lossless compression. If a plug-in provides only one mandatory compression type, then this method may be called without calling <code>setCompressionType</code> first. <p> If there are multiple compression types but none has been set, an <code>IllegalStateException</code> is thrown. <p> The default implementation checks whether compression is supported and the compression mode is <code>MODE_EXPLICIT</code>. If so, if <code>getCompressionTypes()</code> is <code>null</code> or <code>getCompressionType()</code> is non-<code>null</code> <code>true</code> is returned as a convenience.
public void clear(){ lineItems.clear(); }
Removes all line items from the cart.
private void initCachingHttpHeadersFilter(ServletContext servletContext,EnumSet<DispatcherType> disps){ log.debug("Registering Caching HTTP Headers Filter"); FilterRegistration.Dynamic cachingHttpHeadersFilter=servletContext.addFilter("cachingHttpHeadersFilter",new CachingHttpHeadersFilter(env)); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps,true,"/dist/assets/*"); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps,true,"/dist/scripts/*"); cachingHttpHeadersFilter.setAsyncSupported(true); }
Initializes the caching HTTP Headers Filter.
public void removeAttributes(String name){ removeAttributes(name,null); }
Removes all attributes with a certain name from the list.
@CanIgnoreReturnValue @Deprecated @Override public <T extends B>T putInstance(Class<T> type,T value){ throw new UnsupportedOperationException(); }
Guaranteed to throw an exception and leave the map unmodified.
private void insertAdobeMarkerSegment(AdobeMarkerSegment newGuy){ boolean hasJFIF=(findMarkerSegment(JFIFMarkerSegment.class,true) != null); int lastUnknown=findLastUnknownMarkerSegmentPosition(); if (hasJFIF) { markerSequence.add(1,newGuy); } else if (lastUnknown != -1) { markerSequence.add(lastUnknown + 1,newGuy); } else { markerSequence.add(0,newGuy); } }
Insert the given AdobeMarkerSegment into the marker sequence, as follows (we assume there is no Adobe segment yet): If there is a JFIF segment, then the new Adobe segment is inserted after it. If there is no JFIF segment, the new Adobe segment is inserted after the last Unknown segment, if there are any. If there are no Unknown segments, the new Adobe segment is inserted at the beginning of the sequence.
public Collection<GridClientNode> nodes(Iterable<UUID> ids) throws GridClientException { assert ids != null; Collection<GridClientNode> res=new LinkedList<>(); lock.readLock().lock(); try { if (lastError != null) throw new GridClientDisconnectedException("Latest topology update failed.",lastError); for ( UUID id : ids) { GridClientNodeImpl node=nodes.get(id); if (node != null) res.add(node); } return res; } finally { lock.readLock().unlock(); } }
Gets a collection of nodes from last saved topology snapshot by their ids.
public static int paramSize(String desc){ return -dataSize(desc,false); }
Computes the data size of parameters. If one of the parameters is double type, the size of that parameter is 2 words. For example, if the given descriptor is <code>"(IJ)D"</code>, then this method returns 3. The size of the return type is not computed.
public static String typeToStringShort(Attribute att){ return typeToStringShort(att.type()); }
Returns a short string representation of the attribute type.
public static char[] toCharArray(InputStream is,Charset encoding) throws IOException { CharArrayWriter output=new CharArrayWriter(); copy(is,output,encoding); return output.toCharArray(); }
Get the contents of an <code>InputStream</code> as a character array using the specified character encoding. <p> This method buffers the input internally, so there is no need to use a <code>BufferedInputStream</code>.
public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } return new FileInputStream(entry.getCleanFile(index)); } }
Returns an unbuffered input stream to read the last committed value, or null if no value has been committed.
public KeywordLiteral(int pos,int len,int nodeType){ super(pos,len); setType(nodeType); }
Constructs a new KeywordLiteral
public boolean isTailSplit(){ if (!initView) { getView(); } return tailSplit; }
Return <code>true</code> if the index partition satisfies the criteria for a tail split (heavy writes on the tail of the index partition and the size of the index partition is large enough to warrant a tail split).
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public CommHeader(String sync,short messageLength,String sender,String receiver,int sequenceNo){ super(); this.sync=sync; this.messageLength=messageLength; this.sender=sender; this.receiver=receiver; this.sequenceNo=sequenceNo; }
Create a new CommHeader.