code
stringlengths
10
174k
nl
stringlengths
3
129k
public static List<String> splitDBdotName(String src,String cat,String quotId,boolean isNoBslashEscSet){ if ((src == null) || (src.equals("%"))) { return new ArrayList<String>(); } boolean isQuoted=StringUtils.indexOfIgnoreCase(0,src,quotId) > -1; String retval=src; String tmpCat=cat; int trueDotIndex=-1; if (!" ".equals(quotId)) { if (isQuoted) { trueDotIndex=StringUtils.indexOfIgnoreCase(0,retval,quotId + "." + quotId); } else { trueDotIndex=StringUtils.indexOfIgnoreCase(0,retval,"."); } } else { trueDotIndex=retval.indexOf("."); } List<String> retTokens=new ArrayList<String>(2); if (trueDotIndex != -1) { if (isQuoted) { tmpCat=StringUtils.toString(StringUtils.stripEnclosure(retval.substring(0,trueDotIndex + 1).getBytes(),quotId,quotId)); if (StringUtils.startsWithIgnoreCaseAndWs(tmpCat,quotId)) { tmpCat=tmpCat.substring(1,tmpCat.length() - 1); } retval=retval.substring(trueDotIndex + 2); retval=StringUtils.toString(StringUtils.stripEnclosure(retval.getBytes(),quotId,quotId)); } else { tmpCat=retval.substring(0,trueDotIndex); retval=retval.substring(trueDotIndex + 1); } } else { retval=StringUtils.toString(StringUtils.stripEnclosure(retval.getBytes(),quotId,quotId)); } retTokens.add(tmpCat); retTokens.add(retval); return retTokens; }
Next we check if there is anything to split. If so we return result in form of "database";"name" If string is NULL or wildcard (%), returns null and exits.
public ObjectMatrix1D viewRow(int row){ checkRow(row); int viewSize=this.columns; int viewZero=columnZero; int viewStride=this.columnStride; int[] viewOffsets=this.columnOffsets; int viewOffset=this.offset + _rowOffset(_rowRank(row)); return new SelectedSparseObjectMatrix1D(viewSize,this.elements,viewZero,viewStride,viewOffsets,viewOffset); }
Constructs and returns a new <i>slice view</i> representing the columns of the given row. The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa. To obtain a slice view on subranges, construct a sub-ranging view (<tt>viewPart(...)</tt>), then apply this method to the sub-range view. <p> <b>Example:</b> <table border="0"> <tr nowrap> <td valign="top">2 x 3 matrix: <br> 1, 2, 3<br> 4, 5, 6 </td> <td>viewRow(0) ==></td> <td valign="top">Matrix1D of size 3:<br> 1, 2, 3</td> </tr> </table>
public static void main(String[] args){ Set<Emoticon> emotes=makeEmoticons("e1"); System.out.println(emotes.size()); for ( Emoticon emote : emotes) { System.out.println(emote.getInfos()); } }
For testing.
@Override public String toString(){ return String.valueOf(value); }
Returns a string containing a concise, human-readable description of this boolean.
public void debug(Throwable throwable,String msg,Object arg0,Object arg1){ innerLog(Level.DEBUG,throwable,msg,arg0,arg1,UNKNOWN_ARG,null); }
Log a debug message with a throwable.
public void runProcess(){ runProcess(true); }
Runs or resumes the current process. If the process is started, checks for potential errors first and prevents execution unless the user has disabled the pre-run check.
private double calculateBarThickness(Rectangle2D plotArea,RectangleEdge edge){ double result; if (RectangleEdge.isLeftOrRight(edge)) { result=plotArea.getWidth() * this.colorBarThicknessPercent; } else { result=plotArea.getHeight() * this.colorBarThicknessPercent; } return result; }
Calculates the bar thickness.
@Override public void flushBuffer() throws IOException { if (this.printWriter != null) { this.printWriter.flush(); } if (this.gzipOutputStream != null) { this.gzipOutputStream.flush(); } if (!disableFlushBuffer) { super.flushBuffer(); } }
Flush OutputStream or PrintWriter
public void deleteAttributeAt(int position){ if ((position < 0) || (position >= m_Attributes.size())) { throw new IllegalArgumentException("Index out of range"); } if (position == m_ClassIndex) { throw new IllegalArgumentException("Can't delete class attribute"); } freshAttributeInfo(); if (m_ClassIndex > position) { m_ClassIndex--; } m_Attributes.removeElementAt(position); for (int i=position; i < m_Attributes.size(); i++) { Attribute current=(Attribute)m_Attributes.elementAt(i); current.setIndex(current.index() - 1); } for (int i=0; i < numInstances(); i++) { instance(i).forceDeleteAttributeAt(position); } }
Deletes an attribute at the given position (0 to numAttributes() - 1). A deep copy of the attribute information is performed before the attribute is deleted.
protected void performTest(boolean num,boolean cl,boolean dist,boolean error,boolean remove){ Instances icopy; int numAtts; if (num) m_Instances.setClassIndex(1); else m_Instances.setClassIndex(0); icopy=new Instances(m_Instances); m_Filter=getFilter(); if (num) ((AddClassification)m_Filter).setClassifier(new weka.classifiers.trees.M5P()); else ((AddClassification)m_Filter).setClassifier(new weka.classifiers.trees.J48()); ((AddClassification)m_Filter).setOutputClassification(cl); ((AddClassification)m_Filter).setOutputDistribution(dist); ((AddClassification)m_Filter).setOutputErrorFlag(error); ((AddClassification)m_Filter).setRemoveOldClass(remove); numAtts=icopy.numAttributes(); if (cl) numAtts++; if (dist) numAtts+=icopy.numClasses(); if (error) numAtts++; if (remove) numAtts--; Instances result=useFilter(); assertEquals(result.numAttributes(),numAtts); }
sets up the filter and performs the test
public void unscheduleAllSelectors(Object target){ if (target == null) return; tHashSelectorEntry element=hashForSelectors.get(target); if (element != null) { if (!element.currentTimerSalvaged) { element.currentTimerSalvaged=true; } element.timers.clear(); if (currentTarget == element) currentTargetSalvaged=true; else { hashForSelectors.remove(element.target); } } this.unscheduleUpdate(target); }
Unschedules all selectors for a given target. This also includes the "update" selector.
@Override public SSLEngineResult wrap(ByteBuffer[] srcs,int offset,int len,ByteBuffer dst) throws SSLException { if (engine_was_shutteddown) { return new SSLEngineResult(SSLEngineResult.Status.CLOSED,SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,0,0); } if ((srcs == null) || (dst == null)) { throw new IllegalStateException("Some of the input parameters are null"); } if (dst.isReadOnly()) { throw new ReadOnlyBufferException(); } if (!handshake_started) { beginHandshake(); } SSLEngineResult.HandshakeStatus handshakeStatus=getHandshakeStatus(); if ((session == null || engine_was_closed) && (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP) || handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_TASK))) { return new SSLEngineResult(getEngineStatus(),handshakeStatus,0,0); } int capacity=dst.remaining(); int produced=0; if (alertProtocol.hasAlert()) { if (capacity < recordProtocol.getRecordSize(2)) { return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,handshakeStatus,0,0); } byte[] alert_data=alertProtocol.wrap(); dst.put(alert_data); if (alertProtocol.isFatalAlert()) { alertProtocol.setProcessed(); if (session != null) { session.invalidate(); } shutdown(); return new SSLEngineResult(SSLEngineResult.Status.CLOSED,SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,0,alert_data.length); } else { alertProtocol.setProcessed(); if (close_notify_was_sent && close_notify_was_received) { shutdown(); return new SSLEngineResult(SSLEngineResult.Status.CLOSED,SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,0,alert_data.length); } return new SSLEngineResult(getEngineStatus(),getHandshakeStatus(),0,alert_data.length); } } if (capacity < recordProtocol.getMinRecordSize()) { if (logger != null) { logger.println("Capacity of the destination(" + capacity + ") < MIN_PACKET_SIZE("+ recordProtocol.getMinRecordSize()+ ")"); } return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,handshakeStatus,0,0); } try { if (!handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_WRAP)) { dataStream.setSourceBuffers(srcs,offset,len); if ((capacity < SSLRecordProtocol.MAX_SSL_PACKET_SIZE) && (capacity < recordProtocol.getRecordSize(dataStream.available()))) { if (logger != null) { logger.println("The destination buffer(" + capacity + ") can not take the resulting packet("+ recordProtocol.getRecordSize(dataStream.available())+ ")"); } return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,handshakeStatus,0,0); } if (remaining_wrapped_data == null) { remaining_wrapped_data=recordProtocol.wrap(ContentType.APPLICATION_DATA,dataStream); } if (capacity < remaining_wrapped_data.length) { return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,handshakeStatus,dataStream.consumed(),0); } else { dst.put(remaining_wrapped_data); produced=remaining_wrapped_data.length; remaining_wrapped_data=null; return new SSLEngineResult(getEngineStatus(),handshakeStatus,dataStream.consumed(),produced); } } else { if (remaining_hsh_data == null) { remaining_hsh_data=handshakeProtocol.wrap(); } if (capacity < remaining_hsh_data.length) { return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,handshakeStatus,0,0); } else { dst.put(remaining_hsh_data); produced=remaining_hsh_data.length; remaining_hsh_data=null; handshakeStatus=handshakeProtocol.getStatus(); if (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.FINISHED)) { session=recordProtocol.getSession(); } } return new SSLEngineResult(getEngineStatus(),getHandshakeStatus(),0,produced); } } catch ( AlertException e) { alertProtocol.alert(AlertProtocol.FATAL,e.getDescriptionCode()); engine_was_closed=true; if (session != null) { session.invalidate(); } throw e.getReason(); } }
Encodes the application data into SSL/TLS record. If handshake status of the engine differs from NOT_HANDSHAKING the operation can work without consuming of the source data. For more information about TLS record fragmentation see TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-18 10:08:19.790 -0400",hash_original_method="08262397EECB793443234B722C227E60",hash_generated_method="632B5CFBF061DCF547D23A601C200768") public boolean isRtl(String str){ return mDefaultTextDirectionHeuristicCompat.isRtl(str,0,str.length()); }
Estimates the directionality of a string using the default text direction heuristic.
public boolean drawImage(Image img,int dx1,int dy1,int dx2,int dy2,int sx1,int sy1,int sx2,int sy2,ImageObserver observer){ return mGraphics.drawImage(img,dx1,dy1,dx2,dy2,sx1,sy1,sx2,sy2,observer); }
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. Transparent pixels do not affect whatever pixels are already there. <p> This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then <code>drawImage</code> returns <code>false</code>. As more of the image becomes available, the process that draws the image notifies the specified image observer. <p> This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.
void closeImpl(){ ReadStreamOld is=_is; _is=null; WriteStreamOld os=_os; _os=null; try { if (is != null) is.close(); } catch ( Throwable e) { log.log(Level.FINER,e.toString(),e); } try { if (os != null) os.close(); } catch ( Throwable e) { log.log(Level.FINER,e.toString(),e); } if (is != null) { _connProbe.end(); if (_requestStartTime > 0) _requestTimeProbe.end(_requestStartTime); if (_isIdle) _idleProbe.end(); } }
closes the stream.
@Override public String toString(){ return "(" + getLeft() + ", "+ getTop()+ ")"; }
Textual representation of this location formatted as <code>(x, y)</code>.
private boolean ensureTouchModeLocally(boolean inTouchMode){ if (DBG) Log.d("touchmode","ensureTouchModeLocally(" + inTouchMode + "), current "+ "touch mode is "+ mAttachInfo.mInTouchMode); if (mAttachInfo.mInTouchMode == inTouchMode) return false; mAttachInfo.mInTouchMode=inTouchMode; mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); }
Ensure that the touch mode for this window is set, and if it is changing, take the appropriate action.
public void print(String text){ String[] lines=text.split("\n"); for ( String line : lines) { view.print(line.isEmpty() ? " " : line); } performPostOutputActions(); }
Print text on console.
public static Filter createFilter(Model model,RDFNode expression){ Filter filter=model.createResource(SP.Filter).as(Filter.class); filter.addProperty(SP.expression,expression); return filter; }
Creates a Filter from a given expression.
public Trigger linkTrigger(BigInteger alertId,BigInteger notificationId,BigInteger triggerId) throws IOException { String requestUrl=RESOURCE + "/" + alertId.toString()+ "/notifications/"+ notificationId.toString()+ "/triggers/"+ triggerId.toString(); ArgusResponse response=getClient().executeHttpRequest(ArgusHttpClient.RequestType.POST,requestUrl,null); assertValidResponse(response,requestUrl); return fromJson(response.getResult(),Trigger.class); }
Links a trigger to a notification.
public synchronized Graphics2D createGraphics(SurfaceData sd,WComponentPeer peer,Color fgColor,Color bgColor,Font font){ return new SunGraphics2D(sd,fgColor,bgColor,font); }
Creates a SunGraphics2D object for the surface, given the parameters.
protected void checkForDefaultQualifierInHierarchy(QualifierDefaults defs){ if (!defs.hasDefaultsForCheckedCode()) { ErrorReporter.errorAbort("GenericAnnotatedTypeFactory.createQualifierDefaults: " + "@DefaultQualifierInHierarchy or @DefaultFor(TypeUseLocation.OTHERWISE) not found. " + "Every checker must specify a default qualifier. "+ getSortedQualifierNames()); } }
Check that a default qualifier (in at least one hierarchy) has been set and issue an error if not.
@Override public boolean addAll(int index,Collection<? extends T> c){ throw new UnsupportedOperationException("cannot add to Empty Ranges"); }
Always throws <code>UnsupportedOperationException</code> for an empty range.
public static void applyAllElementAnnotations(final List<? extends AnnotatedTypeMirror> types,final List<? extends Element> elements,final AnnotatedTypeFactory typeFactory){ if (types.size() != elements.size()) { ErrorReporter.errorAbort("Number of types and elements don't match!" + "types ( " + PluginUtil.join(", ",types) + " ) "+ "element ( "+ PluginUtil.join(", ",elements)+ " ) "); } for (int i=0; i < types.size(); i++) { ElementAnnotationApplier.apply(types.get(i),elements.get(i),typeFactory); } }
For each type/element pair, add all of the annotations stored in Element to type. See apply for more details.
public static int GetVersionCode(Context context){ try { PackageInfo manager=context.getPackageManager().getPackageInfo(context.getPackageName(),0); return manager.versionCode; } catch ( PackageManager.NameNotFoundException e) { return -1; } }
get version code of this app
static String lookUpFactoryClassName(String factoryId,String propertiesFilename,String fallbackClassName){ SecuritySupport ss=SecuritySupport.getInstance(); try { String systemProp=ss.getSystemProperty(factoryId); if (systemProp != null) { debugPrintln("found system property, value=" + systemProp); return systemProp; } } catch ( SecurityException se) { } String factoryClassName=null; if (propertiesFilename == null) { File propertiesFile=null; boolean propertiesFileExists=false; try { String javah=ss.getSystemProperty("java.home"); propertiesFilename=javah + File.separator + "lib"+ File.separator+ DEFAULT_PROPERTIES_FILENAME; propertiesFile=new File(propertiesFilename); propertiesFileExists=ss.getFileExists(propertiesFile); } catch ( SecurityException e) { fLastModified=-1; fXalanProperties=null; } synchronized (ObjectFactory.class) { boolean loadProperties=false; FileInputStream fis=null; try { if (fLastModified >= 0) { if (propertiesFileExists && (fLastModified < (fLastModified=ss.getLastModified(propertiesFile)))) { loadProperties=true; } else { if (!propertiesFileExists) { fLastModified=-1; fXalanProperties=null; } } } else { if (propertiesFileExists) { loadProperties=true; fLastModified=ss.getLastModified(propertiesFile); } } if (loadProperties) { fXalanProperties=new Properties(); fis=ss.getFileInputStream(propertiesFile); fXalanProperties.load(fis); } } catch ( Exception x) { fXalanProperties=null; fLastModified=-1; } finally { if (fis != null) { try { fis.close(); } catch ( IOException exc) { } } } } if (fXalanProperties != null) { factoryClassName=fXalanProperties.getProperty(factoryId); } } else { FileInputStream fis=null; try { fis=ss.getFileInputStream(new File(propertiesFilename)); Properties props=new Properties(); props.load(fis); factoryClassName=props.getProperty(factoryId); } catch ( Exception x) { } finally { if (fis != null) { try { fis.close(); } catch ( IOException exc) { } } } } if (factoryClassName != null) { debugPrintln("found in " + propertiesFilename + ", value="+ factoryClassName); return factoryClassName; } return findJarServiceProviderName(factoryId); }
Finds the name of the required implementation class in the specified order. The specified order is the following: <ol> <li>query the system property using <code>System.getProperty</code> <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file <li>read <code>META-INF/services/<i>factoryId</i></code> file <li>use fallback classname </ol>
public int resumeDownload(long... ids){ initResumeMethod(); if (resumeDownload == null) { return -1; } try { return ((Integer)resumeDownload.invoke(downloadManager,ids)).intValue(); } catch ( Exception e) { e.printStackTrace(); } return -1; }
resume download
public static double sin(double radians){ return Math.sin(radians); }
Returns the trigonometric sine of the specified angle in radians.
public static int count(String str,String[] set){ if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { return 0; } CharSet chars=evaluateSet(set); int count=0; char[] chrs=str.toCharArray(); int sz=chrs.length; for (int i=0; i < sz; i++) { if (chars.contains(chrs[i])) { count++; } } return count; }
<p>Takes an argument in set-syntax, see evaluateSet, and returns the number of characters present in the specified string.</p> <p>An example would be:</p> <ul> <li>count(&quot;hello&quot;, {&quot;c-f&quot;, &quot;o&quot;}) returns 2.</li> </ul>
public boolean isUnset(Option option,String value){ return (values.get(option.text + value) == null); }
Check if the value for a choice option has not been set to a specific value.
@Override public float scorePayload(int doc,int start,int end,BytesRef payload){ return 1; }
The default implementation returns <code>1</code>
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
protected ItemBuilder(final Material material){ this.itemStack=new BaseItemStack(material); }
Construct new item builder for given material.
public BasicRequest(String url,RequestMethod requestMethod){ this.url=url; mRequestMethod=requestMethod; mHeaders=new HttpHeaders(); mHeaders.set(Headers.HEAD_KEY_ACCEPT,Headers.HEAD_VALUE_ACCEPT_ALL); mHeaders.set(Headers.HEAD_KEY_ACCEPT_ENCODING,Headers.HEAD_VALUE_ACCEPT_ENCODING_GZIP_DEFLATE); mHeaders.set(Headers.HEAD_KEY_ACCEPT_LANGUAGE,HeaderUtil.systemAcceptLanguage()); mHeaders.set(Headers.HEAD_KEY_USER_AGENT,UserAgent.instance()); mParamKeyValues=new LinkedMultiValueMap<>(); }
Create a request.
private void initPanel(){ if (effectorType.getSelectedItem() == "StraightMovement") { cleareffectorPanel(); setTitle("Add a straight movement effector"); currentEffectorPanel=new StraightEffectorPanel(rotatingEntity); mainPanel.add(currentEffectorPanel); } else if (effectorType.getSelectedItem() == "Turning") { cleareffectorPanel(); setTitle("Add a turning effector"); currentEffectorPanel=new TurningEffectorPanel(rotatingEntity); mainPanel.add(currentEffectorPanel); } else if (effectorType.getSelectedItem() == "Speech") { cleareffectorPanel(); setTitle("Add a speech effector"); currentEffectorPanel=new SpeechEffectorPanel(rotatingEntity); mainPanel.add(currentEffectorPanel); } pack(); setLocationRelativeTo(null); }
Initialize the effector Dialog Panel based upon the current effector type.
static void errorUnexpectedEntity(String systemID,int lineNr,String entity) throws XMLParseException { throw new XMLParseException(systemID,lineNr,"No entity reference is expected here (" + entity + ")"); }
Throws an XMLParseException to indicate that an entity reference is unexpected at this point.
public String toString(){ return this.getClass().getName() + "(" + lambda+ ")"; }
Returns a String representation of the receiver.
private void send(boolean decision){ if (mListener != null) { mListener.receive(mNormalOutput ? decision : !decision); } }
Sends the bit decision to the listener
private IgfsFileImpl resolveFileInfo(IgfsPath path,IgfsMode mode) throws Exception { assert path != null; assert mode != null; IgfsEntryInfo info=null; switch (mode) { case PRIMARY: info=meta.infoForPath(path); break; case DUAL_SYNC: case DUAL_ASYNC: try { IgfsFile status=secondaryFs.info(path); if (status != null) return new IgfsFileImpl(status,data.groupBlockSize()); } catch (Exception e) { U.error(log,"File info operation in DUAL mode failed [path=" + path + ']',e); throw e; } break; default : assert mode == PROXY : "Unknown mode: " + mode; IgfsFile status=secondaryFs.info(path); if (status != null) return new IgfsFileImpl(status,data.groupBlockSize()); else return null; } if (info == null) return null; return new IgfsFileImpl(path,info,data.groupBlockSize()); }
Resolve file info for the given path and the given mode.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:36.376 -0500",hash_original_method="CC4432751ADD65730712EA705F22C3CD",hash_generated_method="A16E16A1FBA95A0B4FE5FE948D5FF540") public void registerForSIMReady(Handler h,int what,Object obj){ Registrant r=new Registrant(h,what,obj); synchronized (mStateMonitor) { mSIMReadyRegistrants.add(r); if (mSimState.isSIMReady()) { r.notifyRegistrant(new AsyncResult(null,null,null)); } } }
Any transition into SIM_READY
public void clearDeploymentThisRound(){ deploymentTable.remove(new Integer(getRoundCount())); }
Clear this round from this list of entities to deploy
private boolean readToken() throws IOException { byte token; try { token=this.dataIn.readByte(); switch (token) { case HEADER_TOKEN: readHeaderToken(); this.myIs.putBytes(this.dataOut); break; case RESOURCE_TYPE_TOKEN: readResourceTypeToken(); this.myIs.putBytes(this.dataOut); break; case RESOURCE_INSTANCE_CREATE_TOKEN: case RESOURCE_INSTANCE_INITIALIZE_TOKEN: readResourceInstanceCreateToken(token == RESOURCE_INSTANCE_INITIALIZE_TOKEN); this.myIs.putBytes(this.dataOut); break; case RESOURCE_INSTANCE_DELETE_TOKEN: readResourceInstanceDeleteToken(); this.myIs.putBytes(this.dataOut); break; case SAMPLE_TOKEN: readSampleToken(); this.myIs.putBytes(this.dataOut); break; default : throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TOKEN_BYTE_VALUE_0.toLocalizedString(new Byte(token))); } return true; } catch (EOFException ignore) { return false; } }
Returns true if token read, false if eof.
public void storeCookies(URLConnection conn) throws IOException { String domain=getDomainFromHost(conn.getURL().getHost()); Map domainStore; if (store.containsKey(domain)) { domainStore=(Map)store.get(domain); } else { domainStore=new HashMap(); store.put(domain,domainStore); } String headerName=null; for (int i=1; (headerName=conn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase(SET_COOKIE)) { Map cookie=new HashMap(); StringTokenizer st=new StringTokenizer(conn.getHeaderField(i),COOKIE_VALUE_DELIMITER); if (st.hasMoreTokens()) { String token=st.nextToken(); String name=token.substring(0,token.indexOf(NAME_VALUE_SEPARATOR)); String value=token.substring(token.indexOf(NAME_VALUE_SEPARATOR) + 1,token.length()); domainStore.put(name,cookie); cookie.put(name,value); } while (st.hasMoreTokens()) { String token=st.nextToken(); try { cookie.put(token.substring(0,token.indexOf(NAME_VALUE_SEPARATOR)).toLowerCase(),token.substring(token.indexOf(NAME_VALUE_SEPARATOR) + 1,token.length())); } catch ( Exception e) { } } } } }
Retrieves and stores cookies returned by the host on the other side of the the open java.net.URLConnection. The connection MUST have been opened using the connect() method or a IOException will be thrown.
@Override public int eDerivedStructuralFeatureID(int baseFeatureID,Class<?> baseClass){ if (baseClass == GenericDeclaration.class) { switch (baseFeatureID) { case N4JSPackage.GENERIC_DECLARATION__TYPE_VARS: return N4JSPackage.METHOD_DECLARATION__TYPE_VARS; default : return -1; } } if (baseClass == TypeProvidingElement.class) { switch (baseFeatureID) { default : return -1; } } if (baseClass == TypedElement.class) { switch (baseFeatureID) { case N4JSPackage.TYPED_ELEMENT__DECLARED_TYPE_REF: return N4JSPackage.METHOD_DECLARATION__DECLARED_TYPE_REF; case N4JSPackage.TYPED_ELEMENT__BOGUS_TYPE_REF: return N4JSPackage.METHOD_DECLARATION__BOGUS_TYPE_REF; default : return -1; } } if (baseClass == NamedElement.class) { switch (baseFeatureID) { default : return -1; } } if (baseClass == PropertyNameOwner.class) { switch (baseFeatureID) { case N4JSPackage.PROPERTY_NAME_OWNER__DECLARED_NAME: return N4JSPackage.METHOD_DECLARATION__DECLARED_NAME; default : return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID,baseClass); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private static boolean isAccessible(Path path,AccessMode... modes){ try { provider(path).checkAccess(path,modes); return true; } catch ( IOException x) { return false; } }
Used by isReadbale, isWritable, isExecutable to test access to a file.
public static List<Command> parse(final String[] args,final CommandListener commandListener){ CmdLine.setCommandListener(commandListener); return (CmdLine.parse(args)); }
Parse the command line arguments.
public SearchSourceBuilder query(XContentBuilder query){ return query(query.bytes()); }
Constructs a new search source builder with a query from a builder.
public RRSIGRecord(Name name,int dclass,long ttl,int covered,int alg,long origttl,Date expire,Date timeSigned,int footprint,Name signer,byte[] signature){ super(name,Type.RRSIG,dclass,ttl,covered,alg,origttl,expire,timeSigned,footprint,signer,signature); }
Creates an RRSIG Record from the given data
public boolean contains(EventPoint ep){ return events.contains(ep); }
Determine whether event point already exists within the queue.
private boolean flushAccumulatedRegion(){ boolean success=true; if (accumulatedX != Integer.MAX_VALUE) { SubRegionShowable bsSubRegion=(SubRegionShowable)bufferStrategy; boolean contentsLost=bufferStrategy.contentsLost(); if (!contentsLost) { bsSubRegion.show(accumulatedX,accumulatedY,accumulatedMaxX,accumulatedMaxY); contentsLost=bufferStrategy.contentsLost(); } if (contentsLost) { if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) { LOGGER.finer("endPaint: contents lost"); } bufferInfo.setInSync(false); success=false; } } resetAccumulated(); return success; }
Renders the BufferStrategy to the screen.
public static boolean isGenericStreamPartitionDataElementKey(byte[] key){ return Arrays.equals(key,KLVPacket.GENERIC_STREAM_PARTITION_DATA_ELEMENT_KEY); }
Checks if the key corresponding to the KLV packet is a Generic Stream Partition Data Element key.
public static Command show(String title,Component body,Command... cmds){ return show(title,body,cmds,defaultDialogType,null); }
Shows a modal dialog with the given component as its "body" placed in the center.
static public LexiconKeyOrder valueOf(final int index){ switch (index) { case _TERM2ID: return TERM2ID; case _ID2TERM: return ID2TERM; case _BLOBS: return BLOBS; default : throw new AssertionError(); } }
Returns the singleton corresponding to the <i>index</i>.
public ParserAdapter(Parser parser){ setup(parser); }
Construct a new parser adapter. <p>Note that the embedded parser cannot be changed once the adapter is created; to embed a different parser, allocate a new ParserAdapter.</p>
public static synchronized boolean resolveFully(final PdfObject pdfObject,final PdfFileReader objectReader){ boolean fullyResolved=pdfObject != null; if (fullyResolved) { final byte[] raw; if (pdfObject.getStatus() == PdfObject.DECODED) { raw=StringUtils.toBytes(pdfObject.getObjectRefAsString()); } else { raw=pdfObject.getUnresolvedData(); } pdfObject.setStatus(PdfObject.DECODED); if (raw[0] != 'e' && raw[1] != 'n' && raw[2] != 'd' && raw[3] != 'o' && raw[4] != 'b') { int j=StreamReaderUtils.skipSpacesOrOtherCharacter(raw,0,91); int keyStart=j; j=StreamReaderUtils.skipToEndOfRef(raw,j); final int ref=NumberUtils.parseInt(keyStart,j,raw); j=StreamReaderUtils.skipSpaces(raw,j); keyStart=j; j=StreamReaderUtils.skipToEndOfRef(raw,j); final int generation=NumberUtils.parseInt(keyStart,j,raw); if (raw[raw.length - 1] == 'R') { fullyResolved=resolveFullyChildren(pdfObject,fullyResolved,raw,ref,generation,objectReader); } if (fullyResolved) { pdfObject.ignoreRecursion(false); final ObjectDecoder objDecoder=new ObjectDecoder(objectReader); objDecoder.readDictionaryAsObject(pdfObject,j,raw); } } } return fullyResolved; }
used by linearization to check object fully fully available and return false if not
public static BlockSnapshot checkSnapShotExistsInDB(String nativeGuid,DbClient dbClient){ List<BlockSnapshot> activeSnapshots=CustomQueryUtility.getActiveBlockSnapshotByNativeGuid(dbClient,nativeGuid); Iterator<BlockSnapshot> snapshotItr=activeSnapshots.iterator(); return snapshotItr.hasNext() ? snapshotItr.next() : null; }
Check if the given native GUID String exists in the database for a BlockSnapshot object.
public List<Message> retrieveAll(){ while (!atEnd && retrieve() != null) { } return queued; }
Gets all available Messages. Can be called multiple times and always returns the full set
private static void printUrlDestinationDetails(UrlDestinationDetails destinationDetails){ System.out.println("Goal Url: " + destinationDetails.getUrl()); System.out.println("Case Sensitive: " + destinationDetails.getCaseSensitive()); System.out.println("Match Type: " + destinationDetails.getMatchType()); System.out.println("First Step Required: " + destinationDetails.getFirstStepRequired()); if (destinationDetails.getSteps() != null) { System.out.println("Goal Steps: "); for ( Steps step : destinationDetails.getSteps()) { System.out.println("Step Number: " + step.getNumber()); System.out.println("Name: " + step.getName()); System.out.println("URL: " + step.getUrl()); } } else { System.out.println("No Steps Configured"); } }
Prints details for URL_DESTINATION type goals. Each of these goals might have one or more goal steps configured. If any are present, they are printed.
private static MosaicLevy createZeroMosaicLevy(){ return new MosaicLevy(MosaicTransferFeeType.Absolute,MosaicConstants.MOSAIC_CREATION_FEE_SINK,MosaicConstants.MOSAIC_ID_XEM,Quantity.ZERO); }
Creates a mosaic levy that has zero fee.
public void moveEntries(ByteString fromNamespace,ByteString toNamespace){ if (fromNamespace == null || toNamespace == null || !contents.containsKey(fromNamespace)) { return; } if (!contents.containsKey(toNamespace)) { contents.put(toNamespace,contents.remove(fromNamespace)); } else { contents.get(toNamespace).putAll(contents.remove(fromNamespace)); } }
Move key-value pairs from one namespace to another.
private Cache createCache() throws TimeoutException, CacheWriterException, GatewayException, CacheExistsException, RegionExistsException { return new CacheFactory().set(MCAST_PORT,"0").create(); }
create the cache
public boolean containsKey(Object key){ int index=hashCode(key), length=this.keyTable.length; while (this.keyTable[index] != null) { if (this.keyTable[index] == key) return true; if (++index == length) { index=0; } } return false; }
Returns true if the collection contains an element for the key.
public static void main(String[] args) throws IOException { boolean enableOutput=true; boolean outputToFile=false; String inputFolder=""; String outputFolder=""; String workload="random"; String vmAllocationPolicy="lrr"; String vmSelectionPolicy="mu"; String parameter="1.2"; new RandomRunner(enableOutput,outputToFile,inputFolder,outputFolder,workload,vmAllocationPolicy,vmSelectionPolicy,parameter); }
The main method.
public JsonArrayRequest(String url,Listener<JSONArray> listener,ErrorListener errorListener){ super(Method.GET,url,listener,errorListener); }
Creates a new request.
protected Object copyObject(Object source){ Object result=null; try { result=GenericObjectEditor.makeCopy(source); setCancelButton(true); } catch ( Exception ex) { setCancelButton(false); Logger.log(weka.core.logging.Logger.Level.WARNING,"GenericObjectEditor: Problem making backup object"); Logger.log(weka.core.logging.Logger.Level.WARNING,ex); } return result; }
Makes a copy of an object using serialization.
private void checkMaxRows(int resultSetType,int resultSetConcurrency) throws SQLException { prepareTestData(); try (Statement stmt=con.createStatement(resultSetType,resultSetConcurrency)){ stmt.setMaxRows(2); try (ResultSet rs=stmt.executeQuery(SELECT_DATA)){ assertTrue("Expected a row",rs.next()); assertEquals("Unexpected value for first row",0,rs.getInt(1)); assertTrue("Expected a row",rs.next()); assertEquals("Unexpected value for second row",1,rs.getInt(1)); assertFalse("Expected only two rows in ResultSet",rs.next()); } } }
Checks if the maxRows property is correctly applied to result sets of the specified type and concurrency.
@Override public int hashCode(){ return Objects.hashCode(value); }
Returns the hash code value of the present value, if any, or 0 (zero) if no value is present.
@Override protected void keyTyped(char par1,int par2){ commandBox.textboxKeyTyped(par1,par2); }
Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
private void assertCostReceiptReversal(CostResult costResult,int M_InOutLine_ID,MAcctSchema as,String trxName){ MCost cost=assertCost(costResult); String whereClause="M_Product_ID=? AND M_CostElement_ID=? AND M_CostType_ID=? AND M_InOutLine_ID=?"; ArrayList<Object> parameters=new ArrayList(); parameters.add(costResult.M_Product_ID); parameters.add(cost.getM_CostElement_ID()); parameters.add(cost.getM_CostType_ID()); parameters.add(M_InOutLine_ID); assertCostDetail(costResult,whereClause,parameters); }
assert Cost Receipt
@Override public void process(KeyValPair<K,V> tuple){ K key=tuple.getKey(); V tval=tuple.getValue(); if (!doprocessKey(key) || (tval == null)) { return; } V val=mins.get(key); if (val == null) { mins.put(cloneKey(key),tval); } else if (val.doubleValue() > tval.doubleValue()) { mins.put(key,tval); } }
For each key, updates the hash if the new value is a new min.
@RequestProcessing(value="/activity/1A0001/collect",method=HTTPRequestMethod.POST) @Before(adviceClass={StopwatchStartAdvice.class,LoginCheck.class,Activity1A0001CollectValidation.class}) @After(adviceClass=StopwatchEndAdvice.class) public void collect1A0001(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception { final JSONObject currentUser=(JSONObject)request.getAttribute(User.USER); final String userId=currentUser.optString(Keys.OBJECT_ID); final JSONObject ret=activityMgmtService.collect1A0001(userId); context.renderJSON(ret); }
Collects 1A0001.
public void addPropertiesFromFileList(String source,String propFiles) throws IOException { if (StringUtils.isEmpty(propFiles)) { return; } s_log.info("Trying to load {} config properties from files specified by {}: [{}]",m_category.getCategoryName(),source,propFiles); List<URI> uris=new ArrayList<URI>(); for ( String file : StringUtils.split(propFiles,",")) { file=file.trim(); uris.add(URI.create(file)); } addProperties(uris); }
Comma delimited files in order of precedence
private boolean readEqualsSign(){ skipWhitespace(); if (pos < input.length() && input.charAt(pos) == '=') { pos++; return true; } return false; }
Returns true if an equals sign was read and consumed.
public void appendChannel(YouTubeChannel channel){ append(channel); }
Append channel to this adapter.
static boolean compareLocaleNames(Locale locale,String name){ return name.equalsIgnoreCase(locale.toString()) || name.equalsIgnoreCase(getName(locale)); }
Compare name name of the locale with the given name. The case of the name is ignored.
public BedReader(BufferedReader in,int minAnnotations) throws IOException { mMinAnnotations=minAnnotations; mIn=new BrLineReader(in); mHeader=parseHeader(mIn); }
create a new BED reader with a minimum number of annotations
public JSONException(final Throwable cause){ super(cause.getMessage(),cause); }
Constructs a new JSONException with the specified cause.
public MethodNotFoundException(String methodName){ super("Method " + methodName + " without arguments not found"); }
Creates exception with given method name
public Cursor fetchWordSet(String thelang){ return mDb.query(TABLE_LEXIS,new String[]{_ROWID,KEY_LANG_ROOTWORD,KEY_LANG_LANGUAGE,KEY_LANG_ENGLISHTRANS,KEY_GAME_DIFFICULTY},KEY_LANG_LANGUAGE + " = " + "'"+ thelang+ "'",null,null,null,null); }
Fetch All Language Game Words
public double doOperation() throws OperatorFailedException { double logP=colouringModel.getTreeColouringWithProbability().getLogProbabilityDensity(); double logq; NodeRef i, newParent, newChild; do { i=tree.getNode(MathUtils.nextInt(tree.getNodeCount())); } while (tree.getRoot() == i); NodeRef iP=tree.getParent(i); NodeRef CiP=getOtherChild(tree,iP,i); NodeRef PiP=tree.getParent(iP); double delta=getDelta(); double oldHeight=tree.getNodeHeight(iP); double newHeight=oldHeight + delta; if (delta > 0) { if (PiP != null && tree.getNodeHeight(PiP) < newHeight) { newParent=PiP; newChild=iP; while (tree.getNodeHeight(newParent) < newHeight) { newChild=newParent; newParent=tree.getParent(newParent); if (newParent == null) break; } tree.beginTreeEdit(); if (tree.isRoot(newChild)) { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.setRoot(iP); } else { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.addChild(newParent,iP); } tree.setNodeHeight(iP,newHeight); tree.endTreeEdit(); int possibleSources=intersectingEdges(tree,newChild,oldHeight,null); logq=Math.log(1.0 / (double)possibleSources); } else { tree.setNodeHeight(iP,newHeight); logq=0.0; } } else { if (tree.getNodeHeight(i) > newHeight) { return Double.NEGATIVE_INFINITY; } if (tree.getNodeHeight(CiP) > newHeight) { List<NodeRef> newChildren=new ArrayList<NodeRef>(); int possibleDestinations=intersectingEdges(tree,CiP,newHeight,newChildren); if (newChildren.size() == 0) { return Double.NEGATIVE_INFINITY; } int childIndex=MathUtils.nextInt(newChildren.size()); newChild=newChildren.get(childIndex); newParent=tree.getParent(newChild); tree.beginTreeEdit(); if (tree.isRoot(iP)) { tree.removeChild(iP,CiP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(newParent,iP); tree.setRoot(CiP); } else { tree.removeChild(iP,CiP); tree.removeChild(PiP,iP); tree.removeChild(newParent,newChild); tree.addChild(iP,newChild); tree.addChild(PiP,CiP); tree.addChild(newParent,iP); } tree.setNodeHeight(iP,newHeight); tree.endTreeEdit(); logq=Math.log((double)possibleDestinations); } else { tree.setNodeHeight(iP,newHeight); logq=0.0; } } if (swapRates) { NodeRef j=tree.getNode(MathUtils.nextInt(tree.getNodeCount())); if (j != i) { double tmp=tree.getNodeRate(i); tree.setNodeRate(i,tree.getNodeRate(j)); tree.setNodeRate(j,tmp); } } if (swapTraits) { NodeRef j=tree.getNode(MathUtils.nextInt(tree.getNodeCount())); if (j != i) { double tmp=tree.getNodeTrait(i,"trait"); tree.setNodeTrait(i,"trait",tree.getNodeTrait(j,"trait")); tree.setNodeTrait(j,"trait",tmp); } } if (logq == Double.NEGATIVE_INFINITY) throw new OperatorFailedException("invalid slide"); colouringModel.resample(); double logQ=colouringModel.getTreeColouringWithProbability().getLogProbabilityDensity(); return logq + logP - logQ; }
Do a probablistic subtree slide move.
public ScannerException(File file,ErrorMessages message,int line,int column){ this(file,ErrorMessages.get(message),message,line,column); }
Creates a new ScannerException with a message, line number and column.
@Override public IAgent lastValue(final IScope scope) throws GamaRuntimeException { if (populationSets.size() == 0) { return null; } return populationSets.get(populationSets.size() - 1).lastValue(scope); }
Method last()
public static void checkMADS(Metadata metadata,String producer,String owner,String application,long classId,long labelsId) throws WarpException { if (!loaded) { return; } Long oProducerLimit=producerMADSLimits.get(producer); Long oApplicationLimit=applicationMADSLimits.get(application); if (null == oProducerLimit) { oProducerLimit=DEFAULT_MADS_PRODUCER; if (-1 == oProducerLimit && null == oApplicationLimit) { return; } else if (0 == oProducerLimit) { Map<String,String> labels=new HashMap<String,String>(); labels.put(SensisionConstants.SENSISION_LABEL_PRODUCER,producer); StringBuilder sb=new StringBuilder(); sb.append("Geo Time Series "); GTSHelper.metadataToString(sb,metadata.getName(),metadata.getLabels()); sb.append(" would exceed your Monthly Active Data Streams limit ("); sb.append(oProducerLimit); sb.append(")."); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS,labels,1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS_GLOBAL,Sensision.EMPTY_LABELS,1); throw new WarpException(sb.toString()); } oProducerLimit=(long)Math.ceil(oProducerLimit * toleranceRatio); } long producerLimit=oProducerLimit; HyperLogLogPlus producerHLLP; synchronized (producerHLLPEstimators) { producerHLLP=producerHLLPEstimators.get(producer); if (null == producerHLLP || producerHLLP.hasExpired()) { producerHLLP=new HyperLogLogPlus(DEFAULT_P,DEFAULT_PPRIME); try { producerHLLP.toNormal(); } catch ( IOException ioe) { throw new WarpException(ioe); } producerHLLP.setKey(producer); producerHLLPEstimators.put(producer,producerHLLP); } } long hash=GTSHelper.gtsId(SIP_KEYS,classId,labelsId); boolean newForProducer=producerHLLP.isNew(hash); if (!newForProducer && null == oApplicationLimit) { return; } HyperLogLogPlus applicationHLLP=null; long applicationLimit=Long.MIN_VALUE; if (null != oApplicationLimit) { applicationLimit=oApplicationLimit; synchronized (applicationHLLPEstimators) { applicationHLLP=applicationHLLPEstimators.get(application); if (null == applicationHLLP || applicationHLLP.hasExpired()) { applicationHLLP=new HyperLogLogPlus(DEFAULT_P,DEFAULT_PPRIME); try { applicationHLLP.toNormal(); } catch ( IOException ioe) { throw new WarpException(ioe); } applicationHLLP.setKey(APPLICATION_PREFIX_CHAR + application); applicationHLLPEstimators.put(application,applicationHLLP); } } } if (null != applicationHLLP) { if (!applicationHLLP.isNew(hash)) { return; } try { long cardinality=applicationHLLP.cardinality(); Map<String,String> labels=new HashMap<String,String>(); labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION,application); if (cardinality > applicationLimit) { StringBuilder sb=new StringBuilder(); sb.append("Geo Time Series "); GTSHelper.metadataToString(sb,metadata.getName(),metadata.getLabels()); sb.append(" would exceed your Monthly Active Data Streams limit for application '" + application + "' ("); sb.append((long)Math.floor(applicationLimit / toleranceRatio)); sb.append(")."); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS_PER_APP,labels,1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS_PER_APP_GLOBAL,Sensision.EMPTY_LABELS,1); throw new WarpException(sb.toString()); } applicationHLLP.aggregate(hash); Sensision.set(SensisionConstants.SENSISION_CLASS_CONTINUUM_GTS_DISTINCT_PER_APP,labels,applicationHLLP.cardinality()); } catch ( IOException ioe) { } } try { long cardinality=producerHLLP.cardinality(); Map<String,String> labels=new HashMap<String,String>(); labels.put(SensisionConstants.SENSISION_LABEL_PRODUCER,producer); if (cardinality > producerLimit) { StringBuilder sb=new StringBuilder(); sb.append("Geo Time Series "); GTSHelper.metadataToString(sb,metadata.getName(),metadata.getLabels()); sb.append(" would exceed your Monthly Active Data Streams limit ("); sb.append((long)Math.floor(producerLimit / toleranceRatio)); sb.append(")."); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS,labels,1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_THROTTLING_GTS_GLOBAL,Sensision.EMPTY_LABELS,1); throw new WarpException(sb.toString()); } producerHLLP.aggregate(hash); Sensision.set(SensisionConstants.SENSISION_CLASS_CONTINUUM_GTS_DISTINCT,labels,producerHLLP.cardinality()); } catch ( IOException ioe) { } }
Check compatibility of a GTS with the current MADS limit
private static void init(String args[]) throws FileNotFoundException, IOException { System.out.println("Init program ..."); source1=args[0]; System.out.println("Set working directory to: " + source1); File folder=new File(source1); fileList1=folder.listFiles(new TabFilter()); if (args.length == 3) { System.out.println("Detected multiple data set"); isSingleDataSet=false; source2=args[1]; System.out.println("Set second working directory to: " + source2); folder=new File(source2); fileList2=folder.listFiles(new TabFilter()); if (!dataSetsAreOk()) System.exit(-1); zone_id=Integer.parseInt(args[2]); } else zone_id=Integer.parseInt(args[1]); zone_id_tmp=zone_id; System.out.println("... finished init."); }
init variables
public static int[] shuffle(int[] intArray){ if (intArray == null) { return null; } return shuffle(intArray,getRandom(intArray.length)); }
Shuffling algorithm, Randomly permutes the specified int array using a default source of randomness
public WriterMultiplier(Writer[] writer){ this.writer=writer; }
Creates a new writer multiplier.
private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix,boolean isHorizontal){ int penalty=0; int iLimit=isHorizontal ? matrix.getHeight() : matrix.getWidth(); int jLimit=isHorizontal ? matrix.getWidth() : matrix.getHeight(); byte[][] array=matrix.getArray(); for (int i=0; i < iLimit; i++) { int numSameBitCells=0; int prevBit=-1; for (int j=0; j < jLimit; j++) { int bit=isHorizontal ? array[i][j] : array[j][i]; if (bit == prevBit) { numSameBitCells++; } else { if (numSameBitCells >= 5) { penalty+=N1 + (numSameBitCells - 5); } numSameBitCells=1; prevBit=bit; } } if (numSameBitCells > 5) { penalty+=N1 + (numSameBitCells - 5); } } return penalty; }
Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both vertical and horizontal orders respectively.
protected void rereadFile(){ try { editor.read(new FileReader(shownFile),shownFile); editor.setFont(new Font("Verdana",Font.PLAIN,13)); editor.getDocument().putProperty(PlainDocument.tabSizeAttribute,new Integer(2)); Document doc=editor.getDocument(); doc.addDocumentListener(new XMLListener()); doc.addUndoableEditListener((UndoRedoAction)editor.getActionMap().get("Undo")); editor.requestFocus(); editor.requestFocusInWindow(); } catch ( IOException e) { log.severe("cannot read xml file: " + e); } }
Reads the xml file in the object variable 'shownFile' and displays its content in the editor pane.
public boolean isBorderOpaque(){ return false; }
This default implementation returns false.
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public static void updateBarsColor(Window src,Window dest){ updateBarsColor(src.getStatusBarColor(),dest,false); }
LOLLIPOP ONLY Apply the color of one window to another
public void enableDashedLine(float lineLength,float spaceLength,float phase){ mDashPathEffect=new DashPathEffect(new float[]{lineLength,spaceLength},phase); }
Enables the line to be drawn in dashed mode, e.g. like this "- - - - - -". THIS ONLY WORKS IF HARDWARE-ACCELERATION IS TURNED OFF. Keep in mind that hardware acceleration boosts performance.
public void addButton(Button button){ addComponentsLeft(button); }
alias for addComponentsLeft for ease of porting swing form
@Override public String toString(){ if (Type.LIST.equals(this.type)) { return ("INT_LIST" + ((value.length() != 0) ? (":" + value) : (""))); } else { return (name + ((value.length() != 0) ? (":" + value) : (""))); } }
Returns a string representation of the values associated with this option.
public static boolean testPointTriangle(float pX,float pY,float v0X,float v0Y,float v1X,float v1Y,float v2X,float v2Y){ boolean b1=(pX - v1X) * (v0Y - v1Y) - (v0X - v1X) * (pY - v1Y) < 0.0f; boolean b2=(pX - v2X) * (v1Y - v2Y) - (v1X - v2X) * (pY - v2Y) < 0.0f; if (b1 != b2) return false; boolean b3=(pX - v0X) * (v2Y - v0Y) - (v2X - v0X) * (pY - v0Y) < 0.0f; return b2 == b3; }
Test whether the given point <tt>(pX, pY)</tt> lies inside the triangle with the vertices <tt>(v0X, v0Y)</tt>, <tt>(v1X, v1Y)</tt>, <tt>(v2X, v2Y)</tt>.
public CMSSignedData(Map hashes,byte[] sigBlock) throws CMSException { this(hashes,CMSUtils.readContentInfo(sigBlock)); }
Content with detached signature, digests precomputed
private void readObject(){ }
<!-- begin-user-doc --> Write your own initialization here <!-- end-user-doc -->
private JsonWriter close(int empty,int nonempty,String closeBracket) throws IOException { int context=peek(); if (context != nonempty && context != empty) { throw new IllegalStateException("Nesting problem."); } if (deferredName != null) { throw new IllegalStateException("Dangling name: " + deferredName); } stackSize--; if (context == nonempty) { newline(); } out.write(closeBracket); return this; }
Closes the current scope by appending any necessary whitespace and the given bracket.
public static synchronized void reportUnhealthyContentServer(String address){ for ( HostInfo hostInfo : _hostInfos) { for (int i=0; i < hostInfo.addresses.length; i++) { if (hostInfo.addresses[i].equals(address)) { if (hostInfo.commFailureTimes[i] == 0) System.out.println("SERVER: detected unhealthy content-server: " + address); hostInfo.commFailureTimes[i]=System.currentTimeMillis(); break; } } } }
Reporting an unhealthy content-server. The reported content server will not be accessed for a few minutes, unless all content-servers are unhealthy.
public AccountExternalId(final Account.Id who,final AccountExternalId.Key k){ accountId=who; key=k; }
Create a new binding to an external identity.
public void test_sortLjava_util_ListLjava_util_Comparator(){ Comparator comp=new ReversedMyIntComparator(); try { Collections.sort(null,comp); fail("Expected NullPointerException for null list parameter"); } catch ( NullPointerException e) { } Collections.shuffle(myll); Collections.sort(myll,comp); final int llSize=myll.size(); for (int counter=0; counter < llSize - 1; counter++) { assertTrue("Sorting shuffled list with custom comparator resulted in unsorted list",((MyInt)myll.get(counter)).compareTo((MyInt)myll.get(counter + 1)) >= 0); } ArrayList al=new ArrayList(); al.add("String"); al.add(new Integer(1)); al.add(new Double(3.14)); try { Collections.sort(al,comp); fail("ClassCastException expected"); } catch ( ClassCastException e) { } Mock_ArrayList mal=new Mock_ArrayList(); mal.add(new MyInt(1)); mal.add(new MyInt(2)); try { Collections.sort(mal,comp); fail("UnsupportedOperationException expected"); } catch ( UnsupportedOperationException e) { } }
java.util.Collections#sort(java.util.List, java.util.Comparator)