idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
36,700
|
protected static String getAttribute ( Node node , String name , boolean required ) { NamedNodeMap attributes = node . getAttributes ( ) ; Node idNode = attributes . getNamedItem ( name ) ; if ( idNode == null ) { if ( required ) { throw new IllegalArgumentException ( toPath ( node ) + " has no " + name + " attribute" ) ; } else { return "" ; } } else { String value = idNode . getNodeValue ( ) ; if ( value == null ) { return "" ; } return value ; } }
|
Get an Attribute from the given node and throwing an exception in the case it is required but not present
|
36,701
|
protected static Iterable < Node > evaluate ( Node element , XPathExpression expression , boolean detatch ) throws XPathExpressionException { final NodeList nodeList = ( NodeList ) expression . evaluate ( element , XPathConstants . NODESET ) ; return new Iterable < Node > ( ) { public Iterator < Node > iterator ( ) { return new Iterator < Node > ( ) { int index = 0 ; public boolean hasNext ( ) { return index < nodeList . getLength ( ) ; } public Node next ( ) { Node item = nodeList . item ( index ) ; if ( detatch ) { item . getParentNode ( ) . removeChild ( item ) ; } index ++ ; return item ; } } ; } } ; }
|
evaluates a XPath expression and loops over the nodeset result
|
36,702
|
public String getProperty ( String key , String defaultValue ) { String value = resolver . get ( key ) ; return ( value == null ) ? defaultValue : value ; }
|
Returns the configuration property for the given key or the given default value .
|
36,703
|
public static ConfigurationOption newConfiguration ( String pid ) { return new org . ops4j . pax . exam . cm . internal . ConfigurationProvisionOption ( pid , new HashMap < String , Object > ( ) ) ; }
|
Creates a basic empty configuration for the given PID
|
36,704
|
public static ConfigurationOption overrideConfiguration ( String pid ) { return new org . ops4j . pax . exam . cm . internal . ConfigurationProvisionOption ( pid , new HashMap < String , Object > ( ) ) . override ( true ) . create ( false ) ; }
|
Creates an overriding empty configuration for the given PID
|
36,705
|
public static ConfigurationOption factoryConfiguration ( String pid ) { return new org . ops4j . pax . exam . cm . internal . ConfigurationProvisionOption ( pid , new HashMap < String , Object > ( ) ) . factory ( true ) ; }
|
Creates a factory empty configuration for the given PID
|
36,706
|
public static Option configurationFolder ( File folder , String extension ) { if ( ! folder . exists ( ) ) { throw new TestContainerException ( "folder " + folder + " does not exits" ) ; } List < Option > options = new ArrayList < Option > ( ) ; File [ ] files = folder . listFiles ( ) ; for ( File file : files ) { if ( file . isDirectory ( ) ) { continue ; } String name = file . getName ( ) ; if ( ! name . endsWith ( extension ) ) { continue ; } else { name = name . substring ( 0 , name . length ( ) - extension . length ( ) ) ; } String [ ] split = name . split ( "-" ) ; org . ops4j . pax . exam . cm . internal . ConfigurationProvisionOption cfg = new org . ops4j . pax . exam . cm . internal . ConfigurationProvisionOption ( split [ 0 ] , new HashMap < String , Object > ( ) ) ; cfg . factory ( split . length > 1 ) ; Properties properties = new Properties ( ) ; try { FileInputStream stream = new FileInputStream ( file ) ; try { properties . load ( stream ) ; } finally { stream . close ( ) ; } } catch ( IOException e ) { throw new TestContainerException ( "can't read configuration file " + file , e ) ; } Set < String > names = properties . stringPropertyNames ( ) ; for ( String key : names ) { cfg . put ( key , properties . getProperty ( key ) ) ; } options . add ( cfg . asOption ( ) ) ; } return CoreOptions . composite ( options . toArray ( new Option [ 0 ] ) ) ; }
|
read all configuration files from a folder and transform them into configuration options
|
36,707
|
private BundleContext getBundleContext ( Bundle bundle , long timeout ) { long endTime = System . currentTimeMillis ( ) + timeout ; BundleContext bc = null ; while ( bc == null ) { bc = bundle . getBundleContext ( ) ; if ( bc == null ) { if ( System . currentTimeMillis ( ) >= endTime ) { throw new TestContainerException ( "Unable to retrieve bundle context from bundle " + bundle ) ; } try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { } } } return bc ; }
|
Retrieve bundle context from given bundle . If the bundle is being restarted the bundle context can be null for some time
|
36,708
|
public EntityManager getEntityManager ( EntityManagerFactory emf ) { log . debug ( "producing EntityManager" ) ; return emf . createEntityManager ( ) ; }
|
Use a producer method so that CDI will find this EntityManager .
|
36,709
|
public TestProbeBuilder createProbeBuilder ( Object testClassInstance ) throws IOException , ExamConfigurationException { if ( defaultProbeBuilder == null ) { defaultProbeBuilder = system . createProbe ( ) ; } TestProbeBuilder probeBuilder = overwriteWithUserDefinition ( currentTestClass , testClassInstance ) ; if ( probeBuilder . getTempDir ( ) == null ) { probeBuilder . setTempDir ( defaultProbeBuilder . getTempDir ( ) ) ; } return probeBuilder ; }
|
Lazily creates a probe builder . The same probe builder will be reused for all test classes unless the default builder is overridden in a given class .
|
36,710
|
public static void streamCopy ( final InputStream in , final FileChannel out , final ProgressBar progressBar ) throws IOException { NullArgumentException . validateNotNull ( in , "Input stream" ) ; NullArgumentException . validateNotNull ( out , "Output stream" ) ; final long start = System . currentTimeMillis ( ) ; long bytes = 0 ; ProgressBar feedbackBar = progressBar ; if ( feedbackBar == null ) { feedbackBar = new NullProgressBar ( ) ; } try { ReadableByteChannel inChannel = Channels . newChannel ( in ) ; bytes = out . transferFrom ( inChannel , 0 , Integer . MAX_VALUE ) ; inChannel . close ( ) ; } finally { feedbackBar . increment ( bytes , bytes / Math . max ( System . currentTimeMillis ( ) - start , 1 ) ) ; feedbackBar . stop ( ) ; } }
|
Copy a stream to a destination . It does not close the streams .
|
36,711
|
public static void streamCopy ( final URL url , final FileChannel out , final ProgressBar progressBar ) throws IOException { NullArgumentException . validateNotNull ( url , "URL" ) ; InputStream is = null ; try { is = url . openStream ( ) ; streamCopy ( is , out , progressBar ) ; } finally { if ( is != null ) { is . close ( ) ; } } }
|
Copy a stream from an urlto a destination .
|
36,712
|
public void close ( ) throws IOException { if ( jarOutputStream != null ) { jarOutputStream . close ( ) ; } else if ( os != null ) { os . close ( ) ; } }
|
Closes the archive and releases file system resources . No more files or directories may be added after calling this method .
|
36,713
|
private void addDirectory ( File root , File directory , String targetPath , ZipOutputStream zos ) throws IOException { String prefix = targetPath ; if ( ! prefix . isEmpty ( ) && ! prefix . endsWith ( "/" ) ) { prefix += "/" ; } if ( ! directory . equals ( root ) ) { String path = normalizePath ( root , directory ) ; ZipEntry jarEntry = new ZipEntry ( prefix + path + "/" ) ; jarOutputStream . putNextEntry ( jarEntry ) ; } File [ ] children = directory . listFiles ( ) ; for ( File child : children ) { if ( child . isDirectory ( ) ) { addDirectory ( root , child , prefix , jarOutputStream ) ; } else { addFile ( root , child , prefix , jarOutputStream ) ; } } }
|
Recursively adds the contents of the given directory and all subdirectories to the given ZIP output stream .
|
36,714
|
private void addFile ( File root , File file , String prefix , ZipOutputStream zos ) throws IOException { FileInputStream fis = new FileInputStream ( file ) ; ZipEntry jarEntry = new ZipEntry ( prefix + normalizePath ( root , file ) ) ; zos . putNextEntry ( jarEntry ) ; StreamUtils . copyStream ( fis , zos , false ) ; fis . close ( ) ; }
|
Adds a given file to the given ZIP output stream .
|
36,715
|
private String normalizePath ( File root , File file ) { String relativePath = file . getPath ( ) . substring ( root . getPath ( ) . length ( ) + 1 ) ; String path = relativePath . replaceAll ( "\\" + File . separator , "/" ) ; return path ; }
|
Returns the relative path of the given file with respect to the root directory with all file separators replaced by slashes .
|
36,716
|
public void copyBootClasspathLibraries ( ) throws IOException { BootClasspathLibraryOption [ ] bootClasspathLibraryOptions = subsystem . getOptions ( BootClasspathLibraryOption . class ) ; for ( BootClasspathLibraryOption bootClasspathLibraryOption : bootClasspathLibraryOptions ) { UrlReference libraryUrl = bootClasspathLibraryOption . getLibraryUrl ( ) ; FileUtils . copyURLToFile ( new URL ( libraryUrl . getURL ( ) ) , createUnique ( libraryUrl . getURL ( ) , new File ( karafHome + "/lib" ) , new String [ ] { "jar" } ) ) ; } }
|
Copy jars specified as BootClasspathLibraryOption in system to the karaf lib path to make them available in the boot classpath
|
36,717
|
public void copyReferencedArtifactsToDeployFolder ( ) { File deploy = new File ( karafBase , "deploy" ) ; String [ ] fileEndings = new String [ ] { "jar" , "war" , "zip" , "kar" , "xml" } ; ProvisionOption < ? > [ ] options = subsystem . getOptions ( ProvisionOption . class ) ; for ( ProvisionOption < ? > option : options ) { try { File target = createUnique ( option . getURL ( ) , deploy , fileEndings ) ; FileUtils . copyURLToFile ( new URL ( option . getURL ( ) ) , target ) ; } catch ( Exception e ) { } } }
|
Copy dependencies specified as ProvisionOption in system to the deploy folder
|
36,718
|
public KarafFeaturesOption getDependenciesFeature ( ) { if ( subsystem == null ) { return null ; } try { File featuresXmlFile = new File ( karafBase , "test-dependencies.xml" ) ; Writer wr = new OutputStreamWriter ( new FileOutputStream ( featuresXmlFile ) , "UTF-8" ) ; writeDependenciesFeature ( wr , subsystem . getOptions ( ProvisionOption . class ) ) ; wr . close ( ) ; String repoUrl = "file:" + featuresXmlFile . toString ( ) . replaceAll ( "\\\\" , "/" ) . replaceAll ( " " , "%20" ) ; return new KarafFeaturesOption ( repoUrl , "test-dependencies" ) ; } catch ( IOException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
|
Create a feature for the test dependencies specified as ProvisionOption in the system
|
36,719
|
static void writeDependenciesFeature ( Writer writer , ProvisionOption < ? > ... provisionOptions ) { XMLOutputFactory xof = XMLOutputFactory . newInstance ( ) ; xof . setProperty ( "javax.xml.stream.isRepairingNamespaces" , true ) ; XMLStreamWriter sw = null ; try { sw = xof . createXMLStreamWriter ( writer ) ; sw . writeStartDocument ( "UTF-8" , "1.0" ) ; sw . setDefaultNamespace ( KARAF_FEATURE_NS ) ; sw . writeCharacters ( "\n" ) ; sw . writeStartElement ( "features" ) ; sw . writeAttribute ( "name" , "test-dependencies" ) ; sw . writeCharacters ( "\n" ) ; sw . writeStartElement ( "feature" ) ; sw . writeAttribute ( "name" , "test-dependencies" ) ; sw . writeCharacters ( "\n" ) ; for ( ProvisionOption < ? > provisionOption : provisionOptions ) { if ( provisionOption . getURL ( ) . startsWith ( "link" ) || provisionOption . getURL ( ) . startsWith ( "scan-features" ) ) { continue ; } sw . writeStartElement ( "bundle" ) ; if ( provisionOption . getStartLevel ( ) != null ) { sw . writeAttribute ( "start-level" , provisionOption . getStartLevel ( ) . toString ( ) ) ; } sw . writeCharacters ( provisionOption . getURL ( ) ) ; endElement ( sw ) ; } endElement ( sw ) ; endElement ( sw ) ; sw . writeEndDocument ( ) ; } catch ( XMLStreamException e ) { throw new RuntimeException ( "Error writing feature " + e . getMessage ( ) , e ) ; } finally { close ( sw ) ; } }
|
Write a feature xml structure for test dependencies specified as ProvisionOption in system to the given writer
|
36,720
|
public static void extract ( URL sourceURL , File targetFolder ) throws IOException { if ( sourceURL . getProtocol ( ) . equals ( "file" ) ) { if ( sourceURL . getFile ( ) . indexOf ( ".zip" ) > 0 ) { extractZipDistribution ( sourceURL , targetFolder ) ; } else if ( sourceURL . getFile ( ) . indexOf ( ".tar.gz" ) > 0 ) { extractTarGzDistribution ( sourceURL , targetFolder ) ; } else { throw new IllegalStateException ( "Unknow packaging of distribution; only zip or tar.gz could be handled." ) ; } return ; } if ( sourceURL . toExternalForm ( ) . indexOf ( "/zip" ) > 0 ) { extractZipDistribution ( sourceURL , targetFolder ) ; } else if ( sourceURL . toExternalForm ( ) . indexOf ( "/tar.gz" ) > 0 ) { extractTarGzDistribution ( sourceURL , targetFolder ) ; } else { throw new IllegalStateException ( "Unknow packaging; only zip or tar.gz could be handled. URL was " + sourceURL ) ; } }
|
Extract zip or tar . gz archives to a target folder
|
36,721
|
public CommandLineBuilder append ( final String [ ] segments ) { if ( segments != null && segments . length > 0 ) { final String [ ] command = new String [ commandLine . length + segments . length ] ; System . arraycopy ( commandLine , 0 , command , 0 , commandLine . length ) ; System . arraycopy ( segments , 0 , command , commandLine . length , segments . length ) ; commandLine = command ; } return this ; }
|
Appends an array of strings to command line .
|
36,722
|
public CommandLineBuilder append ( final String segment ) { if ( segment != null && ! segment . isEmpty ( ) ) { return append ( new String [ ] { segment } ) ; } return this ; }
|
Appends a string to command line .
|
36,723
|
public static String getArtifactVersion ( final String groupId , final String artifactId ) { final Properties dependencies = new Properties ( ) ; InputStream depInputStream = null ; try { String depFilePath = "META-INF/maven/dependencies.properties" ; URL fileURL = MavenUtils . class . getClassLoader ( ) . getResource ( depFilePath ) ; if ( fileURL == null ) { fileURL = Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( depFilePath ) ; } if ( fileURL == null ) { throw new FileNotFoundException ( "File [" + depFilePath + "] could not be found in classpath" ) ; } depInputStream = fileURL . openStream ( ) ; dependencies . load ( depInputStream ) ; final String version = dependencies . getProperty ( groupId + "/" + artifactId + "/version" ) ; if ( version == null ) { throw new IllegalArgumentException ( "Could not resolve version. Do you have a dependency for " + groupId + "/" + artifactId + " in your maven project?" ) ; } return version ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Could not resolve version for groupId:" + groupId + " artifactId:" + artifactId + " by reading the dependency information generated by maven." , e ) ; } finally { if ( depInputStream != null ) { try { depInputStream . close ( ) ; } catch ( IOException e ) { } } } }
|
Gets the artifact version out of dependencies file . The dependencies file had to be generated by using the maven plugin .
|
36,724
|
public static MavenArtifactUrlReference . VersionResolver asInProject ( ) { return new MavenArtifactUrlReference . VersionResolver ( ) { public String getVersion ( final String groupId , final String artifactId ) { return getArtifactVersion ( groupId , artifactId ) ; } } ; }
|
Utility method for creating an artifact version resolver that will get the version out of maven project .
|
36,725
|
public URI buildWar ( ) { if ( option . getName ( ) == null ) { option . name ( UUID . randomUUID ( ) . toString ( ) ) ; } processClassPath ( ) ; try { File webResourceDir = getWebResourceDir ( ) ; File probeWar = new File ( tempDir , option . getName ( ) + ".war" ) ; ZipBuilder builder = new ZipBuilder ( probeWar ) ; for ( String library : option . getLibraries ( ) ) { File file = toLocalFile ( library ) ; if ( file . isDirectory ( ) ) { file = toJar ( file ) ; } LOG . debug ( "including library {} = {}" , library , file ) ; builder . addFile ( file , "WEB-INF/lib/" + file . getName ( ) ) ; } builder . addDirectory ( webResourceDir , "" ) ; builder . close ( ) ; URI warUri = probeWar . toURI ( ) ; LOG . info ( "WAR probe = {}" , warUri ) ; return warUri ; } catch ( IOException exc ) { throw new TestContainerException ( exc ) ; } }
|
Builds a WAR from the given option .
|
36,726
|
private static void daxpy ( double constant , double vector1 [ ] , double vector2 [ ] ) { if ( constant == 0 ) return ; assert vector1 . length == vector2 . length ; for ( int i = 0 ; i < vector1 . length ; i ++ ) { vector2 [ i ] += constant * vector1 [ i ] ; } }
|
constant times a vector plus a vector
|
36,727
|
private static double dot ( double vector1 [ ] , double vector2 [ ] ) { double product = 0 ; assert vector1 . length == vector2 . length ; for ( int i = 0 ; i < vector1 . length ; i ++ ) { product += vector1 [ i ] * vector2 [ i ] ; } return product ; }
|
returns the dot product of two vectors
|
36,728
|
private static double euclideanNorm ( double vector [ ] ) { int n = vector . length ; if ( n < 1 ) { return 0 ; } if ( n == 1 ) { return Math . abs ( vector [ 0 ] ) ; } double scale = 0 ; double sum = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vector [ i ] != 0 ) { double abs = Math . abs ( vector [ i ] ) ; if ( scale < abs ) { double t = scale / abs ; sum = 1 + sum * ( t * t ) ; scale = abs ; } else { double t = abs / scale ; sum += t * t ; } } } return scale * Math . sqrt ( sum ) ; }
|
returns the euclidean norm of a vector
|
36,729
|
private static void scale ( double constant , double vector [ ] ) { if ( constant == 1.0 ) return ; for ( int i = 0 ; i < vector . length ; i ++ ) { vector [ i ] *= constant ; } }
|
scales a vector by a constant
|
36,730
|
@ SuppressWarnings ( "unused" ) public void setAutoScaleEnabled ( boolean isAutoScaleEnabled ) { this . isAutoScaleEnabled = isAutoScaleEnabled ; for ( int i = 0 , size = foldableItemsMap . size ( ) ; i < size ; i ++ ) { foldableItemsMap . valueAt ( i ) . setAutoScaleEnabled ( isAutoScaleEnabled ) ; } }
|
Sets whether view should scale down to fit moving part into screen .
|
36,731
|
public void setFoldRotation ( float rotation ) { foldRotation = rotation ; topPart . applyFoldRotation ( rotation ) ; bottomPart . applyFoldRotation ( rotation ) ; setInTransformation ( rotation != 0f ) ; scaleFactor = 1f ; if ( isAutoScaleEnabled && width > 0 ) { double sin = Math . abs ( Math . sin ( Math . toRadians ( rotation ) ) ) ; float dw = ( float ) ( height * sin ) * CAMERA_DISTANCE_MAGIC_FACTOR ; scaleFactor = width / ( width + dw ) ; setScale ( scale ) ; } }
|
Fold rotation value in degrees .
|
36,732
|
public void setRollingDistance ( float distance ) { final float scaleY = scale * scaleFactor * scaleFactorY ; topPart . applyRollingDistance ( distance , scaleY ) ; bottomPart . applyRollingDistance ( distance , scaleY ) ; }
|
Translation preserving middle line splitting .
|
36,733
|
public void unfold ( View coverView , View detailsView ) { if ( this . coverView == coverView && this . detailsView == detailsView ) { scrollToPosition ( 1 ) ; return ; } if ( ( this . coverView != null && this . coverView != coverView ) || ( this . detailsView != null && this . detailsView != detailsView ) ) { scheduledCoverView = coverView ; scheduledDetailsView = detailsView ; foldBack ( ) ; return ; } ViewGroup parent = ( ViewGroup ) getParent ( ) ; origClipChildren = true ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { origClipChildren = parent . getClipChildren ( ) ; } parent . setClipChildren ( false ) ; setCoverViewInternal ( coverView ) ; setDetailsViewInternal ( detailsView ) ; setAdapter ( adapter ) ; setState ( STATE_UNFOLDING ) ; scrollToPosition ( 1 ) ; }
|
Starting unfold animation for given views .
|
36,734
|
public BytesWritable evaluate ( BytesWritable geomref ) { if ( geomref == null || geomref . getLength ( ) == 0 ) { LogUtils . Log_ArgumentsNull ( LOG ) ; return null ; } OGCGeometry ogcGeometry = GeometryUtils . geometryFromEsriShape ( geomref ) ; if ( ogcGeometry == null ) { LogUtils . Log_ArgumentsNull ( LOG ) ; return null ; } if ( GeometryUtils . getType ( geomref ) == GeometryUtils . OGCType . ST_LINESTRING ) { MultiPath lines = ( MultiPath ) ( ogcGeometry . getEsriGeometry ( ) ) ; int wkid = GeometryUtils . getWKID ( geomref ) ; SpatialReference spatialReference = null ; if ( wkid != GeometryUtils . WKID_UNKNOWN ) { spatialReference = SpatialReference . create ( wkid ) ; } return GeometryUtils . geometryToEsriShapeBytesWritable ( OGCGeometry . createFromEsriGeometry ( lines . getPoint ( lines . getPointCount ( ) - 1 ) , spatialReference ) ) ; } else { LogUtils . Log_InvalidType ( LOG , GeometryUtils . OGCType . ST_LINESTRING , GeometryUtils . getType ( geomref ) ) ; return null ; } }
|
Return the last point of the ST_Linestring .
|
36,735
|
public long getId ( double x , double y ) { double down = ( extentMax - y ) / binSize ; double over = ( x - extentMin ) / binSize ; return ( ( long ) down * numCols ) + ( long ) over ; }
|
Gets bin ID from a point .
|
36,736
|
public void queryEnvelope ( long binId , Envelope envelope ) { long down = binId / numCols ; long over = binId % numCols ; double xmin = extentMin + ( over * binSize ) ; double xmax = xmin + binSize ; double ymax = extentMax - ( down * binSize ) ; double ymin = ymax - binSize ; envelope . setCoords ( xmin , ymin , xmax , ymax ) ; }
|
Gets the envelope for the bin ID .
|
36,737
|
public void queryEnvelope ( double x , double y , Envelope envelope ) { double down = ( extentMax - y ) / binSize ; double over = ( x - extentMin ) / binSize ; double xmin = extentMin + ( over * binSize ) ; double xmax = xmin + binSize ; double ymax = extentMax - ( down * binSize ) ; double ymin = ymax - binSize ; envelope . setCoords ( xmin , ymin , xmax , ymax ) ; }
|
Gets the envelope for the bin that contains the x y coords .
|
36,738
|
public boolean next ( LongWritable key , Text value ) throws IOException { JsonToken token ; if ( parser == null ) { parser = new JsonFactory ( ) . createJsonParser ( inputStream ) ; parser . setCodec ( new ObjectMapper ( ) ) ; token = parser . nextToken ( ) ; while ( token != null && ! ( token == JsonToken . START_ARRAY && parser . getCurrentName ( ) != null && parser . getCurrentName ( ) . equals ( "features" ) ) ) { token = parser . nextToken ( ) ; } if ( token == null ) return false ; } key . set ( parser . getCurrentLocation ( ) . getCharOffset ( ) ) ; token = parser . nextToken ( ) ; if ( token == null || ! ( token == JsonToken . START_OBJECT && parser . getCurrentName ( ) == null ) ) return false ; ObjectNode node = parser . readValueAsTree ( ) ; value . set ( node . toString ( ) ) ; return true ; }
|
Both Esri JSON and GeoJSON conveniently have features
|
36,739
|
public static void Log_SRIDMismatch ( Log logger , BytesWritable geomref1 , BytesWritable geomref2 ) { logger . error ( String . format ( messages [ MSG_SRID_MISMATCH ] , GeometryUtils . getWKID ( geomref1 ) , GeometryUtils . getWKID ( geomref2 ) ) ) ; }
|
Log when comparing geometries in different spatial references
|
36,740
|
public static int getWKID ( BytesWritable geomref ) { ByteBuffer bb = ByteBuffer . wrap ( geomref . getBytes ( ) ) ; return bb . getInt ( 0 ) ; }
|
Gets the WKID for the given hive geometry bytes
|
36,741
|
protected boolean moveToRecordStart ( ) throws IOException { int next = 0 ; long resetPosition = readerPosition ; while ( true ) { while ( next != '{' ) { next = getChar ( ) ; if ( next < 0 ) { return false ; } } resetPosition = readerPosition ; inputReader . mark ( 100 ) ; next = getNonWhite ( ) ; if ( next < 0 ) { return false ; } if ( next != '"' ) { continue ; } boolean inEscape = false ; String fieldName = "" ; while ( next != '{' ) { next = getChar ( ) ; if ( next < 0 ) { return false ; } inEscape = ( ! inEscape && next == '\\' ) ; if ( ! inEscape && next == '"' ) { break ; } fieldName += ( char ) next ; } if ( ! ( fieldName . equals ( "attributes" ) || fieldName . equals ( "geometry" ) ) ) { continue ; } next = getNonWhite ( ) ; if ( next < 0 ) { return false ; } if ( next != ':' ) { continue ; } next = getNonWhite ( ) ; if ( next < 0 ) { return false ; } if ( next == '{' ) { break ; } } inputReader . reset ( ) ; readerPosition = resetPosition ; firstBraceConsumed = true ; return true ; }
|
Given an arbitrary byte offset into a unenclosed JSON document find the start of the next record in the document . Discard trailing bytes from the previous record if we happened to seek to the middle of it
|
36,742
|
public float getProgress ( ) throws IOException { if ( reachedEnd ) return 1 ; else { final long filePos = in . position ( ) ; final long fileEnd = virtualEnd >>> 16 ; return ( float ) ( filePos - fileStart ) / ( fileEnd - fileStart + 1 ) ; } }
|
Unless the end has been reached this only takes file position into account not the position within the block .
|
36,743
|
private int guessNextBGZFPos ( int p , int end ) throws IOException { for ( ; ; ) { for ( ; ; ) { in . seek ( p ) ; in . read ( buf . array ( ) , 0 , 4 ) ; int n = buf . getInt ( 0 ) ; if ( n == BGZF_MAGIC ) break ; if ( n >>> 8 == BGZF_MAGIC << 8 >>> 8 ) ++ p ; else if ( n >>> 16 == BGZF_MAGIC << 16 >>> 16 ) p += 2 ; else p += 3 ; if ( p >= end ) return - 1 ; } final int p0 = p ; p += 10 ; in . seek ( p ) ; in . read ( buf . array ( ) , 0 , 2 ) ; p += 2 ; final int xlen = getUShort ( 0 ) ; final int subEnd = p + xlen ; while ( p < subEnd ) { in . read ( buf . array ( ) , 0 , 4 ) ; if ( buf . getInt ( 0 ) != BGZF_MAGIC_SUB ) { p += 4 + getUShort ( 2 ) ; in . seek ( p ) ; continue ; } return p0 ; } p = p0 + 4 ; } }
|
Returns a negative number if it doesn t find anything .
|
36,744
|
private static void writeTerminatorBlock ( final OutputStream out , final SAMFormat samOutputFormat ) throws IOException { if ( SAMFormat . CRAM == samOutputFormat ) { CramIO . issueEOF ( CramVersions . DEFAULT_CRAM_VERSION , out ) ; } else if ( SAMFormat . BAM == samOutputFormat ) { out . write ( BlockCompressedStreamConstants . EMPTY_GZIP_BLOCK ) ; } }
|
Terminate the aggregated output stream with an appropriate SAMOutputFormat - dependent terminator block
|
36,745
|
public static < T extends Locatable > void setIntervals ( Configuration conf , List < T > intervals ) { setTraversalParameters ( conf , intervals , false ) ; }
|
Only include reads that overlap the given intervals . Unplaced unmapped reads are not included .
|
36,746
|
public static void unsetTraversalParameters ( Configuration conf ) { conf . unset ( BOUNDED_TRAVERSAL_PROPERTY ) ; conf . unset ( INTERVALS_PROPERTY ) ; conf . unset ( TRAVERSE_UNPLACED_UNMAPPED_PROPERTY ) ; }
|
Reset traversal parameters so that all reads are included .
|
36,747
|
static QueryInterval [ ] prepareQueryIntervals ( final List < Interval > rawIntervals , final SAMSequenceDictionary sequenceDictionary ) { if ( rawIntervals == null || rawIntervals . isEmpty ( ) ) { return null ; } final QueryInterval [ ] convertedIntervals = rawIntervals . stream ( ) . map ( rawInterval -> convertSimpleIntervalToQueryInterval ( rawInterval , sequenceDictionary ) ) . toArray ( QueryInterval [ ] :: new ) ; return QueryInterval . optimizeIntervals ( convertedIntervals ) ; }
|
Converts a List of SimpleIntervals into the format required by the SamReader query API
|
36,748
|
private static QueryInterval convertSimpleIntervalToQueryInterval ( final Interval interval , final SAMSequenceDictionary sequenceDictionary ) { if ( interval == null ) { throw new IllegalArgumentException ( "interval may not be null" ) ; } if ( sequenceDictionary == null ) { throw new IllegalArgumentException ( "sequence dictionary may not be null" ) ; } final int contigIndex = sequenceDictionary . getSequenceIndex ( interval . getContig ( ) ) ; if ( contigIndex == - 1 ) { throw new IllegalArgumentException ( "Contig " + interval . getContig ( ) + " not present in reads sequence " + "dictionary" ) ; } return new QueryInterval ( contigIndex , interval . getStart ( ) , interval . getEnd ( ) ) ; }
|
Converts an interval in SimpleInterval format into an htsjdk QueryInterval .
|
36,749
|
public static void convertQuality ( Text quality , BaseQualityEncoding current , BaseQualityEncoding target ) { if ( current == target ) throw new IllegalArgumentException ( "current and target quality encodinds are the same (" + current + ")" ) ; byte [ ] bytes = quality . getBytes ( ) ; final int len = quality . getLength ( ) ; final int illuminaSangerDistance = FormatConstants . ILLUMINA_OFFSET - FormatConstants . SANGER_OFFSET ; if ( current == BaseQualityEncoding . Illumina && target == BaseQualityEncoding . Sanger ) { for ( int i = 0 ; i < len ; ++ i ) { if ( bytes [ i ] < FormatConstants . ILLUMINA_OFFSET || bytes [ i ] > ( FormatConstants . ILLUMINA_OFFSET + FormatConstants . ILLUMINA_MAX ) ) { throw new FormatException ( "base quality score out of range for Illumina Phred+64 format (found " + ( bytes [ i ] - FormatConstants . ILLUMINA_OFFSET ) + " but acceptable range is [0," + FormatConstants . ILLUMINA_MAX + "]).\n" + "Maybe qualities are encoded in Sanger format?\n" ) ; } bytes [ i ] -= illuminaSangerDistance ; } } else if ( current == BaseQualityEncoding . Sanger && target == BaseQualityEncoding . Illumina ) { for ( int i = 0 ; i < len ; ++ i ) { if ( bytes [ i ] < FormatConstants . SANGER_OFFSET || bytes [ i ] > ( FormatConstants . SANGER_OFFSET + FormatConstants . SANGER_MAX ) ) { throw new FormatException ( "base quality score out of range for Sanger Phred+64 format (found " + ( bytes [ i ] - FormatConstants . SANGER_OFFSET ) + " but acceptable range is [0," + FormatConstants . SANGER_MAX + "]).\n" + "Maybe qualities are encoded in Illumina format?\n" ) ; } bytes [ i ] += illuminaSangerDistance ; } } else throw new IllegalArgumentException ( "unsupported BaseQualityEncoding transformation from " + current + " to " + target ) ; }
|
Convert quality scores in - place .
|
36,750
|
public static int verifyQuality ( Text quality , BaseQualityEncoding encoding ) { int max , min ; if ( encoding == BaseQualityEncoding . Illumina ) { max = FormatConstants . ILLUMINA_OFFSET + FormatConstants . ILLUMINA_MAX ; min = FormatConstants . ILLUMINA_OFFSET ; } else if ( encoding == BaseQualityEncoding . Sanger ) { max = FormatConstants . SANGER_OFFSET + FormatConstants . SANGER_MAX ; min = FormatConstants . SANGER_OFFSET ; } else throw new IllegalArgumentException ( "Unsupported base encoding quality " + encoding ) ; final byte [ ] bytes = quality . getBytes ( ) ; final int len = quality . getLength ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( bytes [ i ] < min || bytes [ i ] > max ) return i ; } return - 1 ; }
|
Verify that the given quality bytes are within the range allowed for the specified encoding .
|
36,751
|
public static void main ( String [ ] args ) { if ( args . length == 0 ) { System . out . println ( "Usage: BGZFBlockIndex [BGZF block indices...]\n\n" + "Writes a few statistics about each BGZF block index." ) ; return ; } for ( String arg : args ) { final File f = new File ( arg ) ; if ( f . isFile ( ) && f . canRead ( ) ) { try { System . err . printf ( "%s:\n" , f ) ; final BGZFBlockIndex bi = new BGZFBlockIndex ( f ) ; final long second = bi . secondBlock ( ) ; final long last = bi . lastBlock ( ) ; System . err . printf ( "\t%d blocks\n" + "\tfirst after 0 is at %#014x\n" + "\tlast is at %#014x\n" + "\tassociated BGZF file size %d\n" , bi . size ( ) - 1 , bi . secondBlock ( ) , bi . lastBlock ( ) , bi . fileSize ( ) ) ; } catch ( IOException e ) { System . err . printf ( "Failed to read %s!\n" , f ) ; e . printStackTrace ( ) ; } } else System . err . printf ( "%s does not look like a readable file!\n" , f ) ; } }
|
Writes some statistics about each BGZF block index file given as an argument .
|
36,752
|
private void init ( final Path output , final SAMFileHeader header , final boolean writeHeader , final TaskAttemptContext ctx ) throws IOException { init ( output . getFileSystem ( ctx . getConfiguration ( ) ) . create ( output ) , header , writeHeader , ctx ) ; }
|
first statement ...
|
36,753
|
static List < Path > getFilesMatching ( Path directory , String syntaxAndPattern , String excludesExt ) throws IOException { PathMatcher matcher = directory . getFileSystem ( ) . getPathMatcher ( syntaxAndPattern ) ; List < Path > parts = Files . walk ( directory ) . filter ( matcher :: matches ) . filter ( path -> excludesExt == null || ! path . toString ( ) . endsWith ( excludesExt ) ) . collect ( Collectors . toList ( ) ) ; Collections . sort ( parts ) ; return parts ; }
|
Returns all the files in a directory that match the given pattern and that don t have the given extension .
|
36,754
|
static void mergeInto ( List < Path > parts , OutputStream out ) throws IOException { for ( final Path part : parts ) { Files . copy ( part , out ) ; Files . delete ( part ) ; } }
|
Merge the given part files in order into an output stream . This deletes the parts .
|
36,755
|
public List < InputSplit > getSplits ( JobContext job ) throws IOException { final List < InputSplit > splits = super . getSplits ( job ) ; Collections . sort ( splits , new Comparator < InputSplit > ( ) { public int compare ( InputSplit a , InputSplit b ) { FileSplit fa = ( FileSplit ) a , fb = ( FileSplit ) b ; return fa . getPath ( ) . compareTo ( fb . getPath ( ) ) ; } } ) ; final List < InputSplit > newSplits = new ArrayList < InputSplit > ( splits . size ( ) ) ; final Configuration cfg = job . getConfiguration ( ) ; for ( int i = 0 ; i < splits . size ( ) ; ) { try { i = addIndexedSplits ( splits , i , newSplits , cfg ) ; } catch ( IOException e ) { i = addProbabilisticSplits ( splits , i , newSplits , cfg ) ; } } return newSplits ; }
|
The splits returned are FileSplits .
|
36,756
|
public static WrapSeekable < FSDataInputStream > openPath ( FileSystem fs , Path p ) throws IOException { return new WrapSeekable < FSDataInputStream > ( fs . open ( p ) , fs . getFileStatus ( p ) . getLen ( ) , p ) ; }
|
A helper for the common use case .
|
36,757
|
public static SAMFileHeader readSAMHeaderFrom ( final InputStream in , final Configuration conf ) { final ValidationStringency stringency = getValidationStringency ( conf ) ; SamReaderFactory readerFactory = SamReaderFactory . makeDefault ( ) . setOption ( SamReaderFactory . Option . EAGERLY_DECODE , false ) . setUseAsyncIo ( false ) ; if ( stringency != null ) { readerFactory . validationStringency ( stringency ) ; } final ReferenceSource refSource = getReferenceSource ( conf ) ; if ( null != refSource ) { readerFactory . referenceSource ( refSource ) ; } return readerFactory . open ( SamInputResource . of ( in ) ) . getFileHeader ( ) ; }
|
Does not close the stream .
|
36,758
|
public long skip ( long n ) throws IOException { boolean end = false ; long toskip = n ; while ( toskip > 0 && ! end ) { if ( bufferPosn < bufferLength ) { int skipped = ( int ) Math . min ( bufferLength - bufferPosn , toskip ) ; bufferPosn += skipped ; toskip -= skipped ; } if ( bufferPosn >= bufferLength ) { int loaded = loadBuffer ( ) ; end = loaded == 0 ; } } return n - toskip ; }
|
Skip n bytes from the InputStream .
|
36,759
|
public float getProgress ( ) { if ( length == 0 ) return 1 ; if ( ! isBGZF ) return ( float ) ( in . getPosition ( ) - fileStart ) / length ; try { if ( in . peek ( ) == - 1 ) return 1 ; } catch ( IOException e ) { return 1 ; } return ( float ) ( ( bci . getFilePointer ( ) >>> 16 ) - fileStart ) / ( length + 1 ) ; }
|
For compressed BCF unless the end has been reached this is quite inaccurate .
|
36,760
|
public void processAlignment ( final SAMRecord rec ) throws IOException { if ( count == 0 || ( count + 1 ) % granularity == 0 ) { SAMFileSource fileSource = rec . getFileSource ( ) ; SAMFileSpan filePointer = fileSource . getFilePointer ( ) ; writeVirtualOffset ( getPos ( filePointer ) ) ; } count ++ ; }
|
Process the given record for the index .
|
36,761
|
public void writeVirtualOffset ( long virtualOffset ) throws IOException { lb . put ( 0 , virtualOffset ) ; out . write ( byteBuffer . array ( ) ) ; }
|
Write the given virtual offset to the index . This method is for internal use only .
|
36,762
|
public static void index ( final InputStream rawIn , final OutputStream out , final long inputSize , final int granularity ) throws IOException { final BlockCompressedInputStream in = new BlockCompressedInputStream ( rawIn ) ; final ByteBuffer byteBuffer = ByteBuffer . allocate ( 8 ) ; final LongBuffer lb = byteBuffer . order ( ByteOrder . BIG_ENDIAN ) . asLongBuffer ( ) ; skipToAlignmentList ( byteBuffer , in ) ; lb . put ( 0 , in . getFilePointer ( ) ) ; out . write ( byteBuffer . array ( ) ) ; long prevPrint = in . getFilePointer ( ) >> 16 ; for ( int i = 0 ; ; ) { final PtrSkipPair pair = readAlignment ( byteBuffer , in ) ; if ( pair == null ) break ; if ( ++ i == granularity ) { i = 0 ; lb . put ( 0 , pair . ptr ) ; out . write ( byteBuffer . array ( ) ) ; final long filePos = pair . ptr >> 16 ; if ( filePos - prevPrint >= PRINT_EVERY ) { System . out . print ( "-" ) ; prevPrint = filePos ; } } fullySkip ( in , pair . skip ) ; } lb . put ( 0 , inputSize << 16 ) ; out . write ( byteBuffer . array ( ) ) ; out . close ( ) ; in . close ( ) ; }
|
Perform indexing on the given BAM file at the granularity level specified .
|
36,763
|
public static List < Interval > getIntervals ( final Configuration conf , final String intervalPropertyName ) { final String intervalsProperty = conf . get ( intervalPropertyName ) ; if ( intervalsProperty == null ) { return null ; } if ( intervalsProperty . isEmpty ( ) ) { return ImmutableList . of ( ) ; } final List < Interval > intervals = new ArrayList < > ( ) ; for ( final String s : intervalsProperty . split ( "," ) ) { final int lastColonIdx = s . lastIndexOf ( ':' ) ; if ( lastColonIdx < 0 ) { throw new FormatException ( "no colon found in interval string: " + s ) ; } final int hyphenIdx = s . indexOf ( '-' , lastColonIdx + 1 ) ; if ( hyphenIdx < 0 ) { throw new FormatException ( "no hyphen found after colon interval string: " + s ) ; } final String sequence = s . substring ( 0 , lastColonIdx ) ; final int start = parseIntOrThrowFormatException ( s . substring ( lastColonIdx + 1 , hyphenIdx ) , "invalid start position" , s ) ; final int stop = parseIntOrThrowFormatException ( s . substring ( hyphenIdx + 1 ) , "invalid stop position" , s ) ; intervals . add ( new Interval ( sequence , start , stop ) ) ; } return intervals ; }
|
Returns the list of intervals found in a string configuration property separated by colons .
|
36,764
|
public long getLength ( ) { final long vsHi = vStart & ~ 0xffff ; final long veHi = vEnd & ~ 0xffff ; final long hiDiff = veHi - vsHi ; return hiDiff == 0 ? ( ( vEnd & 0xffff ) - ( vStart & 0xffff ) ) : hiDiff ; }
|
Inexact due to the nature of virtual offsets .
|
36,765
|
private void fixBCFSplits ( List < FileSplit > splits , List < InputSplit > newSplits ) throws IOException { Collections . sort ( splits , new Comparator < FileSplit > ( ) { public int compare ( FileSplit a , FileSplit b ) { return a . getPath ( ) . compareTo ( b . getPath ( ) ) ; } } ) ; for ( int i = 0 ; i < splits . size ( ) ; ) i = addGuessedSplits ( splits , i , newSplits ) ; }
|
FileVirtualSplits uncompressed in FileSplits .
|
36,766
|
public static boolean parseBoolean ( String value , boolean defaultValue ) { if ( value == null ) return defaultValue ; value = value . trim ( ) ; final String [ ] acceptedTrue = new String [ ] { "yes" , "true" , "t" , "y" , "1" } ; final String [ ] acceptedFalse = new String [ ] { "no" , "false" , "f" , "n" , "0" } ; for ( String possible : acceptedTrue ) { if ( possible . equalsIgnoreCase ( value ) ) return true ; } for ( String possible : acceptedFalse ) { if ( possible . equalsIgnoreCase ( value ) ) return false ; } throw new IllegalArgumentException ( "Unrecognized boolean value '" + value + "'" ) ; }
|
Convert a string to a boolean .
|
36,767
|
public static void main ( String [ ] args ) { if ( args . length == 0 ) { System . out . println ( "Usage: SplittingBAMIndex [splitting BAM indices...]\n\n" + "Writes a few statistics about each splitting BAM index." ) ; return ; } for ( String arg : args ) { final File f = new File ( arg ) ; if ( f . isFile ( ) && f . canRead ( ) ) { try { System . err . printf ( "%s:\n" , f ) ; final SplittingBAMIndex bi = new SplittingBAMIndex ( f ) ; if ( bi . size ( ) == 1 ) { System . err . printf ( "\t0 alignments\n" + "\tassociated BAM file size %d\n" , bi . bamSize ( ) ) ; } else { final long first = bi . first ( ) ; final long last = bi . last ( ) ; System . err . printf ( "\t%d alignments\n" + "\tfirst is at %#06x in BGZF block at %#014x\n" + "\tlast is at %#06x in BGZF block at %#014x\n" + "\tassociated BAM file size %d\n" , bi . size ( ) , first & 0xffff , first >>> 16 , last & 0xffff , last >>> 16 , bi . bamSize ( ) ) ; } } catch ( IOException e ) { System . err . printf ( "Failed to read %s!\n" , f ) ; e . printStackTrace ( ) ; } } else System . err . printf ( "%s does not look like a readable file!\n" , f ) ; } }
|
Writes some statistics about each splitting BAM index file given as an argument .
|
36,768
|
public static synchronized void cancelNetworkCall ( String url , String requestMethod , long endTime , String exception ) { if ( url != null ) { String id = sanitiseURL ( url ) ; if ( ( connections != null ) && ( connections . containsKey ( id ) ) ) { connections . remove ( id ) ; } } }
|
When a network request is cancelled we stop tracking it and do not send the information through . Future updates may include sending the cancelled request timing through with information showing it was cancelled .
|
36,769
|
private static int postRUM ( String apiKey , String jsonPayload ) { try { if ( validateApiKey ( apiKey ) ) { String endpoint = RaygunSettings . getRUMEndpoint ( ) ; MediaType MEDIA_TYPE_JSON = MediaType . parse ( "application/json; charset=utf-8" ) ; OkHttpClient client = new OkHttpClient . Builder ( ) . connectTimeout ( NETWORK_TIMEOUT , TimeUnit . SECONDS ) . writeTimeout ( NETWORK_TIMEOUT , TimeUnit . SECONDS ) . readTimeout ( NETWORK_TIMEOUT , TimeUnit . SECONDS ) . build ( ) ; RequestBody body = RequestBody . create ( MEDIA_TYPE_JSON , jsonPayload ) ; Request request = new Request . Builder ( ) . url ( endpoint ) . header ( "X-ApiKey" , apiKey ) . post ( body ) . build ( ) ; Response response = null ; try { response = client . newCall ( request ) . execute ( ) ; RaygunLogger . d ( "RUM HTTP POST result: " + response . code ( ) ) ; return response . code ( ) ; } catch ( IOException ioe ) { RaygunLogger . e ( "OkHttp POST to Raygun RUM backend failed - " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } finally { if ( response != null ) response . body ( ) . close ( ) ; } } } catch ( Exception e ) { RaygunLogger . e ( "Can't post to RUM. Exception - " + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } return - 1 ; }
|
Raw post method that delivers a pre - built RUM payload to the Raygun API .
|
36,770
|
public static void init ( Context context ) { String apiKey = readApiKey ( context ) ; init ( context , apiKey ) ; }
|
Initializes the Raygun client . This expects that you have placed the API key in your AndroidManifest . xml in a meta - data element .
|
36,771
|
public static void init ( Context context , String apiKey ) { RaygunClient . apiKey = apiKey ; RaygunClient . context = context ; RaygunClient . appContextIdentifier = UUID . randomUUID ( ) . toString ( ) ; RaygunLogger . d ( "Configuring Raygun (v" + RaygunSettings . RAYGUN_CLIENT_VERSION + ")" ) ; try { RaygunClient . version = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) . versionName ; } catch ( PackageManager . NameNotFoundException e ) { RaygunClient . version = "Not provided" ; RaygunLogger . w ( "Couldn't read application version from calling package" ) ; } }
|
Initializes the Raygun client with your Android application s context and your Raygun API key . The version transmitted will be the value of the versionName attribute in your manifest element .
|
36,772
|
public static void init ( Context context , String apiKey , String version ) { init ( context , apiKey ) ; RaygunClient . version = version ; }
|
Initializes the Raygun client with your Android application s context your Raygun API key and the version of your application
|
36,773
|
public static void send ( Throwable throwable , List tags , Map userCustomData ) { RaygunMessage msg = buildMessage ( throwable ) ; if ( msg == null ) { RaygunLogger . e ( "Failed to send RaygunMessage - due to invalid message being built" ) ; return ; } msg . getDetails ( ) . setTags ( RaygunUtils . mergeLists ( RaygunClient . tags , tags ) ) ; msg . getDetails ( ) . setUserCustomData ( RaygunUtils . mergeMaps ( RaygunClient . userCustomData , userCustomData ) ) ; if ( RaygunClient . onBeforeSend != null ) { msg = RaygunClient . onBeforeSend . onBeforeSend ( msg ) ; if ( msg == null ) { return ; } } enqueueWorkForCrashReportingService ( RaygunClient . apiKey , new Gson ( ) . toJson ( msg ) ) ; postCachedMessages ( ) ; }
|
Sends an exception - type object to Raygun with a list of tags you specify and a set of custom data .
|
36,774
|
public static void sendPulseTimingEvent ( RaygunPulseEventType eventType , String name , long milliseconds ) { if ( RaygunClient . sessionId == null ) { sendPulseEvent ( RaygunSettings . RUM_EVENT_SESSION_START ) ; } if ( eventType == RaygunPulseEventType . ACTIVITY_LOADED ) { if ( RaygunClient . shouldIgnoreView ( name ) ) { return ; } } RaygunPulseMessage message = new RaygunPulseMessage ( ) ; RaygunPulseDataMessage dataMessage = new RaygunPulseDataMessage ( ) ; SimpleDateFormat df = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss" ) ; df . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; Calendar c = Calendar . getInstance ( ) ; c . add ( Calendar . MILLISECOND , - ( int ) milliseconds ) ; String timestamp = df . format ( c . getTime ( ) ) ; dataMessage . setTimestamp ( timestamp ) ; dataMessage . setSessionId ( RaygunClient . sessionId ) ; dataMessage . setVersion ( RaygunClient . version ) ; dataMessage . setOS ( "Android" ) ; dataMessage . setOSVersion ( Build . VERSION . RELEASE ) ; dataMessage . setPlatform ( String . format ( "%s %s" , Build . MANUFACTURER , Build . MODEL ) ) ; dataMessage . setType ( "mobile_event_timing" ) ; RaygunUserContext userContext ; if ( RaygunClient . userInfo == null ) { userContext = new RaygunUserContext ( new RaygunUserInfo ( null , null , null , null , null , true ) , RaygunClient . context ) ; } else { userContext = new RaygunUserContext ( RaygunClient . userInfo , RaygunClient . context ) ; } dataMessage . setUser ( userContext ) ; RaygunPulseData data = new RaygunPulseData ( ) ; RaygunPulseTimingMessage timingMessage = new RaygunPulseTimingMessage ( ) ; timingMessage . setType ( eventType == RaygunPulseEventType . ACTIVITY_LOADED ? "p" : "n" ) ; timingMessage . setDuration ( milliseconds ) ; data . setName ( name ) ; data . setTiming ( timingMessage ) ; RaygunPulseData [ ] dataArray = new RaygunPulseData [ ] { data } ; String dataStr = new Gson ( ) . toJson ( dataArray ) ; dataMessage . setData ( dataStr ) ; message . setEventData ( new RaygunPulseDataMessage [ ] { dataMessage } ) ; enqueueWorkForRUMService ( RaygunClient . apiKey , new Gson ( ) . toJson ( message ) ) ; }
|
Sends a pulse timing event to Raygun . The message is sent on a background thread .
|
36,775
|
public static < T extends Tag , V > void register ( Class < T > tag , Class < V > type , TagConverter < T , V > converter ) throws ConverterRegisterException { if ( tagToConverter . containsKey ( tag ) ) { throw new ConverterRegisterException ( "Type conversion to tag " + tag . getName ( ) + " is already registered." ) ; } if ( typeToConverter . containsKey ( type ) ) { throw new ConverterRegisterException ( "Tag conversion to type " + type . getName ( ) + " is already registered." ) ; } tagToConverter . put ( tag , converter ) ; typeToConverter . put ( type , converter ) ; }
|
Registers a converter .
|
36,776
|
public static < T extends Tag , V > void unregister ( Class < T > tag , Class < V > type ) { tagToConverter . remove ( tag ) ; typeToConverter . remove ( type ) ; }
|
Unregisters a converter .
|
36,777
|
public static < T extends Tag , V > V convertToValue ( T tag ) throws ConversionException { if ( tag == null || tag . getValue ( ) == null ) { return null ; } if ( ! tagToConverter . containsKey ( tag . getClass ( ) ) ) { throw new ConversionException ( "Tag type " + tag . getClass ( ) . getName ( ) + " has no converter." ) ; } TagConverter < T , ? > converter = ( TagConverter < T , ? > ) tagToConverter . get ( tag . getClass ( ) ) ; return ( V ) converter . convert ( tag ) ; }
|
Converts the given tag to a value .
|
36,778
|
public static < V , T extends Tag > T convertToTag ( String name , V value ) throws ConversionException { if ( value == null ) { return null ; } TagConverter < T , V > converter = ( TagConverter < T , V > ) typeToConverter . get ( value . getClass ( ) ) ; if ( converter == null ) { for ( Class < ? > clazz : getAllClasses ( value . getClass ( ) ) ) { if ( typeToConverter . containsKey ( clazz ) ) { try { converter = ( TagConverter < T , V > ) typeToConverter . get ( clazz ) ; break ; } catch ( ClassCastException e ) { } } } } if ( converter == null ) { throw new ConversionException ( "Value type " + value . getClass ( ) . getName ( ) + " has no converter." ) ; } return converter . convert ( name , value ) ; }
|
Converts the given value to a tag .
|
36,779
|
public static void writeTag ( OutputStream out , Tag tag ) throws IOException { writeTag ( out , tag , false ) ; }
|
Writes an NBT tag in big endian .
|
36,780
|
public void setValue ( List < Tag > value ) throws IllegalArgumentException { this . type = null ; this . value . clear ( ) ; for ( Tag tag : value ) { this . add ( tag ) ; } }
|
Sets the value of this tag . The list tag s type will be set to that of the first tag being added or null if the given list is empty .
|
36,781
|
public boolean add ( Tag tag ) throws IllegalArgumentException { if ( tag == null ) { return false ; } if ( this . type == null ) { this . type = tag . getClass ( ) ; } else if ( tag . getClass ( ) != this . type ) { throw new IllegalArgumentException ( "Tag type cannot differ from ListTag type." ) ; } return this . value . add ( tag ) ; }
|
Adds a tag to this list tag . If the list does not yet have a type it will be set to the type of the tag being added .
|
36,782
|
public void setValue ( Map < String , Tag > value ) { this . value = new LinkedHashMap < String , Tag > ( value ) ; }
|
Sets the value of this tag .
|
36,783
|
public < T extends Tag > T get ( String tagName ) { return ( T ) this . value . get ( tagName ) ; }
|
Gets the tag with the specified name .
|
36,784
|
public < T extends Tag > T put ( T tag ) { return ( T ) this . value . put ( tag . getName ( ) , tag ) ; }
|
Puts the tag into this compound tag .
|
36,785
|
public < T extends Tag > T remove ( String tagName ) { return ( T ) this . value . remove ( tagName ) ; }
|
Removes a tag from this compound tag .
|
36,786
|
public static void register ( int id , Class < ? extends Tag > tag ) throws TagRegisterException { if ( idToTag . containsKey ( id ) ) { throw new TagRegisterException ( "Tag ID \"" + id + "\" is already in use." ) ; } if ( tagToId . containsKey ( tag ) ) { throw new TagRegisterException ( "Tag \"" + tag . getSimpleName ( ) + "\" is already registered." ) ; } idToTag . put ( id , tag ) ; tagToId . put ( tag , id ) ; }
|
Registers a tag class .
|
36,787
|
public static Class < ? extends Tag > getClassFor ( int id ) { if ( ! idToTag . containsKey ( id ) ) { return null ; } return idToTag . get ( id ) ; }
|
Gets the tag class with the given id .
|
36,788
|
public static int getIdFor ( Class < ? extends Tag > clazz ) { if ( ! tagToId . containsKey ( clazz ) ) { return - 1 ; } return tagToId . get ( clazz ) ; }
|
Gets the id of the given tag class .
|
36,789
|
public static Tag createInstance ( int id , String tagName ) throws TagCreateException { Class < ? extends Tag > clazz = idToTag . get ( id ) ; if ( clazz == null ) { throw new TagCreateException ( "Could not find tag with ID \"" + id + "\"." ) ; } try { Constructor < ? extends Tag > constructor = clazz . getDeclaredConstructor ( String . class ) ; constructor . setAccessible ( true ) ; return constructor . newInstance ( tagName ) ; } catch ( Exception e ) { throw new TagCreateException ( "Failed to create instance of tag \"" + clazz . getSimpleName ( ) + "\"." , e ) ; } }
|
Creates an instance of the tag with the given id using the String constructor .
|
36,790
|
protected synchronized void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { int width = 200 ; if ( MeasureSpec . UNSPECIFIED != MeasureSpec . getMode ( widthMeasureSpec ) ) { width = MeasureSpec . getSize ( widthMeasureSpec ) ; } int height = thumbImage . getHeight ( ) + ( ! showTextAboveThumbs ? 0 : PixelUtil . dpToPx ( getContext ( ) , HEIGHT_IN_DP ) ) + ( thumbShadow ? thumbShadowYOffset + thumbShadowBlur : 0 ) ; if ( MeasureSpec . UNSPECIFIED != MeasureSpec . getMode ( heightMeasureSpec ) ) { height = Math . min ( height , MeasureSpec . getSize ( heightMeasureSpec ) ) ; } setMeasuredDimension ( width , height ) ; }
|
Ensures correct size of the widget .
|
36,791
|
private void drawThumb ( float screenCoord , boolean pressed , Canvas canvas , boolean areSelectedValuesDefault ) { Bitmap buttonToDraw ; if ( ! activateOnDefaultValues && areSelectedValuesDefault ) { buttonToDraw = thumbDisabledImage ; } else { buttonToDraw = pressed ? thumbPressedImage : thumbImage ; } canvas . drawBitmap ( buttonToDraw , screenCoord - thumbHalfWidth , textOffset , paint ) ; }
|
Draws the normal resp . pressed thumb image on specified x - coordinate .
|
36,792
|
private void drawThumbShadow ( float screenCoord , Canvas canvas ) { thumbShadowMatrix . setTranslate ( screenCoord + thumbShadowXOffset , textOffset + thumbHalfHeight + thumbShadowYOffset ) ; translatedThumbShadowPath . set ( thumbShadowPath ) ; translatedThumbShadowPath . transform ( thumbShadowMatrix ) ; canvas . drawPath ( translatedThumbShadowPath , shadowPaint ) ; }
|
Draws a drop shadow beneath the slider thumb .
|
36,793
|
private void setNormalizedMinValue ( double value ) { normalizedMinValue = Math . max ( 0d , Math . min ( 1d , Math . min ( value , normalizedMaxValue ) ) ) ; invalidate ( ) ; }
|
Sets normalized min value to value so that 0 < = value < = normalized max value < = 1 . The View will get invalidated when calling this method .
|
36,794
|
private void setNormalizedMaxValue ( double value ) { normalizedMaxValue = Math . max ( 0d , Math . min ( 1d , Math . max ( value , normalizedMinValue ) ) ) ; invalidate ( ) ; }
|
Sets normalized max value to value so that 0 < = normalized min value < = value < = 1 . The View will get invalidated when calling this method .
|
36,795
|
@ SuppressWarnings ( "unchecked" ) protected T normalizedToValue ( double normalized ) { double v = absoluteMinValuePrim + normalized * ( absoluteMaxValuePrim - absoluteMinValuePrim ) ; return ( T ) numberType . toNumber ( Math . round ( v * 100 ) / 100d ) ; }
|
Converts a normalized value to a Number object in the value space between absolute minimum and maximum .
|
36,796
|
protected double valueToNormalized ( T value ) { if ( 0 == absoluteMaxValuePrim - absoluteMinValuePrim ) { return 0d ; } return ( value . doubleValue ( ) - absoluteMinValuePrim ) / ( absoluteMaxValuePrim - absoluteMinValuePrim ) ; }
|
Converts the given Number value to a normalized double .
|
36,797
|
private double screenToNormalized ( float screenCoord ) { int width = getWidth ( ) ; if ( width <= 2 * padding ) { return 0d ; } else { double result = ( screenCoord - padding ) / ( width - 2 * padding ) ; return Math . min ( 1d , Math . max ( 0d , result ) ) ; } }
|
Converts screen space x - coordinates into normalized values .
|
36,798
|
public static < K > void updateWeights ( double l2 , double learningRate , Map < K , Double > weights , Map < K , Double > newWeights ) { if ( l2 > 0.0 ) { for ( Map . Entry < K , Double > e : weights . entrySet ( ) ) { K column = e . getKey ( ) ; newWeights . put ( column , newWeights . get ( column ) + l2 * e . getValue ( ) * ( - learningRate ) ) ; } } }
|
Updates the weights by applying the L2 regularization .
|
36,799
|
public static < K > double estimatePenalty ( double l2 , Map < K , Double > weights ) { double penalty = 0.0 ; if ( l2 > 0.0 ) { double sumWeightsSquared = 0.0 ; for ( double w : weights . values ( ) ) { sumWeightsSquared += w * w ; } penalty = l2 * sumWeightsSquared / 2.0 ; } return penalty ; }
|
Estimates the penalty by adding the L2 regularization .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.