idx
int64
0
34.9k
question
stringlengths
12
26.4k
target
stringlengths
15
2.3k
300
public static Path createTempFile ( String prefix , String suffix ) throws IOException { Path tempDirPath = Paths . get ( SystemProperties . getTempFilesPath ( ) ) ; return createTempFile ( tempDirPath , prefix , suffix ) ; }
Creates a temporary file on disk (location specified by SystemProperties.getTempFilesPath()) and returns its path.
301
private synchronized void rebuildJournal ( ) throws IOException { if ( journalWriter != null ) { journalWriter . close ( ) ; } Writer writer = new BufferedWriter ( new FileWriter ( journalFileTmp ) , IO_BUFFER_SIZE ) ; writer . write ( MAGIC ) ; writer . write ( "\n" ) ; writer . write ( VERSION_1 ) ; writer . write ( "\n" ) ; writer . write ( Integer . toString ( appVersion ) ) ; writer . write ( "\n" ) ; writer . write ( Integer . toString ( valueCount ) ) ; writer . write ( "\n" ) ; writer . write ( "\n" ) ; for ( Entry entry : lruEntries . values ( ) ) { if ( entry . currentEditor != null ) { writer . write ( DIRTY + ' ' + entry . key + '\n' ) ; } else { writer . write ( CLEAN + ' ' + entry . key + entry . getLengths ( ) + '\n' ) ; } } writer . close ( ) ; journalFileTmp . renameTo ( journalFile ) ; journalWriter = new BufferedWriter ( new FileWriter ( journalFile , true ) , IO_BUFFER_SIZE ) ; }
Creates a new journal that omits redundant information. This replaces the current journal if it exists.
302
public static short [ ] initializeSubStateArray ( List < Tree < String > > trainTrees , List < Tree < String > > validationTrees , Numberer tagNumberer , short nSubStates ) { short [ ] nSub = new short [ 2 ] ; nSub [ 0 ] = 1 ; nSub [ 1 ] = nSubStates ; StateSetTreeList trainStateSetTrees = new StateSetTreeList ( trainTrees , nSub , true , tagNumberer ) ; @ SuppressWarnings ( "unused" ) StateSetTreeList validationStateSetTrees = new StateSetTreeList ( validationTrees , nSub , true , tagNumberer ) ; StateSetTreeList . initializeTagNumberer ( trainTrees , tagNumberer ) ; StateSetTreeList . initializeTagNumberer ( validationTrees , tagNumberer ) ; short numStates = ( short ) tagNumberer . total ( ) ; short [ ] nSubStateArray = new short [ numStates ] ; Arrays . fill ( nSubStateArray , nSubStates ) ; nSubStateArray [ 0 ] = 1 ; return nSubStateArray ; }
Convert a single Tree[String] to Tree[StateSet]
303
public void addPropertyChangeListener ( PropertyChangeListener listener ) { propertyChangeSupport . addPropertyChangeListener ( listener ) ; }
Add a PropertyChangeListener to the listener list.
304
public PluginDescriptionFile ( final String pluginName , final String pluginVersion , final String mainClass ) { name = pluginName . replace ( ' ' , '_' ) ; version = pluginVersion ; main = mainClass ; }
Creates a new PluginDescriptionFile with the given detailed
305
public void fill ( Graphics2D g , Shape s ) { Rectangle bounds = s . getBounds ( ) ; int width = bounds . width ; int height = bounds . height ; BufferedImage bimage = Effect . createBufferedImage ( width , height , true ) ; Graphics2D gbi = bimage . createGraphics ( ) ; gbi . setColor ( Color . BLACK ) ; gbi . fill ( s ) ; g . drawImage ( applyEffect ( bimage , null , width , height ) , 0 , 0 , null ) ; }
Paint the effect based around a solid shape in the graphics supplied.
306
public void silentClear ( ) { mSelectedWidgets . clear ( ) ; mModifiedWidgets . clear ( ) ; }
Clear the selection without warning listeners
307
public static boolean isArray ( Element arrayE ) { String name = arrayE . getTagName ( ) ; if ( name . equals ( "Array" ) || name . equals ( "NUM-ARRAY" ) || name . equals ( "INT-ARRAY" ) || name . equals ( "REAL-ARRAY" ) || name . equals ( "STRING-ARRAY" ) || isSparseArray ( arrayE ) ) { return true ; } return false ; }
Utility method to check if an XML element is an array.
308
public void addNotificationListener ( ObjectName name , NotificationListener listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException { mbsInterceptor . addNotificationListener ( cloneObjectName ( name ) , listener , filter , handback ) ; }
Adds a listener to a registered MBean.
309
static long readVarLong ( InputStream in ) throws IOException { long x = in . read ( ) ; if ( x < 0 ) { throw new EOFException ( ) ; } x = ( byte ) x ; if ( x >= 0 ) { return x ; } x &= 0x7f ; for ( int s = 7 ; s < 64 ; s += 7 ) { long b = in . read ( ) ; if ( b < 0 ) { throw new EOFException ( ) ; } b = ( byte ) b ; x |= ( b & 0x7f ) << s ; if ( b >= 0 ) { break ; } } return x ; }
Read a variable size long value.
310
public void addFillOutsideLine ( FillOutsideLine fill ) { mFillBelowLine . add ( fill ) ; }
Sets if the line chart should be filled outside its line. Filling outside with FillOutsideLine.INTEGRAL the line transforms a line chart into an area chart.
311
public static Builder createBuilder ( AbstractManagedObjectDefinition < ? , ? > d , String propertyName ) { return new Builder ( d , propertyName ) ; }
Create a ACI property definition builder.
312
public void filter ( File inputFile , PrintWriter o ) throws IOException { BufferedWriter bw = new BufferedWriter ( o ) ; StringBuffer sb = ( StringBuffer ) fileMap . get ( inputFile . toString ( ) ) ; if ( sb == null ) { sb = loadFile ( inputFile ) ; } filter ( sb , bw ) ; bw . flush ( ) ; }
Filters data from file.
313
public int update ( String sql , StatementVisitor visitor ) throws SQLException { Connection connection = null ; PreparedStatement stmt = null ; try { connection = source . getConnection ( ) ; stmt = connection . prepareStatement ( sql ) ; visitor . visit ( stmt ) ; return stmt . executeUpdate ( ) ; } finally { SQLUtil . closeQuietly ( stmt ) ; SQLUtil . closeQuietly ( connection ) ; } }
Perform SQL update statement. If the SQL string contains ? placeholders, use the StatementVisitor to update the PreparedStatement with actual values.
314
public void stop ( ) { logger . info ( "Cassandra shutting down..." ) ; if ( thriftServer != null ) thriftServer . stop ( ) ; if ( nativeServer != null ) nativeServer . stop ( ) ; if ( FBUtilities . isWindows ( ) ) System . exit ( 0 ) ; if ( jmxServer != null ) { try { jmxServer . stop ( ) ; } catch ( IOException e ) { logger . error ( "Error shutting down local JMX server: " , e ) ; } } }
Stop the daemon, ideally in an idempotent manner. Hook for JSVC / Procrun
315
private void compileMethod ( HotSpotResolvedJavaMethod method , int counter ) { try { long start = System . currentTimeMillis ( ) ; long allocatedAtStart = MemUseTrackerImpl . getCurrentThreadAllocatedBytes ( ) ; int entryBCI = JVMCICompiler . INVOCATION_ENTRY_BCI ; HotSpotCompilationRequest request = new HotSpotCompilationRequest ( method , entryBCI , 0L ) ; boolean useProfilingInfo = false ; boolean installAsDefault = false ; CompilationTask task = new CompilationTask ( jvmciRuntime , compiler , request , useProfilingInfo , installAsDefault ) ; task . runCompilation ( ) ; HotSpotInstalledCode installedCode = task . getInstalledCode ( ) ; if ( installedCode != null ) { installedCode . invalidate ( ) ; } memoryUsed . getAndAdd ( MemUseTrackerImpl . getCurrentThreadAllocatedBytes ( ) - allocatedAtStart ) ; compileTime . getAndAdd ( System . currentTimeMillis ( ) - start ) ; compiledMethodsCounter . incrementAndGet ( ) ; } catch ( Throwable t ) { println ( "CompileTheWorld (%d) : Error compiling method: %s" , counter , method . format ( "%H.%n(%p):%r" ) ) ; printStackTrace ( t ) ; } }
Compiles a method and gathers some statistics.
316
private static void doCopyDirectory ( File srcDir , File destDir , FileFilter filter , boolean preserveFileDate , List < String > exclusionList ) throws IOException { File [ ] srcFiles = filter == null ? srcDir . listFiles ( ) : srcDir . listFiles ( filter ) ; if ( srcFiles == null ) { throw new IOException ( "Failed to list contents of " + srcDir ) ; } if ( destDir . exists ( ) ) { if ( destDir . isDirectory ( ) == false ) { throw new IOException ( "Destination '" + destDir + "' exists but is not a directory" ) ; } } else { if ( ! destDir . mkdirs ( ) && ! destDir . isDirectory ( ) ) { throw new IOException ( "Destination '" + destDir + "' directory cannot be created" ) ; } } if ( destDir . canWrite ( ) == false ) { throw new IOException ( "Destination '" + destDir + "' cannot be written to" ) ; } for ( File srcFile : srcFiles ) { File dstFile = new File ( destDir , srcFile . getName ( ) ) ; if ( exclusionList == null || ! exclusionList . contains ( srcFile . getCanonicalPath ( ) ) ) { if ( srcFile . isDirectory ( ) ) { doCopyDirectory ( srcFile , dstFile , filter , preserveFileDate , exclusionList ) ; } else { doCopyFile ( srcFile , dstFile , preserveFileDate ) ; } } } if ( preserveFileDate ) { destDir . setLastModified ( srcDir . lastModified ( ) ) ; } }
Internal copy directory method.
317
public int processByte ( byte in , byte [ ] out , int outOff ) throws DataLengthException , IllegalStateException { int resultLen = 0 ; if ( bufOff == buf . length ) { resultLen = cipher . processBlock ( buf , 0 , out , outOff ) ; System . arraycopy ( buf , blockSize , buf , 0 , blockSize ) ; bufOff = blockSize ; } buf [ bufOff ++ ] = in ; return resultLen ; }
process a single byte, producing an output block if necessary.
318
public EsriShapeExport ( EsriGraphicList list , DbfTableModel dbf , String pathToFile ) { setGraphicList ( list ) ; setMasterDBF ( dbf ) ; filePath = pathToFile ; DEBUG = logger . isLoggable ( Level . FINE ) ; }
Create an EsriShapeExport object.
319
void saveOffsetInExternalStore ( String topic , int partition , long offset ) { try { FileWriter writer = new FileWriter ( storageName ( topic , partition ) , false ) ; BufferedWriter bufferedWriter = new BufferedWriter ( writer ) ; bufferedWriter . write ( offset + "" ) ; bufferedWriter . flush ( ) ; bufferedWriter . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } }
Overwrite the offset for the topic in an external storage.
320
private CentroidClusterModel assinePoints ( CentroidClusterModel model ) { double [ ] values = new double [ attributes . size ( ) ] ; int i = 0 ; for ( Example example : exampleSet ) { double [ ] exampleValues = getAsDoubleArray ( example , attributes , values ) ; double nearestDistance = measure . calculateDistance ( model . getCentroidCoordinates ( 0 ) , exampleValues ) ; int nearestIndex = 0 ; int id = 0 ; for ( Centroid cr : model . getCentroids ( ) ) { double distance = measure . calculateDistance ( cr . getCentroid ( ) , exampleValues ) ; if ( distance < nearestDistance ) { nearestDistance = distance ; nearestIndex = id ; } id ++ ; } centroidAssignments [ i ] = nearestIndex ; i ++ ; } model . setClusterAssignments ( centroidAssignments , exampleSet ) ; return model ; }
assign the Points to cluster
321
public static String formatQuantity ( BigDecimal quantity ) { if ( quantity == null ) return "" ; else return quantityDecimalFormat . format ( quantity ) ; }
Formats an BigDecimal representing a quantity into a string
322
public void importPKCS8 ( BurpCertificate certificate , String filename ) { setStatus ( "Importing private key..." ) ; FileInputStream fis ; File file = new File ( filename ) ; PrivateKey privateKey ; try { fis = new FileInputStream ( file ) ; DataInputStream dis = new DataInputStream ( fis ) ; byte [ ] keyBytes = new byte [ ( int ) file . length ( ) ] ; dis . readFully ( keyBytes ) ; dis . close ( ) ; PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec ( keyBytes ) ; KeyFactory keyFactory = KeyFactory . getInstance ( "RSA" ) ; privateKey = keyFactory . generatePrivate ( keySpec ) ; certificate . setPrivateKey ( privateKey ) ; setCertificateTree ( ) ; setStatus ( "Private Key imported." ) ; } catch ( IOException | NoSuchAlgorithmException | InvalidKeySpecException e ) { setStatus ( "Error importing private Key. (" + e . getMessage ( ) + ")" ) ; e . printStackTrace ( ) ; } catch ( Exception e ) { setStatus ( "Error (" + e . getMessage ( ) + ")" ) ; } }
Import a private Key in PKCS8 format in DER format.
323
public Collection < Object > undo ( ) { HashSet < Object > modifiedObjects = null ; boolean done = false ; while ( ( indexOfNextAdd > 0 ) && ! done ) { List < mxUndoableEdit > edits = history . get ( -- indexOfNextAdd ) ; for ( int i = edits . size ( ) - 1 ; i >= 0 ; i -- ) { mxUndoableEdit edit = edits . get ( i ) ; edit . undo ( ) ; modifiedObjects = edit . getAffectedObjects ( ) ; if ( edit . isSignificant ( ) ) { fireEvent ( new mxEventObject ( mxEvent . UNDO , "edit" , edit ) ) ; done = true ; } } } return modifiedObjects ; }
Undoes the last change.
324
public TeXParser ( String parseString , TeXFormula formula ) { this ( parseString , formula , true ) ; }
Create a new TeXParser
325
public static < T > TreeNode < T > copy ( TreeDef < T > treeDef , T root ) { return copy ( treeDef , root , Function . identity ( ) ) ; }
Creates a hierarchy of TreeNodes that copies the structure and content of the given tree.
326
protected void drawWithOffset ( float zone , int pointsRight , int pointsLeft , float fixedPoints , Canvas canvas , Paint paint ) { int position = getPositionForZone ( zone ) ; int firstPosition = ( int ) ( position - pointsLeft - fixedPoints ) ; int lastPosition = ( int ) ( position + pointsRight + fixedPoints ) ; if ( lastPosition > pointsNumber - 1 && lastPosition != pointsNumber ) { int offset = lastPosition - pointsNumber - 1 ; float [ ] pointsF = getArrayFloat ( points . subList ( 0 , offset ) ) ; lastPosition = pointsNumber - 1 ; canvas . drawPoints ( pointsF , paint ) ; } if ( firstPosition < 0 ) { int offset = Math . abs ( firstPosition ) ; float [ ] pointsF = getArrayFloat ( points . subList ( ( pointsNumber - 1 ) - offset , pointsNumber - 1 ) ) ; canvas . drawPoints ( pointsF , paint ) ; firstPosition = 0 ; } float [ ] pointsF = getArrayFloat ( points . subList ( firstPosition , lastPosition ) ) ; canvas . drawPoints ( pointsF , paint ) ; }
Paint a line with a offset for right and left
327
static String calculateNthPercentile ( List < String > values , int n ) { String [ ] valuesArr = new String [ values . size ( ) ] ; valuesArr = values . toArray ( valuesArr ) ; Arrays . sort ( valuesArr ) ; int ordinalRank = ( int ) Math . ceil ( n * values . size ( ) / 100.0 ) ; return valuesArr [ ordinalRank - 1 ] ; }
Calculates nth percentile of a set of values using the Nearest Neighbor Method.
328
private void boundsChanged ( ) { if ( runLaterPending ) return ; runLaterPending = true ; Platform . runLater ( null ) ; }
Remembers the window bounds when the window is not iconified, maximized or in fullScreen.
329
public void clear ( ) { synchronized ( lock ) { File [ ] files = cachePath . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { removeFile ( file ) ; } pendingTasks . clear ( ) ; } }
Gets rid of all pending commands.
330
@ Nullable protected abstract URL resolveTestData ( String name ) ;
Resolves a test data name relative to the root of all test data, returning a URL to represent it.
331
public static boolean isFullAccessibleField ( JField field , JClassType clazz ) { return field . isPublic ( ) || hasGetAndSetMethods ( field , clazz ) ; }
Verify if the given field is fully accessible.
332
public byte [ ] convert ( byte [ ] inBuffer , int size ) { byte [ ] result = null ; if ( inBuffer != null ) { DrmConvertedStatus convertedStatus = null ; try { if ( size != inBuffer . length ) { byte [ ] buf = new byte [ size ] ; System . arraycopy ( inBuffer , 0 , buf , 0 , size ) ; convertedStatus = mDrmClient . convertData ( mConvertSessionId , buf ) ; } else { convertedStatus = mDrmClient . convertData ( mConvertSessionId , inBuffer ) ; } if ( convertedStatus != null && convertedStatus . statusCode == DrmConvertedStatus . STATUS_OK && convertedStatus . convertedData != null ) { result = convertedStatus . convertedData ; } } catch ( IllegalArgumentException e ) { Log . w ( TAG , "Buffer with data to convert is illegal. Convertsession: " + mConvertSessionId , e ) ; } catch ( IllegalStateException e ) { Log . w ( TAG , "Could not convert data. Convertsession: " + mConvertSessionId , e ) ; } } else { throw new IllegalArgumentException ( "Parameter inBuffer is null" ) ; } return result ; }
Convert a buffer of data to protected format.
333
public void simulateMethod ( SootMethod method , ReferenceVariable thisVar , ReferenceVariable returnVar , ReferenceVariable params [ ] ) { String subSignature = method . getSubSignature ( ) ; if ( subSignature . equals ( "java.lang.Process execInternal(java.lang.String[],java.lang.String[],java.lang.String)" ) ) { java_lang_Runtime_execInternal ( method , thisVar , returnVar , params ) ; return ; } else { defaultMethod ( method , thisVar , returnVar , params ) ; return ; } }
Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures.
334
@ Deprecated private static void makeJSForInlineSubmit ( Appendable writer , Map < String , Object > context , ModelForm modelForm , String hiddenFormName ) throws IOException { List < ModelFormField > rowSubmitFields = modelForm . getMultiSubmitFields ( ) ; if ( rowSubmitFields != null ) { writer . append ( "<script type=\"text/javascript\">\r\n" ) ; writer . append ( "jQuery(document).ready(function() {\r\n" ) ; writer . append ( "\tvar submitForm = $(\"form[name=" + hiddenFormName + "]\");\r\n" ) ; writer . append ( "\tif (submitForm) {\r\n" ) ; for ( ModelFormField rowSubmitField : rowSubmitFields ) { writer . append ( "\t\tvar id = $(\"[id^=" + rowSubmitField . getCurrentContainerId ( context ) + "]\");\r\n" ) ; writer . append ( "\t\t$(id).click(function(e) {\r\n" ) ; writer . append ( "\t\te.preventDefault();\r\n" ) ; makeHiddenFieldsForHiddenForm ( writer ) ; writer . append ( "\t\t\tsubmitForm.submit();\r\n" ) ; writer . append ( "\t\t});\r\n" ) ; } writer . append ( "\t} else {\r\n" ) ; writer . append ( "\t\treturn false;\r\n" ) ; writer . append ( "\t}\r\n" ) ; writer . append ( "});\r\n" ) ; writer . append ( "</script>\r\n" ) ; } }
SCIPIO: Creates JS script to populate the target hidden form with the corresponding fields of the row that triggered the submission (only when use-submit-row is false)
335
public void clear ( ) { oredCriteria . clear ( ) ; orderByClause = null ; distinct = false ; }
This method was generated by MyBatis Generator. This method corresponds to the database table address
336
private URL createSearchURL ( URL url ) throws MalformedURLException { if ( url == null ) { return url ; } String protocol = url . getProtocol ( ) ; if ( isDirectory ( url ) || protocol . equals ( "jar" ) ) { return url ; } if ( factory == null ) { return new URL ( "jar" , "" , - 1 , url . toString ( ) + "!/" ) ; } return new URL ( "jar" , "" , - 1 , url . toString ( ) + "!/" , factory . createURLStreamHandler ( "jar" ) ) ; }
Returns an URL that will be checked if it contains the class or resource. If the file component of the URL is not a directory, a Jar URL will be created.
337
public final void trackedAction ( Core controller ) throws InterruptedException { long time = System . currentTimeMillis ( ) ; statistics . useNow ( ) ; action ( controller ) ; time = System . currentTimeMillis ( ) - time ; statistics . updateAverageExecutionTime ( time ) ; }
Perform the action and track the statistics related to this action.
338
private boolean translateReadyOps ( int ops , int initialOps , SelectionKeyImpl sk ) { int intOps = sk . nioInterestOps ( ) ; int oldOps = sk . nioReadyOps ( ) ; int newOps = initialOps ; if ( ( ops & Net . POLLNVAL ) != 0 ) { return false ; } if ( ( ops & ( Net . POLLERR | Net . POLLHUP ) ) != 0 ) { newOps = intOps ; sk . nioReadyOps ( newOps ) ; return ( newOps & ~ oldOps ) != 0 ; } if ( ( ( ops & Net . POLLIN ) != 0 ) && ( ( intOps & SelectionKey . OP_READ ) != 0 ) ) newOps |= SelectionKey . OP_READ ; if ( ( ( ops & Net . POLLOUT ) != 0 ) && ( ( intOps & SelectionKey . OP_WRITE ) != 0 ) ) newOps |= SelectionKey . OP_WRITE ; sk . nioReadyOps ( newOps ) ; return ( newOps & ~ oldOps ) != 0 ; }
Translates native poll revent ops into a ready operation ops
339
public Executor env ( Map < String , String > env ) { this . env = env ; return this ; }
Sets the environment variables for the child process.
340
protected void initView ( ) { mMonthTitlePaint = new Paint ( ) ; mMonthTitlePaint . setFakeBoldText ( true ) ; mMonthTitlePaint . setAntiAlias ( true ) ; mMonthTitlePaint . setTextSize ( MONTH_LABEL_TEXT_SIZE ) ; mMonthTitlePaint . setTypeface ( Typeface . create ( mMonthTitleTypeface , Typeface . BOLD ) ) ; mMonthTitlePaint . setColor ( mDayTextColor ) ; mMonthTitlePaint . setTextAlign ( Align . CENTER ) ; mMonthTitlePaint . setStyle ( Style . FILL ) ; mMonthTitleBGPaint = new Paint ( ) ; mMonthTitleBGPaint . setFakeBoldText ( true ) ; mMonthTitleBGPaint . setAntiAlias ( true ) ; mMonthTitleBGPaint . setColor ( mMonthTitleBGColor ) ; mMonthTitleBGPaint . setTextAlign ( Align . CENTER ) ; mMonthTitleBGPaint . setStyle ( Style . FILL ) ; mSelectedCirclePaint = new Paint ( ) ; mSelectedCirclePaint . setFakeBoldText ( true ) ; mSelectedCirclePaint . setAntiAlias ( true ) ; mSelectedCirclePaint . setColor ( mTodayNumberColor ) ; mSelectedCirclePaint . setTextAlign ( Align . CENTER ) ; mSelectedCirclePaint . setStyle ( Style . FILL ) ; mSelectedCirclePaint . setAlpha ( SELECTED_CIRCLE_ALPHA ) ; mMonthDayLabelPaint = new Paint ( ) ; mMonthDayLabelPaint . setAntiAlias ( true ) ; mMonthDayLabelPaint . setTextSize ( MONTH_DAY_LABEL_TEXT_SIZE ) ; mMonthDayLabelPaint . setColor ( mDayTextColor ) ; mMonthDayLabelPaint . setTypeface ( Typeface . create ( mDayOfWeekTypeface , Typeface . NORMAL ) ) ; mMonthDayLabelPaint . setStyle ( Style . FILL ) ; mMonthDayLabelPaint . setTextAlign ( Align . CENTER ) ; mMonthDayLabelPaint . setFakeBoldText ( true ) ; mMonthNumPaint = new Paint ( ) ; mMonthNumPaint . setAntiAlias ( true ) ; mMonthNumPaint . setTextSize ( MINI_DAY_NUMBER_TEXT_SIZE ) ; mMonthNumPaint . setStyle ( Style . FILL ) ; mMonthNumPaint . setTextAlign ( Align . CENTER ) ; mMonthNumPaint . setFakeBoldText ( false ) ; mCircleIndicatorPaint = new Paint ( ) ; mCircleIndicatorPaint . setAntiAlias ( true ) ; mCircleIndicatorPaint . setStyle ( Style . FILL ) ; mCircleIndicatorPaint . setColor ( mDayTextColor ) ; }
Sets up the text and style properties for painting. Override this if you want to use a different paint.
341
public static KeyPair createECKeyPair ( String name ) throws IOException { try { ECGenParameterSpec ecSpec = new ECGenParameterSpec ( name ) ; KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "EC" ) ; keyGen . initialize ( ecSpec , new SecureRandom ( ) ) ; return keyGen . generateKeyPair ( ) ; } catch ( NoSuchAlgorithmException | InvalidAlgorithmParameterException ex ) { throw new IOException ( ex ) ; } }
Creates a random ECC key pair with the given curve name.
342
public void init ( boolean encrypting , CipherParameters params ) throws IllegalArgumentException { this . encrypting = encrypting ; if ( params instanceof ParametersWithIV ) { ParametersWithIV ivParam = ( ParametersWithIV ) params ; byte [ ] iv = ivParam . getIV ( ) ; if ( iv . length < IV . length ) { System . arraycopy ( iv , 0 , IV , IV . length - iv . length , iv . length ) ; for ( int i = 0 ; i < IV . length - iv . length ; i ++ ) { IV [ i ] = 0 ; } } else { System . arraycopy ( iv , 0 , IV , 0 , IV . length ) ; } reset ( ) ; if ( ivParam . getParameters ( ) != null ) { cipher . init ( true , ivParam . getParameters ( ) ) ; } } else { reset ( ) ; if ( params != null ) { cipher . init ( true , params ) ; } } }
Initialise the cipher and, possibly, the initialisation vector (IV). If an IV isn't passed as part of the parameter, the IV will be all zeros. An IV which is too short is handled in FIPS compliant fashion.
343
public static Document loadDocument ( InputStream stream ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( stream ) ; }
Loads a XML document from a stream and returns the corresponding DOM Document.
344
private int handleSingleNalUnitPacket ( Buffer input , Buffer output ) { byte [ ] bufferData = ( byte [ ] ) input . getData ( ) ; int bufferDataLength = bufferData . length ; byte [ ] data = new byte [ bufferDataLength ] ; System . arraycopy ( bufferData , 0 , data , 0 , bufferDataLength ) ; output . setData ( data ) ; output . setLength ( data . length ) ; output . setOffset ( 0 ) ; output . setTimeStamp ( input . getTimeStamp ( ) ) ; output . setSequenceNumber ( input . getSequenceNumber ( ) ) ; output . setVideoOrientation ( input . getVideoOrientation ( ) ) ; output . setFormat ( input . getFormat ( ) ) ; output . setFlags ( input . getFlags ( ) ) ; return BUFFER_PROCESSED_OK ; }
Handle single NAL Unit packet
345
public static < T > List < T > asList ( T ... values ) { if ( values == null ) { return new ArrayList < T > ( 0 ) ; } else { return new ArrayList < T > ( Arrays . asList ( values ) ) ; } }
Collects the passed in objects into a List.
346
void messageReceived ( ByteBuffer buf ) throws IgniteCheckedException , SSLException { if ( buf . limit ( ) > inNetBuf . remaining ( ) ) { inNetBuf = expandBuffer ( inNetBuf , inNetBuf . capacity ( ) + buf . limit ( ) * 2 ) ; appBuf = expandBuffer ( appBuf , inNetBuf . capacity ( ) * 2 ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Expanded buffers [inNetBufCapacity=" + inNetBuf . capacity ( ) + ", appBufCapacity=" + appBuf . capacity ( ) + ", ses=" + ses + ", " ) ; } inNetBuf . put ( buf ) ; if ( ! handshakeFinished ) handshake ( ) ; else unwrapData ( ) ; if ( isInboundDone ( ) ) { int newPosition = buf . position ( ) - inNetBuf . position ( ) ; if ( newPosition >= 0 ) { buf . position ( newPosition ) ; if ( buf . hasRemaining ( ) ) U . warn ( log , "Got unread bytes after receiving close_notify message (will ignore): " + ses ) ; } inNetBuf . clear ( ) ; } }
Called by SSL filter when new message was received.
347
public final Object copy ( ) { DynamicIntArray copy = new DynamicIntArray ( m_Objects . length ) ; copy . m_Size = m_Size ; copy . m_CapacityIncrement = m_CapacityIncrement ; copy . m_CapacityMultiplier = m_CapacityMultiplier ; System . arraycopy ( m_Objects , 0 , copy . m_Objects , 0 , m_Size ) ; return copy ; }
Produces a copy of this vector.
348
public static int deleteOldSMS ( ) { long olderthan = System . currentTimeMillis ( ) - OLD_SMS_THRESHOLD ; return database . delete ( DatabaseOpenHelper . SMS_TABLE_NAME , "date < " + olderthan , null ) ; }
Deletes SMS from the Database that are older then 5 days
349
private void checkClassAndSync ( Class < ? extends IPacket > clazz ) { if ( ! registeredClasses . contains ( clazz ) ) { throw new RuntimeException ( "NetworkHelper got unknown Packet type " + clazz + " to send, critical error" ) ; } while ( isCurrentlySendingSemaphor ) { Thread . yield ( ) ; } isCurrentlySendingSemaphor = true ; }
Since the crash that happens if we dont do this is complete garbage
350
private void fitImageToView ( ) { Drawable drawable = getDrawable ( ) ; if ( drawable == null || drawable . getIntrinsicWidth ( ) == 0 || drawable . getIntrinsicHeight ( ) == 0 ) { return ; } if ( matrix == null || prevMatrix == null ) { return ; } int drawableWidth = drawable . getIntrinsicWidth ( ) ; int drawableHeight = drawable . getIntrinsicHeight ( ) ; float scaleX = ( float ) viewWidth / drawableWidth ; float scaleY = ( float ) viewHeight / drawableHeight ; switch ( mScaleType ) { case CENTER : scaleX = scaleY = 1 ; break ; case CENTER_CROP : scaleX = scaleY = Math . max ( scaleX , scaleY ) ; break ; case CENTER_INSIDE : scaleX = scaleY = Math . min ( 1 , Math . min ( scaleX , scaleY ) ) ; case FIT_CENTER : scaleX = scaleY = Math . min ( scaleX , scaleY ) ; break ; case FIT_XY : break ; default : throw new UnsupportedOperationException ( "TouchImageView does not support FIT_START or FIT_END" ) ; } float redundantXSpace = viewWidth - ( scaleX * drawableWidth ) ; float redundantYSpace = viewHeight - ( scaleY * drawableHeight ) ; matchViewWidth = viewWidth - redundantXSpace ; matchViewHeight = viewHeight - redundantYSpace ; if ( ! isZoomed ( ) && ! imageRenderedAtLeastOnce ) { matrix . setScale ( scaleX , scaleY ) ; matrix . postTranslate ( redundantXSpace / 2 , redundantYSpace / 2 ) ; normalizedScale = 1 ; } else { if ( prevMatchViewWidth == 0 || prevMatchViewHeight == 0 ) { savePreviousImageValues ( ) ; } prevMatrix . getValues ( m ) ; m [ Matrix . MSCALE_X ] = matchViewWidth / drawableWidth * normalizedScale ; m [ Matrix . MSCALE_Y ] = matchViewHeight / drawableHeight * normalizedScale ; float transX = m [ Matrix . MTRANS_X ] ; float transY = m [ Matrix . MTRANS_Y ] ; float prevActualWidth = prevMatchViewWidth * normalizedScale ; float actualWidth = getImageWidth ( ) ; translateMatrixAfterRotate ( Matrix . MTRANS_X , transX , prevActualWidth , actualWidth , prevViewWidth , viewWidth , drawableWidth ) ; float prevActualHeight = prevMatchViewHeight * normalizedScale ; float actualHeight = getImageHeight ( ) ; translateMatrixAfterRotate ( Matrix . MTRANS_Y , transY , prevActualHeight , actualHeight , prevViewHeight , viewHeight , drawableHeight ) ; matrix . setValues ( m ) ; } fixTrans ( ) ; setImageMatrix ( matrix ) ; }
If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise, it is made to fit the screen according to the dimensions of the previous image matrix. This allows the image to maintain its zoom after rotation.
351
private static String encodeMetricFilters ( String metricString , Map < String , String > mapper ) { String finalString = metricString ; int counter = 0 ; int startIndex = 0 ; int endIndex = 0 ; for ( int i = 0 ; i < metricString . length ( ) ; i ++ ) { char currentChar = metricString . charAt ( i ) ; startIndex = ( currentChar == '(' && counter == 0 ) ? i : startIndex ; counter = ( currentChar == '(' ) ? counter + 1 : counter ; if ( currentChar == ')' ) { endIndex = i ; counter = counter - 1 ; } if ( counter == 0 && startIndex != 0 ) { String filterString = metricString . substring ( startIndex , endIndex + 1 ) ; finalString = finalString . replace ( filterString , "-" + startIndex ) ; mapper . put ( "-" + startIndex , filterString ) ; startIndex = 0 ; } } return finalString ; }
Returns modified metrics string. Aggregated metric filter details are stripped and stored in mapper. Metric filter is replaced by hashkey which can be used to retrieve the filter from the mapper
352
private void finalizeAdditions ( boolean addHomeScreenShortcuts ) { finalizeWorkFolder ( ) ; if ( addHomeScreenShortcuts && ! mHomescreenApps . isEmpty ( ) ) { sortList ( mHomescreenApps ) ; mModel . addAndBindAddedWorkspaceItems ( mContext , mHomescreenApps ) ; } }
Adds and binds all shortcuts marked for addition.
353
private void stopCheckingStatus ( ) { executor . shutdownNow ( ) ; executor = Executors . newSingleThreadExecutor ( ) ; future = null ; }
Re-sets the executor and indicates the system is no longer checking the status of the transactions
354
public void updateNotification ( int notificationId ) { try { notificationDAO . open ( ) ; notificationDAO . updateNotification ( notificationId , Notification . Status . DISMISSED ) ; } finally { notificationDAO . close ( ) ; } }
This method is used to update the notification which is stored in the embedded db.
355
public static Element addChildElementNSValue ( Element element , String childElementName , String childElementValue , Document document , String nameSpaceUrl ) { Element newElement = document . createElementNS ( nameSpaceUrl , childElementName ) ; newElement . appendChild ( document . createTextNode ( childElementValue ) ) ; element . appendChild ( newElement ) ; return element ; }
Creates a child element with the given namespace supportive name and appends it to the element child node list. Also creates a Text node with the given value and appends it to the new elements child node list.
356
public static void overScrollBy ( final PullToRefreshBase < ? > view , final int deltaX , final int scrollX , final int deltaY , final int scrollY , final int scrollRange , final int fuzzyThreshold , final float scaleFactor , final boolean isTouchEvent ) { final int deltaValue , currentScrollValue , scrollValue ; switch ( view . getPullToRefreshScrollDirection ( ) ) { case HORIZONTAL : deltaValue = deltaX ; scrollValue = scrollX ; currentScrollValue = view . getScrollX ( ) ; break ; case VERTICAL : default : deltaValue = deltaY ; scrollValue = scrollY ; currentScrollValue = view . getScrollY ( ) ; break ; } if ( view . isPullToRefreshOverScrollEnabled ( ) && ! view . isRefreshing ( ) ) { final Mode mode = view . getMode ( ) ; if ( mode . permitsPullToRefresh ( ) && ! isTouchEvent && deltaValue != 0 ) { final int newScrollValue = ( deltaValue + scrollValue ) ; if ( PullToRefreshBase . DEBUG ) { Log . d ( LOG_TAG , "OverScroll. DeltaX: " + deltaX + ", ScrollX: " + scrollX + ", DeltaY: " + deltaY + ", ScrollY: " + scrollY + ", NewY: " + newScrollValue + ", ScrollRange: " + scrollRange + ", CurrentScroll: " + currentScrollValue ) ; } if ( newScrollValue < ( 0 - fuzzyThreshold ) ) { if ( mode . showHeaderLoadingLayout ( ) ) { if ( currentScrollValue == 0 ) { view . setState ( State . OVERSCROLLING ) ; } view . setHeaderScroll ( ( int ) ( scaleFactor * ( currentScrollValue + newScrollValue ) ) ) ; } } else if ( newScrollValue > ( scrollRange + fuzzyThreshold ) ) { if ( mode . showFooterLoadingLayout ( ) ) { if ( currentScrollValue == 0 ) { view . setState ( State . OVERSCROLLING ) ; } view . setHeaderScroll ( ( int ) ( scaleFactor * ( currentScrollValue + newScrollValue - scrollRange ) ) ) ; } } else if ( Math . abs ( newScrollValue ) <= fuzzyThreshold || Math . abs ( newScrollValue - scrollRange ) <= fuzzyThreshold ) { view . setState ( State . RESET ) ; } } else if ( isTouchEvent && State . OVERSCROLLING == view . getState ( ) ) { view . setState ( State . RESET ) ; } } }
Helper method for Overscrolling that encapsulates all of the necessary function. This is the advanced version of the call.
357
public void addColumnListener ( ColumnListener listener ) { m_listeners . add ( listener ) ; }
Adds a listener to be notified when this column changes
358
public void loadDataset ( URL url , IRI context , ParserConfig config ) throws RepositoryException { try { Long since = lastModified . get ( url ) ; URLConnection urlCon = url . openConnection ( ) ; if ( since != null ) { urlCon . setIfModifiedSince ( since ) ; } if ( since == null || since < urlCon . getLastModified ( ) ) { load ( url , urlCon , context , config ) ; } } catch ( RDFParseException e ) { throw new RepositoryException ( e ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } }
Inspects if the dataset at the supplied URL location has been modified since the last load into this repository and if so loads it into the supplied context.
359
protected int read ( InputStream inputStream , byte [ ] buffer , char [ ] divider ) throws IOException { int index = 0 ; int dividerIndex = 0 ; do { byte readByte = ( byte ) ( 0x000000FF & inputStream . read ( ) ) ; if ( readByte == - 1 ) { return index ; } if ( readByte == divider [ dividerIndex ] ) { dividerIndex ++ ; } if ( dividerIndex == divider . length ) { index -= dividerIndex - 1 ; for ( int i = index ; i < index + dividerIndex ; i ++ ) { if ( i >= buffer . length ) { break ; } buffer [ i ] = 0 ; } return index ; } buffer [ index ] = readByte ; index ++ ; } while ( index < buffer . length ) ; return index ; }
Reads bytes from a given file reader until either a specified character sequence is read, the buffer is completely filled or the end of file is reached.
360
public void testNodeDocumentFragmentNormalize1 ( ) throws Throwable { Document doc ; DocumentFragment docFragment ; String nodeValue ; Text txtNode ; Node retval ; doc = ( Document ) load ( "hc_staff" , builder ) ; docFragment = doc . createDocumentFragment ( ) ; txtNode = doc . createTextNode ( "foo" ) ; retval = docFragment . appendChild ( txtNode ) ; txtNode = doc . createTextNode ( "bar" ) ; retval = docFragment . appendChild ( txtNode ) ; docFragment . normalize ( ) ; txtNode = ( Text ) docFragment . getFirstChild ( ) ; nodeValue = txtNode . getNodeValue ( ) ; assertEquals ( "normalizedNodeValue" , "foobar" , nodeValue ) ; retval = txtNode . getNextSibling ( ) ; assertNull ( "singleChild" , retval ) ; }
Runs the test case.
361
private void collectTimes ( Tree tree , NodeRef node , Set < NodeRef > excludeNodesBelow , Intervals intervals ) { intervals . addCoalescentEvent ( tree . getNodeHeight ( node ) ) ; for ( int i = 0 ; i < tree . getChildCount ( node ) ; i ++ ) { NodeRef child = tree . getChild ( node , i ) ; boolean include = true ; if ( excludeNodesBelow != null && excludeNodesBelow . contains ( child ) ) { include = false ; } if ( ! include || tree . isExternal ( child ) ) { intervals . addSampleEvent ( tree . getNodeHeight ( child ) ) ; } else { collectTimes ( tree , child , excludeNodesBelow , intervals ) ; } } }
extract coalescent times and tip information into ArrayList times from tree.
362
public StringBody ( final String text , final String mimeType , Charset charset ) throws UnsupportedEncodingException { super ( mimeType ) ; if ( text == null ) { throw new IllegalArgumentException ( "Text may not be null" ) ; } if ( charset == null ) { charset = Charset . forName ( HTTP . UTF_8 ) ; } this . content = text . getBytes ( charset . name ( ) ) ; this . charset = charset ; }
Create a StringBody from the specified text, mime type and character set.
363
public void makeImmutable ( ) { mutable = false ; if ( authnContextClassRef != null ) { authnContextClassRef = Collections . unmodifiableList ( authnContextClassRef ) ; } if ( authnContextDeclRef != null ) { authnContextDeclRef = Collections . unmodifiableList ( authnContextDeclRef ) ; } return ; }
Makes the obejct immutable
364
protected abstract int readSkipData ( int level , IndexInput skipStream ) throws IOException ;
Subclasses must implement the actual skip data encoding in this method.
365
SSLSession toSession ( byte [ ] data , String host , int port ) { ByteArrayInputStream bais = new ByteArrayInputStream ( data ) ; DataInputStream dais = new DataInputStream ( bais ) ; try { int type = dais . readInt ( ) ; if ( type != OPEN_SSL ) { log ( new AssertionError ( "Unexpected type ID: " + type ) ) ; return null ; } int length = dais . readInt ( ) ; byte [ ] sessionData = new byte [ length ] ; dais . readFully ( sessionData ) ; int count = dais . readInt ( ) ; X509Certificate [ ] certs = new X509Certificate [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { length = dais . readInt ( ) ; byte [ ] certData = new byte [ length ] ; dais . readFully ( certData ) ; certs [ i ] = OpenSSLX509Certificate . fromX509Der ( certData ) ; } return new OpenSSLSessionImpl ( sessionData , host , port , certs , this ) ; } catch ( IOException e ) { log ( e ) ; return null ; } }
Creates a session from the given bytes.
366
protected TamsMessage pollMessage ( ) { if ( disablePoll ) { return null ; } if ( ! pollQueue . isEmpty ( ) ) { PollMessage pm = pollQueue . peek ( ) ; if ( pm != null ) { tm = pm . getMessage ( ) ; return pm . getMessage ( ) ; } } return null ; }
Check Tams MC for status updates
367
public Path bin ( ) { return root . resolve ( "bin" ) ; }
Gets the bin directory.
368
public static void safeCopy ( final Reader reader , final Writer writer ) throws IOException { try { IOUtils . copy ( reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; } }
Copy and close the reader and writer streams.
369
public static < T extends Bean > T load ( Bson query , T t ) { String collection = getCollection ( t . getClass ( ) ) ; if ( collection != null ) { try { return load ( query , null , t ) ; } catch ( Exception e ) { if ( log . isErrorEnabled ( ) ) log . error ( e . getMessage ( ) , e ) ; } } return null ; }
load the data full into the t.
370
private PrintElement createImageElement ( MPrintFormatItem item ) { Object obj = m_data . getNode ( new Integer ( item . getAD_Column_ID ( ) ) ) ; if ( obj == null ) return null ; else if ( obj instanceof PrintDataElement ) ; else { log . log ( Level . SEVERE , "Element not PrintDataElement " + obj . getClass ( ) ) ; return null ; } PrintDataElement data = ( PrintDataElement ) obj ; if ( data . isNull ( ) && item . isSuppressNull ( ) ) return null ; String url = data . getValueDisplay ( m_format . getLanguage ( ) ) ; if ( ( url == null || url . length ( ) == 0 ) ) { if ( item . isSuppressNull ( ) ) return null ; else return null ; } ImageElement element = null ; if ( data . getDisplayType ( ) == DisplayType . Image ) { element = ImageElement . get ( data , url ) ; } else { element = ImageElement . get ( url ) ; } return element ; }
Create Image Element from item
371
public void resetCharges ( ) { pendingCharges . removeAllElements ( ) ; }
Resets the pending charges list.
372
static RepaintManager currentManager ( AppContext appContext ) { RepaintManager rm = ( RepaintManager ) appContext . get ( repaintManagerKey ) ; if ( rm == null ) { rm = new RepaintManager ( BUFFER_STRATEGY_TYPE ) ; appContext . put ( repaintManagerKey , rm ) ; } return rm ; }
Returns the RepaintManager for the specified AppContext. If a RepaintManager has not been created for the specified AppContext this will return null.
373
public static void paintCheckedBackground ( Component c , Graphics g , int x , int y , int width , int height ) { if ( backgroundImage == null ) { backgroundImage = new BufferedImage ( 64 , 64 , BufferedImage . TYPE_INT_ARGB ) ; Graphics bg = backgroundImage . createGraphics ( ) ; for ( int by = 0 ; by < 64 ; by += 8 ) { for ( int bx = 0 ; bx < 64 ; bx += 8 ) { bg . setColor ( ( ( bx ^ by ) & 8 ) != 0 ? Color . lightGray : Color . white ) ; bg . fillRect ( bx , by , 8 , 8 ) ; } } bg . dispose ( ) ; } if ( backgroundImage != null ) { Shape saveClip = g . getClip ( ) ; Rectangle r = g . getClipBounds ( ) ; if ( r == null ) r = new Rectangle ( c . getSize ( ) ) ; r = r . intersection ( new Rectangle ( x , y , width , height ) ) ; g . setClip ( r ) ; int w = backgroundImage . getWidth ( ) ; int h = backgroundImage . getHeight ( ) ; if ( w != - 1 && h != - 1 ) { int x1 = ( r . x / w ) * w ; int y1 = ( r . y / h ) * h ; int x2 = ( ( r . x + r . width + w - 1 ) / w ) * w ; int y2 = ( ( r . y + r . height + h - 1 ) / h ) * h ; for ( y = y1 ; y < y2 ; y += h ) for ( x = x1 ; x < x2 ; x += w ) g . drawImage ( backgroundImage , x , y , c ) ; } g . setClip ( saveClip ) ; } }
Paint a check pattern, used for a background to indicate image transparency.
374
public int decrement ( ) { lock . lock ( ) ; int newValue = -- value ; lock . unlock ( ) ; return newValue ; }
Decrements the counter by 1.
375
private void addPoint ( Point p ) { Coordinate coord = p . getCoordinate ( ) ; insertPoint ( argIndex , coord , Location . INTERIOR ) ; }
Add a Point to the graph.
376
public boolean isConnectable ( ) { for ( DeviceService service : services . values ( ) ) { if ( service . isConnectable ( ) ) return true ; } return false ; }
Whether the device has any DeviceServices that require an active connection (websocket, HTTP registration, etc)
377
public E take ( ) throws InterruptedException { final ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { for ( ; ; ) { E first = q . peek ( ) ; if ( first == null ) available . await ( ) ; else { long delay = first . getDelay ( NANOSECONDS ) ; if ( delay <= 0 ) return q . poll ( ) ; first = null ; if ( leader != null ) available . await ( ) ; else { Thread thisThread = Thread . currentThread ( ) ; leader = thisThread ; try { available . awaitNanos ( delay ) ; } finally { if ( leader == thisThread ) leader = null ; } } } } } finally { if ( leader == null && q . peek ( ) != null ) available . signal ( ) ; lock . unlock ( ) ; } }
Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.
378
private static void skipArray ( ByteBuffer buf ) { int length = buf . getShort ( ) & 0xFFFF ; for ( int i = 0 ; i < length ; i ++ ) skipMemberValue ( buf ) ; }
Skips the array value at the current position in the specified byte buffer. The cursor of the byte buffer must point to an array value struct.
379
public static byte [ ] hash ( byte [ ] input ) { if ( input != null ) { final MessageDigest digest ; try { digest = MessageDigest . getInstance ( "SHA-256" ) ; byte [ ] hashedBytes = input ; digest . update ( hashedBytes , 0 , hashedBytes . length ) ; return hashedBytes ; } catch ( NoSuchAlgorithmException e ) { Log . e ( TAG , "problem hashing \"" + input + "\" " + e . getMessage ( ) , e ) ; } } else { Log . w ( TAG , "hash called with null input byte[]" ) ; } return null ; }
Created SHA256 of input
380
private void reopen ( ) { Timeline animation = new Timeline ( new KeyFrame ( Duration . seconds ( 0.1 ) , new KeyValue ( inputs . prefHeightProperty ( ) , inputs . getMaxHeight ( ) ) ) ) ; animation . play ( ) ; }
Makes an animation to make the input vbox slide open over .1 seconds
381
private byte [ ] copyArray ( byte [ ] buffer , int length ) { byte [ ] result = new byte [ length ] ; System . arraycopy ( buffer , 0 , result , 0 , Math . min ( buffer . length , length ) ) ; return result ; }
Implement java.util.Arrays.copyOf() for jdk 1.5.
382
protected void drawPath ( Canvas canvas , List < Float > points , Paint paint , boolean circular ) { Path path = new Path ( ) ; int height = canvas . getHeight ( ) ; int width = canvas . getWidth ( ) ; float [ ] tempDrawPoints ; if ( points . size ( ) < 4 ) { return ; } tempDrawPoints = calculateDrawPoints ( points . get ( 0 ) , points . get ( 1 ) , points . get ( 2 ) , points . get ( 3 ) , height , width ) ; path . moveTo ( tempDrawPoints [ 0 ] , tempDrawPoints [ 1 ] ) ; path . lineTo ( tempDrawPoints [ 2 ] , tempDrawPoints [ 3 ] ) ; int length = points . size ( ) ; for ( int i = 4 ; i < length ; i += 2 ) { if ( ( points . get ( i - 1 ) < 0 && points . get ( i + 1 ) < 0 ) || ( points . get ( i - 1 ) > height && points . get ( i + 1 ) > height ) ) { continue ; } tempDrawPoints = calculateDrawPoints ( points . get ( i - 2 ) , points . get ( i - 1 ) , points . get ( i ) , points . get ( i + 1 ) , height , width ) ; if ( ! circular ) { path . moveTo ( tempDrawPoints [ 0 ] , tempDrawPoints [ 1 ] ) ; } path . lineTo ( tempDrawPoints [ 2 ] , tempDrawPoints [ 3 ] ) ; } if ( circular ) { path . lineTo ( points . get ( 0 ) , points . get ( 1 ) ) ; } canvas . drawPath ( path , paint ) ; }
The graphical representation of a path.
383
public static Map < String , Object > testSOAPService ( DispatchContext dctx , Map < String , ? > context ) { Delegator delegator = dctx . getDelegator ( ) ; Map < String , Object > response = ServiceUtil . returnSuccess ( ) ; List < GenericValue > testingNodes = new LinkedList < GenericValue > ( ) ; for ( int i = 0 ; i < 3 ; i ++ ) { GenericValue testingNode = delegator . makeValue ( "TestingNode" ) ; testingNode . put ( "testingNodeId" , "TESTING_NODE" + i ) ; testingNode . put ( "description" , "Testing Node " + i ) ; testingNode . put ( "createdStamp" , UtilDateTime . nowTimestamp ( ) ) ; testingNodes . add ( testingNode ) ; } response . put ( "testingNodes" , testingNodes ) ; return response ; }
Generic Test SOAP Service
384
public XmlDom ( InputStream is ) throws SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder ; try { builder = factory . newDocumentBuilder ( ) ; Document doc = builder . parse ( is ) ; this . root = ( Element ) doc . getDocumentElement ( ) ; } catch ( ParserConfigurationException e ) { } catch ( IOException e ) { throw new SAXException ( e ) ; } }
Instantiates a new xml dom.
385
public void removeKeyListener ( GlobalKeyListener listener ) { listeners . remove ( listener ) ; }
Removes a global key listener
386
public Set search3 ( String tokenID , String startDN , String filter , int numOfEntries , int timeLimit , boolean sortResults , boolean ascendingOrder , Set excludes ) throws SMSException , SSOException , RemoteException { initialize ( ) ; if ( debug . messageEnabled ( ) ) { debug . message ( "SMSJAXRPCObjectImpl::search dn: " + startDN + " filter: " + filter + " excludes: " + excludes ) ; } Iterator i = SMSEntry . search ( getToken ( tokenID ) , startDN , filter , numOfEntries , timeLimit , sortResults , ascendingOrder , excludes ) ; Set < String > result = new HashSet < String > ( ) ; while ( i . hasNext ( ) ) { SMSDataEntry e = ( SMSDataEntry ) i . next ( ) ; try { result . add ( e . toJSONString ( ) ) ; } catch ( JSONException ex ) { debug . error ( "SMSJAXRPCObjectImpl::problem performing search dn: " + startDN + " filter: " + filter + " excludes: " + excludes , ex ) ; } } return result ; }
Searches the data store for objects that match the filter with an exclude set
387
private Resource generatePreviewResource ( Resource resource , Eml eml , BigDecimal nextVersion ) { Resource copy = new Resource ( ) ; copy . setShortname ( resource . getShortname ( ) ) ; copy . setTitle ( resource . getTitle ( ) ) ; copy . setLastPublished ( resource . getLastPublished ( ) ) ; copy . setStatus ( resource . getStatus ( ) ) ; copy . setOrganisation ( resource . getOrganisation ( ) ) ; copy . setKey ( resource . getKey ( ) ) ; copy . setEmlVersion ( nextVersion ) ; if ( resource . isCitationAutoGenerated ( ) ) { Citation citation = new Citation ( ) ; URI homepage = cfg . getResourceVersionUri ( resource . getShortname ( ) , nextVersion ) ; citation . setCitation ( resource . generateResourceCitation ( nextVersion , homepage ) ) ; eml . setCitation ( citation ) ; } Date releaseDate = new Date ( ) ; copy . setLastPublished ( releaseDate ) ; eml . setPubDate ( releaseDate ) ; copy . setEml ( eml ) ; List < VersionHistory > histories = Lists . newArrayList ( ) ; histories . addAll ( resource . getVersionHistory ( ) ) ; copy . setVersionHistory ( histories ) ; VersionHistory history = new VersionHistory ( nextVersion , releaseDate , PublicationStatus . PUBLIC ) ; User modifiedBy = getCurrentUser ( ) ; if ( modifiedBy != null ) { history . setModifiedBy ( modifiedBy ) ; } if ( resource . getDoi ( ) != null && ( resource . getIdentifierStatus ( ) == IdentifierStatus . PUBLIC_PENDING_PUBLICATION || resource . getIdentifierStatus ( ) == IdentifierStatus . PUBLIC ) ) { copy . setDoi ( resource . getDoi ( ) ) ; copy . setIdentifierStatus ( IdentifierStatus . PUBLIC ) ; history . setDoi ( resource . getDoi ( ) ) ; history . setStatus ( IdentifierStatus . PUBLIC ) ; } copy . addVersionHistory ( history ) ; return copy ; }
Generate a copy of the resource, previewing what the next publication of the resource will look like. This involves copying over certain fields not in EML, and then setting the version equal to next published version, and setting a new pubDate.
388
public boolean removeEntry ( int xIndex , int dataSetIndex ) { if ( dataSetIndex >= mDataSets . size ( ) ) return false ; T dataSet = mDataSets . get ( dataSetIndex ) ; Entry e = dataSet . getEntryForXIndex ( xIndex ) ; if ( e == null || e . getXIndex ( ) != xIndex ) return false ; return removeEntry ( e , dataSetIndex ) ; }
Removes the Entry object at the given xIndex from the DataSet at the specified index. Returns true if an Entry was removed, false if no Entry was found that meets the specified requirements.
389
void closeStream ( Closeable closeable ) { try { if ( closeable != null ) { closeable . close ( ) ; } } catch ( IOException ex ) { utils . logIssue ( "Could not close exception storage file." , ex ) ; } }
Attempt to close given FileInputStream. Checks for null. Exceptions are logged.
390
private void emitEnsureCollection ( Method method , String fieldName , StringBuilder builder ) { builder . append ( " protected void " ) ; builder . append ( getEnsureName ( fieldName ) ) ; builder . append ( "() {\n" ) ; builder . append ( " if (" ) ; builder . append ( fieldName ) ; builder . append ( " == null) {\n " ) ; builder . append ( fieldName ) ; builder . append ( " = new " ) ; builder . append ( getImplName ( method . getGenericReturnType ( ) , true ) ) ; builder . append ( "();\n" ) ; builder . append ( " }\n" ) ; builder . append ( " }\n" ) ; }
Emit a method that ensures a collection is initialized.
391
public void testFromDate ( ) throws Exception { TimeZone . setDefault ( TimeZone . getTimeZone ( "PST" ) ) ; final Calendar date = Calendar . getInstance ( ) ; date . setTime ( new Date ( 123456789012345L ) ) ; Assert . assertEquals ( "5882-03-11T00:30:12.345Z" , CalendarSerializer . serialize ( date ) ) ; final Calendar dateNoMillis = Calendar . getInstance ( ) ; dateNoMillis . setTime ( new Date ( 123456789012000L ) ) ; Assert . assertEquals ( "5882-03-11T00:30:12.000Z" , CalendarSerializer . serialize ( dateNoMillis ) ) ; }
Make sure that dates with and without millis can be converted properly into strings
392
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; registrarID = new ServiceID ( in ) ; if ( server == null ) { throw new InvalidObjectException ( "null server" ) ; } }
Reads the default serializable field value for this instance, followed by the registrar's service ID encoded as specified by the ServiceID.writeBytes method. Verifies that the deserialized registrar reference is non-null.
393
@ Override public boolean eIsSet ( int featureID ) { switch ( featureID ) { case EipPackage . METADATA__KEY : return KEY_EDEFAULT == null ? key != null : ! KEY_EDEFAULT . equals ( key ) ; case EipPackage . METADATA__VALUES : return values != null && ! values . isEmpty ( ) ; } return super . eIsSet ( featureID ) ; }
<!-- begin-user-doc --> <!-- end-user-doc -->
394
public void addHandler ( String columnName , SQLDataHandler handler ) { if ( m_overrides == null ) m_overrides = new HashMap ( 3 ) ; m_overrides . put ( columnName , handler ) ; }
Add a custom data handler for a given column name.
395
@ Override public boolean isModified ( ) { if ( _isDigestModified ) { if ( log . isLoggable ( Level . FINE ) ) log . fine ( _source . getNativePath ( ) + " digest is modified." ) ; return true ; } long sourceLastModified = _source . getLastModified ( ) ; long sourceLength = _source . length ( ) ; if ( ! _requireSource && sourceLastModified == 0 ) { return false ; } else if ( sourceLength != _length ) { if ( log . isLoggable ( Level . FINE ) ) { log . fine ( _source . getNativePath ( ) + " length is modified (" + _length + " -> " + sourceLength + ")" ) ; } return true ; } else if ( sourceLastModified != _lastModified ) { if ( log . isLoggable ( Level . FINE ) ) log . fine ( _source . getNativePath ( ) + " time is modified." ) ; return true ; } else return false ; }
If the source modified date changes at all, treat it as a modification. This protects against the case where multiple computers have misaligned dates and a '<' comparison may fail.
396
public byte [ ] toByteArray ( ) { int totalLen = _pastLen + _currBlockPtr ; if ( totalLen == 0 ) { return NO_BYTES ; } byte [ ] result = new byte [ totalLen ] ; int offset = 0 ; for ( byte [ ] block : _pastBlocks ) { int len = block . length ; System . arraycopy ( block , 0 , result , offset , len ) ; offset += len ; } System . arraycopy ( _currBlock , 0 , result , offset , _currBlockPtr ) ; offset += _currBlockPtr ; if ( offset != totalLen ) { throw new RuntimeException ( "Internal error: total len assumed to be " + totalLen + ", copied " + offset + " bytes" ) ; } if ( ! _pastBlocks . isEmpty ( ) ) { reset ( ) ; } return result ; }
Method called when results are finalized and we can get the full aggregated result buffer to return to the caller
397
public CommandEditor ( ActionCommand cmd , EditableResources res , String uiName , List < com . codename1 . ui . Command > commands , Properties projectGeneratorSettings , boolean java5 ) { this . java5 = java5 ; this . projectGeneratorSettings = projectGeneratorSettings ; this . uiName = uiName ; initComponents ( ) ; goToSource . setEnabled ( projectGeneratorSettings != null ) ; com . codename1 . ui . Command [ ] existing = new com . codename1 . ui . Command [ commands . size ( ) + 1 ] ; existing [ 0 ] = null ; for ( int iter = 1 ; iter < existing . length ; iter ++ ) { existing [ iter ] = commands . get ( iter - 1 ) ; } Vector postActions = new Vector ( ) ; postActions . addElement ( "None" ) ; Vector actions = new Vector ( ) ; actions . addElement ( "None" ) ; actions . addElement ( "Minimize" ) ; actions . addElement ( "Exit" ) ; actions . addElement ( "Execute" ) ; actions . addElement ( "Back" ) ; backCommand . setSelected ( cmd . isBackCommand ( ) ) ; String [ ] uiEntries = new String [ res . getUIResourceNames ( ) . length ] ; System . arraycopy ( res . getUIResourceNames ( ) , 0 , uiEntries , 0 , uiEntries . length ) ; Arrays . sort ( uiEntries ) ; for ( String uis : uiEntries ) { if ( ! uiName . equals ( uis ) ) { actions . addElement ( uis ) ; postActions . addElement ( uis ) ; } } action . setModel ( new DefaultComboBoxModel ( actions ) ) ; postAction . setModel ( new DefaultComboBoxModel ( postActions ) ) ; String a = cmd . getAction ( ) ; if ( a != null ) { if ( a . startsWith ( "@" ) ) { a = a . substring ( 1 ) ; asynchronous . setSelected ( true ) ; } else { if ( a . startsWith ( "!" ) ) { a = a . substring ( 1 ) ; String [ ] arr = a . split ( ";" ) ; action . setSelectedItem ( arr [ 0 ] ) ; postAction . setSelectedItem ( arr [ 1 ] ) ; } else { if ( a . startsWith ( "$" ) ) { a = a . substring ( 1 ) ; } } } } action . setSelectedItem ( a ) ; name . setText ( cmd . getCommandName ( ) ) ; id . setModel ( new SpinnerNumberModel ( cmd . getId ( ) , - 10000 , Integer . MAX_VALUE , 1 ) ) ; ResourceEditorView . initImagesComboBox ( icon , res , false , true ) ; icon . setSelectedItem ( cmd . getIcon ( ) ) ; ResourceEditorView . initImagesComboBox ( rollover , res , false , true ) ; rollover . setSelectedItem ( cmd . getRolloverIcon ( ) ) ; ResourceEditorView . initImagesComboBox ( pressed , res , false , true ) ; pressed . setSelectedItem ( cmd . getPressedIcon ( ) ) ; ResourceEditorView . initImagesComboBox ( disabled , res , false , true ) ; disabled . setSelectedItem ( cmd . getDisabledIcon ( ) ) ; }
Creates new form CommandEditor
398
public static < M extends Message > String writeJsonStream ( ImmutableList < M > messages ) { ByteArrayOutputStream resultStream = new ByteArrayOutputStream ( ) ; MessageWriter < M > writer = MessageWriter . create ( Output . forStream ( new PrintStream ( resultStream ) ) ) ; writer . writeAll ( messages ) ; return resultStream . toString ( ) ; }
Returns the string representation of the stream of supplied messages. Each individual message is represented as valid json, but not that the whole result is, itself, *not* valid json.
399
public org . smpte_ra . schemas . st2067_2_2016 . ContentMaturityRatingType buildContentMaturityRatingType ( String agency , String rating , org . smpte_ra . schemas . st2067_2_2016 . ContentMaturityRatingType . Audience audience ) throws URISyntaxException { org . smpte_ra . schemas . st2067_2_2016 . ContentMaturityRatingType contentMaturityRatingType = new org . smpte_ra . schemas . st2067_2_2016 . ContentMaturityRatingType ( ) ; if ( ! agency . matches ( "^[a-zA-Z0-9._-]+" ) == true ) { throw new URISyntaxException ( "Invalid URI" , "The ContentMaturityRating agency %s does not follow the syntax of a valid URI (a-z, A-Z, 0-9, ., _, -)" ) ; } contentMaturityRatingType . setAgency ( agency ) ; contentMaturityRatingType . setRating ( rating ) ; contentMaturityRatingType . setAudience ( audience ) ; return contentMaturityRatingType ; }
A method to construct a ContentMaturityRatingType conforming to the 2016 schema