idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
25,200 | @ Override public void close ( ) { if ( parent != null ) parent . remove ( this ) ; setState ( State . DISPOSED ) ; setBatch ( null ) ; } | Disposes this layer removing it from its parent layer . Any resources associated with this layer are freed and it cannot be reused after being disposed . Disposing a layer that has children will dispose them as well . | 40 | 41 |
25,201 | public AffineTransform transform ( ) { if ( isSet ( Flag . XFDIRTY ) ) { float sina = FloatMath . sin ( rotation ) , cosa = FloatMath . cos ( rotation ) ; float m00 = cosa * scaleX , m01 = sina * scaleX ; float m10 = - sina * scaleY , m11 = cosa * scaleY ; float tx = transform . tx ( ) , ty = transform . ty ( ) ; transform . setTransform ( m00 , m01 , m10 , m11 , tx , ty ) ; setFlag ( Flag . XFDIRTY , false ) ; } return transform ; } | Returns the layer s current transformation matrix . If any changes have been made to the layer s scale rotation or translation they will be applied to the transform matrix before it is returned . | 141 | 35 |
25,202 | public float originX ( ) { if ( isSet ( Flag . ODIRTY ) ) { float width = width ( ) ; if ( width > 0 ) { this . originX = origin . ox ( width ) ; this . originY = origin . oy ( height ( ) ) ; setFlag ( Flag . ODIRTY , false ) ; } } return originX ; } | Returns the x - component of the layer s origin . | 79 | 11 |
25,203 | public float originY ( ) { if ( isSet ( Flag . ODIRTY ) ) { float height = height ( ) ; if ( height > 0 ) { this . originX = origin . ox ( width ( ) ) ; this . originY = origin . oy ( height ) ; setFlag ( Flag . ODIRTY , false ) ; } } return originY ; } | Returns the y - component of the layer s origin . | 79 | 11 |
25,204 | public Layer setOrigin ( Origin origin ) { this . origin = origin ; setFlag ( Flag . ODIRTY , true ) ; return this ; } | Configures the origin of this layer based on a logical location which is recomputed whenever the layer changes size . | 31 | 23 |
25,205 | public void debugPrint ( final Log log ) { this . visit ( new Visitor ( ) { public void visit ( Layer layer , int depth ) { String prefix = repeat ( ' ' , depth ) ; log . debug ( prefix + layer . toString ( ) ) ; } } ) ; } | Prints a debug representation of this layer and its children . | 61 | 12 |
25,206 | public SoundImpl < ? > createSound ( AssetFileDescriptor fd ) { PooledSound sound = new PooledSound ( pool . load ( fd , 1 ) ) ; loadingSounds . put ( sound . soundId , sound ) ; return sound ; } | Creates a sound instance from the supplied asset file descriptor . | 56 | 12 |
25,207 | public SoundImpl < ? > createSound ( FileDescriptor fd , long offset , long length ) { PooledSound sound = new PooledSound ( pool . load ( fd , offset , length , 1 ) ) ; loadingSounds . put ( sound . soundId , sound ) ; return sound ; } | Creates a sound instance from the supplied file descriptor offset . | 65 | 12 |
25,208 | public int compareTo ( ByteBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; byte thisByte , otherByte ; while ( compareRemaining > 0 ) { thisByte = get ( thisPos ) ; otherByte = otherBuffer . get ( otherPos ) ; if ( thisByte != otherByte ) { return thisByte < otherByte ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } return remaining ( ) - otherBuffer . remaining ( ) ; } | Compares the remaining bytes of this buffer to another byte buffer s remaining bytes . | 141 | 16 |
25,209 | public final ByteBuffer get ( byte [ ] dest , int off , int len ) { int length = dest . length ; if ( off < 0 || len < 0 || ( long ) off + ( long ) len > length ) { throw new IndexOutOfBoundsException ( ) ; } if ( len > remaining ( ) ) { throw new BufferUnderflowException ( ) ; } for ( int i = 0 ; i < len ; i ++ ) { dest [ i + off ] = get ( position + i ) ; } position += len ; return this ; } | Reads bytes from the current position into the specified byte array starting at the specified offset and increases the position by the number of bytes read . | 117 | 28 |
25,210 | public ByteBuffer put ( byte [ ] src , int off , int len ) { int length = src . length ; if ( off < 0 || len < 0 || off + len > length ) { throw new IndexOutOfBoundsException ( ) ; } if ( len > remaining ( ) ) { throw new BufferOverflowException ( ) ; } for ( int i = 0 ; i < len ; i ++ ) { byteArray . set ( i + position , src [ off + i ] ) ; } position += len ; return this ; } | Writes bytes in the given byte array starting from the specified offset to the current position and increases the position by the number of bytes written . | 113 | 28 |
25,211 | @ Override public void close ( ) { if ( ! disposed ) { disposed = true ; if ( gfx . exec ( ) . isMainThread ( ) ) { gfx . gl . glDeleteTexture ( id ) ; } else { gfx . exec ( ) . invokeNextFrame ( new Runnable ( ) { public void run ( ) { gfx . gl . glDeleteTexture ( id ) ; } } ) ; } } } | Deletes this texture s GPU resources and renders it unusable . | 93 | 13 |
25,212 | public void onSurfaceChanged ( int pixelWidth , int pixelHeight , int orient ) { viewportChanged ( pixelWidth , pixelHeight ) ; screenSize . setSize ( viewSize ) ; switch ( orient ) { case Configuration . ORIENTATION_LANDSCAPE : orientDetailM . update ( OrientationDetail . LANDSCAPE_LEFT ) ; break ; case Configuration . ORIENTATION_PORTRAIT : orientDetailM . update ( OrientationDetail . PORTRAIT ) ; break ; default : // Configuration.ORIENTATION_UNDEFINED orientDetailM . update ( OrientationDetail . UNKNOWN ) ; break ; } } | Informs the graphics system that the surface into which it is rendering has changed size . The supplied width and height are in pixels not display units . | 144 | 29 |
25,213 | void viewDidInit ( CGRect bounds ) { defaultFramebuffer = gl . glGetInteger ( GL20 . GL_FRAMEBUFFER_BINDING ) ; if ( defaultFramebuffer == 0 ) throw new IllegalStateException ( "Failed to determine defaultFramebuffer" ) ; boundsChanged ( bounds ) ; } | called when our view appears | 68 | 5 |
25,214 | public RFuture < String > getText ( Keyboard . TextType textType , String label , String initialValue ) { return getText ( textType , label , initialValue , "Ok" , "Cancel" ) ; } | Requests a line of text from the user . On platforms that have only a virtual keyboard this will display a text entry interface obtain the line of text and dismiss the text entry interface when finished . | 47 | 39 |
25,215 | public RFuture < String > getText ( Keyboard . TextType textType , String label , String initialValue , String ok , String cancel ) { return RFuture . failure ( new Exception ( "getText not supported" ) ) ; } | Requests a line of text from the user . On platforms that have only a virtual keyboard this will display a text entry interface obtain the line of text and dismiss the text entry interface when finished . Note that HTML5 and some Java backends do not support customization of the OK and Cancel labels . Thus those platforms will ignore the supplied labels and use their mandatory labels . | 49 | 73 |
25,216 | public RFuture < Boolean > sysDialog ( String title , String text , String ok , String cancel ) { return RFuture . failure ( new Exception ( "sysDialog not supported" ) ) ; } | Displays a system dialog with the specified title and text an OK button and optionally a Cancel button . | 41 | 20 |
25,217 | public static Point layerToScreen ( Layer layer , float x , float y ) { Point into = new Point ( x , y ) ; return layerToScreen ( layer , into , into ) ; } | Converts the supplied point from coordinates relative to the specified layer to screen coordinates . | 41 | 16 |
25,218 | public static Point layerToParent ( Layer layer , Layer parent , float x , float y ) { Point into = new Point ( x , y ) ; return layerToParent ( layer , parent , into , into ) ; } | Converts the supplied point from coordinates relative to the specified child layer to coordinates relative to the specified parent layer . | 46 | 22 |
25,219 | public static Point screenToLayer ( Layer layer , float x , float y ) { Point into = new Point ( x , y ) ; return screenToLayer ( layer , into , into ) ; } | Converts the supplied point from screen coordinates to coordinates relative to the specified layer . | 41 | 16 |
25,220 | public static Layer layerUnderPoint ( Layer root , float x , float y ) { Point p = new Point ( x , y ) ; root . transform ( ) . inverseTransform ( p , p ) ; p . x += root . originX ( ) ; p . y += root . originY ( ) ; return layerUnderPoint ( root , p ) ; } | Gets the layer underneath the given screen coordinates ignoring hit testers . This is useful for inspecting the scene graph for debugging purposes and is not intended for use is shipped code . The layer returned is the one that has a size and is the deepest within the graph and contains the coordinate . | 75 | 56 |
25,221 | public static int indexInParent ( Layer layer ) { GroupLayer parent = layer . parent ( ) ; if ( parent == null ) return - 1 ; for ( int ii = parent . children ( ) - 1 ; ii >= 0 ; ii -- ) { if ( parent . childAt ( ii ) == layer ) return ii ; } throw new AssertionError ( ) ; } | Returns the index of the given layer within its parent or - 1 if the parent is null . | 78 | 19 |
25,222 | public void bind ( ) { gfx . gl . glBindFramebuffer ( GL_FRAMEBUFFER , id ( ) ) ; gfx . gl . glViewport ( 0 , 0 , width ( ) , height ( ) ) ; } | Binds the framebuffer . | 51 | 6 |
25,223 | @ Override public void close ( ) { gl . glDeleteShader ( vertexShader ) ; gl . glDeleteShader ( fragmentShader ) ; gl . glDeleteProgram ( id ) ; } | Frees this program and associated compiled shaders . The program must not be used after closure . | 43 | 19 |
25,224 | private void emitStringValue ( String s ) { raw ( ' ' ) ; char b = 0 , c = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { b = c ; c = s . charAt ( i ) ; switch ( c ) { case ' ' : case ' ' : raw ( ' ' ) ; raw ( c ) ; break ; case ' ' : // Special case to ensure that </script> doesn't appear in JSON // output if ( b == ' ' ) raw ( ' ' ) ; raw ( c ) ; break ; case ' ' : raw ( "\\b" ) ; break ; case ' ' : raw ( "\\t" ) ; break ; case ' ' : raw ( "\\n" ) ; break ; case ' ' : raw ( "\\f" ) ; break ; case ' ' : raw ( "\\r" ) ; break ; default : if ( shouldBeEscaped ( c ) ) { String t = "000" + Integer . toHexString ( c ) ; raw ( "\\u" + t . substring ( t . length ( ) - "0000" . length ( ) ) ) ; } else { raw ( c ) ; } } } raw ( ' ' ) ; } | Emits a quoted string value escaping characters that are required to be escaped . | 270 | 15 |
25,225 | FontRenderContext aaFontContext ( ) { if ( aaFontContext == null ) { // set up the dummy font contexts Graphics2D aaGfx = new BufferedImage ( 1 , 1 , BufferedImage . TYPE_INT_ARGB ) . createGraphics ( ) ; aaGfx . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; aaFontContext = aaGfx . getFontRenderContext ( ) ; } return aaFontContext ; } | these are initialized lazily to avoid doing any AWT stuff during startup | 125 | 14 |
25,226 | public int compareTo ( DoubleBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; // BEGIN android-changed double thisDouble , otherDouble ; while ( compareRemaining > 0 ) { thisDouble = get ( thisPos ) ; otherDouble = otherBuffer . get ( otherPos ) ; // checks for double and NaN inequality if ( ( thisDouble != otherDouble ) && ( ( thisDouble == thisDouble ) || ( otherDouble == otherDouble ) ) ) { return thisDouble < otherDouble ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } // END android-changed return remaining ( ) - otherBuffer . remaining ( ) ; } | Compare the remaining doubles of this buffer to another double buffer s remaining doubles . | 180 | 15 |
25,227 | public DoubleBuffer get ( double [ ] dest , int off , int len ) { int length = dest . length ; if ( off < 0 || len < 0 || ( long ) off + ( long ) len > length ) { throw new IndexOutOfBoundsException ( ) ; } if ( len > remaining ( ) ) { throw new BufferUnderflowException ( ) ; } for ( int i = off ; i < off + len ; i ++ ) { dest [ i ] = get ( ) ; } return this ; } | Reads doubles from the current position into the specified double array starting from the specified offset and increases the position by the number of doubles read . | 109 | 28 |
25,228 | public DoubleBuffer put ( double [ ] src , int off , int len ) { int length = src . length ; if ( off < 0 || len < 0 || ( long ) off + ( long ) len > length ) { throw new IndexOutOfBoundsException ( ) ; } if ( len > remaining ( ) ) { throw new BufferOverflowException ( ) ; } for ( int i = off ; i < off + len ; i ++ ) { put ( src [ i ] ) ; } return this ; } | Writes doubles from the given double array starting from the specified offset to the current position and increases the position by the number of doubles written . | 108 | 28 |
25,229 | public synchronized void succeed ( I impl ) { this . impl = impl ; setVolumeImpl ( volume ) ; setLoopingImpl ( looping ) ; if ( playing ) playImpl ( ) ; ( ( RPromise < Sound > ) state ) . succeed ( this ) ; } | Configures this sound with its platform implementation . This may be called from any thread . | 58 | 17 |
25,230 | private int toModifierFlags ( int mods ) { return modifierFlags ( ( mods & GLFW_MOD_ALT ) != 0 , ( mods & GLFW_MOD_CONTROL ) != 0 , ( mods & GLFW_MOD_SUPER ) != 0 , ( mods & GLFW_MOD_SHIFT ) != 0 ) ; } | Converts GLFW modifier key flags into PlayN modifier key flags . | 73 | 14 |
25,231 | public < T > RPromise < T > deferredPromise ( ) { return new RPromise < T > ( ) { @ Override public void succeed ( final T value ) { invokeLater ( new Runnable ( ) { public void run ( ) { superSucceed ( value ) ; } } ) ; } @ Override public void fail ( final Throwable cause ) { invokeLater ( new Runnable ( ) { public void run ( ) { superFail ( cause ) ; } } ) ; } private void superSucceed ( T value ) { super . succeed ( value ) ; } private void superFail ( Throwable cause ) { super . fail ( cause ) ; } } ; } | Creates a promise which defers notification of success or failure to the game thread regardless of what thread on which it is completed . Note that even if it is completed on the game thread it will still defer completion until the next frame . | 148 | 47 |
25,232 | public void addTris ( Texture tex , int tint , AffineTransform xf , float [ ] xys , int xysOffset , int xysLen , float tw , float th , int [ ] indices , int indicesOffset , int indicesLen , int indexBase ) { setTexture ( tex ) ; prepare ( tint , xf ) ; addTris ( xys , xysOffset , xysLen , tw , th , indices , indicesOffset , indicesLen , indexBase ) ; } | Adds a collection of textured triangles to the current render operation . | 104 | 13 |
25,233 | public float adjustWidth ( float width ) { // Canvas.measureText does not account for the extra width consumed by italic characters, so we // fudge in a fraction of an em and hope the font isn't too slanted switch ( font . style ) { case ITALIC : return width + emwidth / 8 ; case BOLD_ITALIC : return width + emwidth / 6 ; default : return width ; // nada } } | Adjusts a measured width to account for italic and bold italic text . We have to handle this hackily because there s no way to measure exact text extent in HTML5 . | 94 | 37 |
25,234 | private File getWarDirectory ( TreeLogger logger ) throws UnableToCompleteException { File currentDirectory = new File ( "." ) ; try { String canonicalPath = currentDirectory . getCanonicalPath ( ) ; logger . log ( TreeLogger . INFO , "Current directory in which this generator is executing: " + canonicalPath ) ; if ( canonicalPath . endsWith ( "war" ) ) { return currentDirectory ; } else { return new File ( "war" ) ; } } catch ( IOException e ) { logger . log ( TreeLogger . ERROR , "Failed to get canonical path" , e ) ; throw new UnableToCompleteException ( ) ; } } | When invoking the GWT compiler from GPE the working directory is the Eclipse project directory . However when launching a GPE project the working directory is the project war directory . This methods returns the war directory in either case in a fairly naive and non - robust manner . | 143 | 53 |
25,235 | protected void paintScene ( ) { viewSurf . saveTx ( ) ; viewSurf . begin ( ) ; viewSurf . clear ( cred , cgreen , cblue , calpha ) ; try { rootLayer . paint ( viewSurf ) ; } finally { viewSurf . end ( ) ; viewSurf . restoreTx ( ) ; } } | Renders the main scene graph into the OpenGL frame buffer . | 76 | 12 |
25,236 | protected Resource requireResource ( String path ) throws IOException { URL url = getClass ( ) . getClassLoader ( ) . getResource ( pathPrefix + path ) ; if ( url != null ) { return url . getProtocol ( ) . equals ( "file" ) ? new FileResource ( new File ( URLDecoder . decode ( url . getPath ( ) , "UTF-8" ) ) ) : new URLResource ( url ) ; } for ( File dir : directories ) { File f = new File ( dir , path ) . getCanonicalFile ( ) ; if ( f . exists ( ) ) { return new FileResource ( f ) ; } } throw new FileNotFoundException ( path ) ; } | Attempts to locate the resource at the given path and returns a wrapper which allows its data to be efficiently read . | 153 | 22 |
25,237 | protected void prepareDraw ( ) { VertexAttribArrayState previousNio = null ; int previousElementSize = 0 ; if ( useNioBuffer == 0 && enabledArrays == previouslyEnabledArrays ) { return ; } for ( int i = 0 ; i < VERTEX_ATTRIB_ARRAY_COUNT ; i ++ ) { int mask = 1 << i ; int enabled = enabledArrays & mask ; if ( enabled != ( previouslyEnabledArrays & mask ) ) { if ( enabled != 0 ) { gl . enableVertexAttribArray ( i ) ; } else { gl . disableVertexAttribArray ( i ) ; } } if ( enabled != 0 && ( useNioBuffer & mask ) != 0 ) { VertexAttribArrayState data = vertexAttribArrayState [ i ] ; if ( previousNio != null && previousNio . nioBuffer == data . nioBuffer && previousNio . nioBufferLimit >= data . nioBufferLimit ) { if ( boundArrayBuffer != previousNio . webGlBuffer ) { gl . bindBuffer ( ARRAY_BUFFER , previousNio . webGlBuffer ) ; boundArrayBuffer = data . webGlBuffer ; } gl . vertexAttribPointer ( i , data . size , data . type , data . normalize , data . stride , data . nioBufferPosition * previousElementSize ) ; } else { if ( boundArrayBuffer != data . webGlBuffer ) { gl . bindBuffer ( ARRAY_BUFFER , data . webGlBuffer ) ; boundArrayBuffer = data . webGlBuffer ; } int elementSize = getElementSize ( data . nioBuffer ) ; int savePosition = data . nioBuffer . position ( ) ; if ( data . nioBufferPosition * elementSize < data . stride ) { data . nioBuffer . position ( 0 ) ; gl . bufferData ( ARRAY_BUFFER , getTypedArray ( data . nioBuffer , data . type , data . nioBufferLimit * elementSize ) , STREAM_DRAW ) ; gl . vertexAttribPointer ( i , data . size , data . type , data . normalize , data . stride , data . nioBufferPosition * elementSize ) ; previousNio = data ; previousElementSize = elementSize ; } else { data . nioBuffer . position ( data . nioBufferPosition ) ; gl . bufferData ( ARRAY_BUFFER , getTypedArray ( data . nioBuffer , data . type , ( data . nioBufferLimit - data . nioBufferPosition ) * elementSize ) , STREAM_DRAW ) ; gl . vertexAttribPointer ( i , data . size , data . type , data . normalize , data . stride , 0 ) ; } data . nioBuffer . position ( savePosition ) ; } } } previouslyEnabledArrays = enabledArrays ; } | The content of non - VBO buffers may be changed between the glVertexAttribPointer call and the glDrawXxx call . Thus we need to defer copying them to a VBO buffer until just before the actual glDrawXxx call . | 625 | 52 |
25,238 | private void setFillColor ( Color3f color ) { if ( cacheFillR == color . x && cacheFillG == color . y && cacheFillB == color . z ) { // no need to re-set the fill color, just use the cached values } else { cacheFillR = color . x ; cacheFillG = color . y ; cacheFillB = color . z ; setFillColorFromCache ( ) ; } } | Sets the fill color from a Color3f | 92 | 10 |
25,239 | private void setStrokeColor ( Color3f color ) { if ( cacheStrokeR == color . x && cacheStrokeG == color . y && cacheStrokeB == color . z ) { // no need to re-set the stroke color, just use the cached values } else { cacheStrokeR = color . x ; cacheStrokeG = color . y ; cacheStrokeB = color . z ; setStrokeColorFromCache ( ) ; } } | Sets the stroke color from a Color3f | 108 | 10 |
25,240 | public void start ( ) { if ( config . activationKey != null ) { input ( ) . keyboardEvents . connect ( new Slot < Keyboard . Event > ( ) { public void onEmit ( Keyboard . Event event ) { if ( event instanceof Keyboard . KeyEvent ) { Keyboard . KeyEvent kevent = ( Keyboard . KeyEvent ) event ; if ( kevent . key == config . activationKey && kevent . down ) { toggleActivation ( ) ; } } } } ) ; } // make a note of the main thread synchronized ( this ) { mainThread = Thread . currentThread ( ) ; } // run the game loop loop ( ) ; // let the game run any of its exit hooks dispatchEvent ( lifecycle , Lifecycle . EXIT ) ; // shutdown our thread pool try { pool . shutdown ( ) ; pool . awaitTermination ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException ie ) { // nothing to do here except go ahead and exit } // and finally stick a fork in the JVM System . exit ( 0 ) ; } | Starts the game loop . This method will not return until the game exits . | 227 | 16 |
25,241 | public static IntBuffer allocate ( int capacity ) { if ( capacity < 0 ) { throw new IllegalArgumentException ( ) ; } ByteBuffer bb = ByteBuffer . allocateDirect ( capacity * 4 ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; return bb . asIntBuffer ( ) ; } | Creates an int buffer based on a newly allocated int array . | 68 | 13 |
25,242 | public int compareTo ( IntBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; // BEGIN android-changed int thisInt , otherInt ; while ( compareRemaining > 0 ) { thisInt = get ( thisPos ) ; otherInt = otherBuffer . get ( otherPos ) ; if ( thisInt != otherInt ) { return thisInt < otherInt ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } // END android-changed return remaining ( ) - otherBuffer . remaining ( ) ; } | Compares the remaining ints of this buffer to another int buffer s remaining ints . | 152 | 18 |
25,243 | public TextFormat withFont ( String name , Font . Style style , float size ) { return withFont ( new Font ( name , style , size ) ) ; } | Returns a clone of this text format with the font configured as specified . | 34 | 14 |
25,244 | public Image getImageSync ( String path ) { ImageImpl image = createImage ( false , 0 , 0 , path ) ; try { image . succeed ( load ( path ) ) ; } catch ( Throwable t ) { image . fail ( t ) ; } return image ; } | Synchronously loads and returns an image . The calling thread will block while the image is loaded from disk and decoded . When this call returns the image s width and height will be valid and the image can be immediately converted to a texture and drawn into a canvas . | 58 | 54 |
25,245 | public RFuture < String > getText ( final String path ) { final RPromise < String > result = exec . deferredPromise ( ) ; exec . invokeAsync ( new Runnable ( ) { public void run ( ) { try { result . succeed ( getTextSync ( path ) ) ; } catch ( Throwable t ) { result . fail ( t ) ; } } } ) ; return result ; } | Loads UTF - 8 encoded text asynchronously . The returned state instance provides a means to listen for the arrival of the text . | 87 | 27 |
25,246 | public RFuture < ByteBuffer > getBytes ( final String path ) { final RPromise < ByteBuffer > result = exec . deferredPromise ( ) ; exec . invokeAsync ( new Runnable ( ) { public void run ( ) { try { result . succeed ( getBytesSync ( path ) ) ; } catch ( Throwable t ) { result . fail ( t ) ; } } } ) ; return result ; } | Loads binary data asynchronously . The returned state instance provides a means to listen for the arrival of the data . | 89 | 24 |
25,247 | static float getRelativeX ( NativeEvent e , Element target ) { return ( e . getClientX ( ) - target . getAbsoluteLeft ( ) + target . getScrollLeft ( ) + target . getOwnerDocument ( ) . getScrollLeft ( ) ) / HtmlGraphics . experimentalScale ; } | Gets the event s x - position relative to a given element . | 65 | 14 |
25,248 | static float getRelativeY ( NativeEvent e , Element target ) { return ( e . getClientY ( ) - target . getAbsoluteTop ( ) + target . getScrollTop ( ) + target . getOwnerDocument ( ) . getScrollTop ( ) ) / HtmlGraphics . experimentalScale ; } | Gets the event s y - position relative to a given element . | 65 | 14 |
25,249 | public synchronized void succeed ( Data data ) { scale = data . scale ; pixelWidth = data . pixelWidth ; assert pixelWidth > 0 ; pixelHeight = data . pixelHeight ; assert pixelHeight > 0 ; setBitmap ( data . bitmap ) ; ( ( RPromise < Image > ) state ) . succeed ( this ) ; // state is a deferred promise } | Notifies this image that its implementation bitmap is available . This can be called from any thread . | 77 | 20 |
25,250 | public synchronized void fail ( Throwable error ) { if ( pixelWidth == 0 ) pixelWidth = 50 ; if ( pixelHeight == 0 ) pixelHeight = 50 ; setBitmap ( createErrorBitmap ( pixelWidth , pixelHeight ) ) ; ( ( RPromise < Image > ) state ) . fail ( error ) ; // state is a deferred promise } | Notifies this image that its implementation bitmap failed to load . This can be called from any thread . | 75 | 21 |
25,251 | protected boolean accept ( String path ) { // GWT Development Mode files if ( path . equals ( "hosted.html" ) || path . endsWith ( ".devmode.js" ) ) { return false ; } // Default or welcome file if ( path . equals ( "/" ) ) { return true ; } // Whitelisted file extension int pos = path . lastIndexOf ( ' ' ) ; if ( pos != - 1 ) { String extension = path . substring ( pos + 1 ) ; if ( DEFAULT_EXTENSION_WHITELIST . contains ( extension ) ) { return true ; } } // Not included by default return false ; } | Determines whether our not the given should be included in the app cache manifest . Subclasses may override this method in order to filter out specific file patterns . | 140 | 32 |
25,252 | public Texture createTexture ( float width , float height , Texture . Config config ) { int texWidth = config . toTexWidth ( scale . scaledCeil ( width ) ) ; int texHeight = config . toTexHeight ( scale . scaledCeil ( height ) ) ; if ( texWidth <= 0 || texHeight <= 0 ) throw new IllegalArgumentException ( "Invalid texture size: " + texWidth + "x" + texHeight ) ; int id = createTexture ( config ) ; gl . glTexImage2D ( GL_TEXTURE_2D , 0 , GL_RGBA , texWidth , texHeight , 0 , GL_RGBA , GL_UNSIGNED_BYTE , null ) ; return new Texture ( this , id , config , texWidth , texHeight , scale , width , height ) ; } | Creates an empty texture into which one can render . The supplied width and height are in display units and will be converted to pixels based on the current scale factor . | 176 | 33 |
25,253 | protected void viewportChanged ( int pixelWidth , int pixelHeight ) { viewPixelWidth = pixelWidth ; viewPixelHeight = pixelHeight ; viewSizeM . width = scale . invScaled ( pixelWidth ) ; viewSizeM . height = scale . invScaled ( pixelHeight ) ; plat . log ( ) . info ( "viewPortChanged " + pixelWidth + "x" + pixelHeight + " / " + scale . factor + " -> " + viewSize ) ; } | Informs the graphics system that the main framebuffer size has changed . The supplied size should be in physical pixels . | 102 | 23 |
25,254 | public static ShortBuffer allocate ( int capacity ) { if ( capacity < 0 ) { throw new IllegalArgumentException ( ) ; } ByteBuffer bb = ByteBuffer . allocateDirect ( capacity * 2 ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; return bb . asShortBuffer ( ) ; } | Creates a short buffer based on a newly allocated short array . | 68 | 13 |
25,255 | @ SuppressWarnings ( "unchecked" ) < T > T parse ( Class < T > clazz ) throws JsonParserException { advanceToken ( ) ; Object parsed = currentValue ( ) ; if ( advanceToken ( ) != Token . EOF ) throw createParseException ( null , "Expected end of input, got " + token , true ) ; if ( clazz != Object . class && ( parsed == null || clazz != parsed . getClass ( ) ) ) throw createParseException ( null , "JSON did not contain the correct type, expected " + clazz . getName ( ) + "." , true ) ; return ( T ) ( parsed ) ; } | Parse a single JSON value from the string expecting an EOF at the end . | 147 | 17 |
25,256 | private Object currentValue ( ) throws JsonParserException { // Only a value start token should appear when we're in the context of parsing a JSON value if ( token . isValue ) return value ; throw createParseException ( null , "Expected JSON value, got " + token , true ) ; } | Starts parsing a JSON value at the current token position . | 64 | 12 |
25,257 | private void consumeKeyword ( char first , char [ ] expected ) throws JsonParserException { for ( int i = 0 ; i < expected . length ; i ++ ) if ( advanceChar ( ) != expected [ i ] ) throw createHelpfulException ( first , expected , i ) ; // The token should end with something other than an ASCII letter if ( isAsciiLetter ( peekChar ( ) ) ) throw createHelpfulException ( first , expected , expected . length ) ; } | Expects a given string at the current position . | 103 | 10 |
25,258 | private char stringChar ( ) throws JsonParserException { int c = advanceChar ( ) ; if ( c == - 1 ) throw createParseException ( null , "String was not terminated before end of input" , true ) ; if ( c < 32 ) throw createParseException ( null , "Strings may not contain control characters: 0x" + Integer . toString ( c , 16 ) , false ) ; return ( char ) c ; } | Advances a character throwing if it is illegal in the context of a JSON string . | 96 | 17 |
25,259 | private int stringHexChar ( ) throws JsonParserException { // GWT-compatible Character.digit(char, int) int c = "0123456789abcdef0123456789ABCDEF" . indexOf ( advanceChar ( ) ) % 16 ; if ( c == - 1 ) throw createParseException ( null , "Expected unicode hex escape character" , false ) ; return c ; } | Advances a character throwing if it is illegal in the context of a JSON string hex unicode escape . | 90 | 21 |
25,260 | private JsonParserException createHelpfulException ( char first , char [ ] expected , int failurePosition ) throws JsonParserException { // Build the first part of the token StringBuilder errorToken = new StringBuilder ( first + ( expected == null ? "" : new String ( expected , 0 , failurePosition ) ) ) ; // Consume the whole pseudo-token to make a better error message while ( isAsciiLetter ( peekChar ( ) ) && errorToken . length ( ) < 15 ) errorToken . append ( ( char ) advanceChar ( ) ) ; return createParseException ( null , "Unexpected token '" + errorToken + "'" + ( expected == null ? "" : ". Did you mean '" + first + new String ( expected ) + "'?" ) , true ) ; } | Throws a helpful exception based on the current alphanumeric token . | 169 | 14 |
25,261 | public void capture ( CaptureMode mode ) { assert dispatchLayer != null ; if ( canceled ) throw new IllegalStateException ( "Cannot capture canceled interaction." ) ; if ( capturingLayer != dispatchLayer && captured ( ) ) throw new IllegalStateException ( "Interaction already captured by " + capturingLayer ) ; capturingLayer = dispatchLayer ; captureMode = mode ; notifyCancel ( capturingLayer , captureMode , event ) ; } | Captures this interaction in the specified capture mode . Depending on the mode subsequent events will go only to the current layer or that layer and its parents or that layer and its children . Other layers in the interaction will receive a cancellation event and nothing further . | 89 | 50 |
25,262 | public void begin ( float fbufWidth , float fbufHeight , boolean flip ) { if ( begun ) throw new IllegalStateException ( getClass ( ) . getSimpleName ( ) + " mismatched begin()" ) ; begun = true ; } | Must be called before this batch is used to accumulate and send drawing commands . | 52 | 15 |
25,263 | public static void registerVariant ( String name , Style style , String variantName ) { Map < String , String > styleVariants = _variants . get ( style ) ; if ( styleVariants == null ) { _variants . put ( style , styleVariants = new HashMap < String , String > ( ) ) ; } styleVariants . put ( name , variantName ) ; } | Registers a font for use when a bold italic or bold italic variant is requested . iOS does not programmatically generate bold italic and bold italic variants of fonts . Instead it uses the actual bold italic or bold italic variant of the font provided by the original designer . | 84 | 58 |
25,264 | public static FloatBuffer allocate ( int capacity ) { if ( capacity < 0 ) { throw new IllegalArgumentException ( ) ; } ByteBuffer bb = ByteBuffer . allocateDirect ( capacity * 4 ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; return bb . asFloatBuffer ( ) ; } | Creates a float buffer based on a newly allocated float array . | 68 | 13 |
25,265 | public int compareTo ( FloatBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; // BEGIN android-changed float thisFloat , otherFloat ; while ( compareRemaining > 0 ) { thisFloat = get ( thisPos ) ; otherFloat = otherBuffer . get ( otherPos ) ; // checks for float and NaN inequality if ( ( thisFloat != otherFloat ) && ( ( thisFloat == thisFloat ) || ( otherFloat == otherFloat ) ) ) { return thisFloat < otherFloat ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } // END android-changed return remaining ( ) - otherBuffer . remaining ( ) ; } | Compare the remaining floats of this buffer to another float buffer s remaining floats . | 180 | 15 |
25,266 | @ SuppressWarnings ( "rawtypes" ) public Class < ? extends TBase > getMessageClass ( String topic ) { return allTopics ? messageClassForAll : messageClassByTopic . get ( topic ) ; } | Returns configured thrift message class for the given Kafka topic | 48 | 11 |
25,267 | public void init ( SecorConfig config , OffsetTracker offsetTracker , FileRegistry fileRegistry , UploadManager uploadManager , MessageReader messageReader , MetricCollector metricCollector , DeterministicUploadPolicyTracker deterministicUploadPolicyTracker ) { init ( config , offsetTracker , fileRegistry , uploadManager , messageReader , new ZookeeperConnector ( config ) , metricCollector , deterministicUploadPolicyTracker ) ; } | Init the Uploader with its dependent objects . | 90 | 9 |
25,268 | public void init ( SecorConfig config , OffsetTracker offsetTracker , FileRegistry fileRegistry , UploadManager uploadManager , MessageReader messageReader , ZookeeperConnector zookeeperConnector , MetricCollector metricCollector , DeterministicUploadPolicyTracker deterministicUploadPolicyTracker ) { mConfig = config ; mOffsetTracker = offsetTracker ; mFileRegistry = fileRegistry ; mUploadManager = uploadManager ; mMessageReader = messageReader ; mZookeeperConnector = zookeeperConnector ; mTopicFilter = mConfig . getKafkaTopicUploadAtMinuteMarkFilter ( ) ; mMetricCollector = metricCollector ; mDeterministicUploadPolicyTracker = deterministicUploadPolicyTracker ; if ( mConfig . getOffsetsStorage ( ) . equals ( SecorConstants . KAFKA_OFFSETS_STORAGE_KAFKA ) ) { isOffsetsStorageKafka = true ; } } | For testing use only . | 202 | 5 |
25,269 | protected FileReader createReader ( LogFilePath srcPath , CompressionCodec codec ) throws Exception { return ReflectionUtil . createFileReader ( mConfig . getFileReaderWriterFactory ( ) , srcPath , codec , mConfig ) ; } | This method is intended to be overwritten in tests . | 52 | 11 |
25,270 | public void applyPolicy ( boolean forceUpload ) throws Exception { Collection < TopicPartition > topicPartitions = mFileRegistry . getTopicPartitions ( ) ; for ( TopicPartition topicPartition : topicPartitions ) { checkTopicPartition ( topicPartition , forceUpload ) ; } } | Apply the Uploader policy for pushing partition files to the underlying storage . | 63 | 14 |
25,271 | private CompressionKind resolveCompression ( CompressionCodec codec ) { if ( codec instanceof Lz4Codec ) return CompressionKind . LZ4 ; else if ( codec instanceof SnappyCodec ) return CompressionKind . SNAPPY ; // although GZip and ZLIB are not same thing // there is no better named codec for this case, // use hadoop Gzip codec to enable ORC ZLIB compression else if ( codec instanceof GzipCodec ) return CompressionKind . ZLIB ; else return CompressionKind . NONE ; } | Used for returning the compression kind used in ORC | 120 | 10 |
25,272 | private FileReader createFileReader ( LogFilePath logFilePath ) throws Exception { CompressionCodec codec = null ; if ( mConfig . getCompressionCodec ( ) != null && ! mConfig . getCompressionCodec ( ) . isEmpty ( ) ) { codec = CompressionUtil . createCompressionCodec ( mConfig . getCompressionCodec ( ) ) ; } FileReader fileReader = ReflectionUtil . createFileReader ( mConfig . getFileReaderWriterFactory ( ) , logFilePath , codec , mConfig ) ; return fileReader ; } | Helper to create a file reader writer from config | 124 | 9 |
25,273 | public Class < ? extends Message > getMessageClass ( String topic ) { return allTopics ? messageClassForAll : messageClassByTopic . get ( topic ) ; } | Returns configured protobuf message class for the given Kafka topic | 35 | 12 |
25,274 | public Message decodeProtobufMessage ( String topic , byte [ ] payload ) { Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic . get ( topic ) ; try { return ( Message ) parseMethod . invoke ( null , payload ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Can't parse protobuf message, since parseMethod() is not callable. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Can't parse protobuf message, since parseMethod() is not accessible. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)" , e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( "Error parsing protobuf message" , e ) ; } } | Decodes protobuf message | 210 | 6 |
25,275 | public Message decodeProtobufOrJsonMessage ( String topic , byte [ ] payload ) { try { if ( shouldDecodeFromJsonMessage ( topic ) ) { return decodeJsonMessage ( topic , payload ) ; } } catch ( InvalidProtocolBufferException e ) { //When trimming files, the Uploader will read and then decode messages in protobuf format LOG . debug ( "Unable to translate JSON string {} to protobuf message" , new String ( payload , Charsets . UTF_8 ) ) ; } return decodeProtobufMessage ( topic , payload ) ; } | Decodes protobuf message If the secor . topic . message . format property is set to JSON for topic assume payload is JSON | 127 | 27 |
25,276 | public static UploadManager createUploadManager ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! UploadManager . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , UploadManager . class . getName ( ) ) ) ; } // Assume that subclass of UploadManager has a constructor with the same signature as UploadManager return ( UploadManager ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } | Create an UploadManager from its fully qualified class name . | 143 | 11 |
25,277 | public static Uploader createUploader ( String className ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! Uploader . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , Uploader . class . getName ( ) ) ) ; } return ( Uploader ) clazz . newInstance ( ) ; } | Create an Uploader from its fully qualified class name . | 108 | 11 |
25,278 | public static MessageParser createMessageParser ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! MessageParser . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , MessageParser . class . getName ( ) ) ) ; } // Assume that subclass of MessageParser has a constructor with the same signature as MessageParser return ( MessageParser ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } | Create a MessageParser from it s fully qualified class name . The class passed in by name must be assignable to MessageParser and have 1 - parameter constructor accepting a SecorConfig . Allows the MessageParser to be pluggable by providing the class name of a desired MessageParser in config . | 143 | 59 |
25,279 | private static FileReaderWriterFactory createFileReaderWriterFactory ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! FileReaderWriterFactory . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , FileReaderWriterFactory . class . getName ( ) ) ) ; } try { // Try to load constructor that accepts single parameter - secor // configuration instance return ( FileReaderWriterFactory ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } catch ( NoSuchMethodException e ) { // Fallback to parameterless constructor return ( FileReaderWriterFactory ) clazz . newInstance ( ) ; } } | Create a FileReaderWriterFactory that is able to read and write a specific type of output log file . The class passed in by name must be assignable to FileReaderWriterFactory . Allows for pluggable FileReader and FileWriter instances to be constructed for a particular type of log file . | 185 | 59 |
25,280 | public static FileWriter createFileWriter ( String className , LogFilePath logFilePath , CompressionCodec codec , SecorConfig config ) throws Exception { return createFileReaderWriterFactory ( className , config ) . BuildFileWriter ( logFilePath , codec ) ; } | Use the FileReaderWriterFactory specified by className to build a FileWriter | 58 | 15 |
25,281 | public static FileReader createFileReader ( String className , LogFilePath logFilePath , CompressionCodec codec , SecorConfig config ) throws Exception { return createFileReaderWriterFactory ( className , config ) . BuildFileReader ( logFilePath , codec ) ; } | Use the FileReaderWriterFactory specified by className to build a FileReader | 58 | 15 |
25,282 | public static MessageTransformer createMessageTransformer ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! MessageTransformer . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , MessageTransformer . class . getName ( ) ) ) ; } return ( MessageTransformer ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } | Create a MessageTransformer from it s fully qualified class name . The class passed in by name must be assignable to MessageTransformers and have 1 - parameter constructor accepting a SecorConfig . Allows the MessageTransformers to be pluggable by providing the class name of a desired MessageTransformers in config . | 130 | 63 |
25,283 | public static ORCSchemaProvider createORCSchemaProvider ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! ORCSchemaProvider . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , ORCSchemaProvider . class . getName ( ) ) ) ; } return ( ORCSchemaProvider ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } | Create a ORCSchemaProvider from it s fully qualified class name . The class passed in by name must be assignable to ORCSchemaProvider and have 1 - parameter constructor accepting a SecorConfig . Allows the ORCSchemaProvider to be pluggable by providing the class name of a desired ORCSchemaProvider in config . | 140 | 71 |
25,284 | public static String getMd5Hash ( String topic , String [ ] partitions ) { ArrayList < String > elements = new ArrayList < String > ( ) ; elements . add ( topic ) ; for ( String partition : partitions ) { elements . add ( partition ) ; } String pathPrefix = StringUtils . join ( elements , "/" ) ; try { final MessageDigest messageDigest = MessageDigest . getInstance ( "MD5" ) ; byte [ ] md5Bytes = messageDigest . digest ( pathPrefix . getBytes ( "UTF-8" ) ) ; return getHexEncode ( md5Bytes ) . substring ( 0 , 4 ) ; } catch ( NoSuchAlgorithmException e ) { LOG . error ( e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( e . getMessage ( ) ) ; } return "" ; } | Generate MD5 hash of topic and partitions . And extract first 4 characters of the MD5 hash . | 196 | 21 |
25,285 | private void setSchemas ( SecorConfig config ) { Map < String , String > schemaPerTopic = config . getORCMessageSchema ( ) ; for ( Entry < String , String > entry : schemaPerTopic . entrySet ( ) ) { String topic = entry . getKey ( ) ; TypeDescription schema = TypeDescription . fromString ( entry . getValue ( ) ) ; topicToSchemaMap . put ( topic , schema ) ; // If common schema is given if ( "*" . equals ( topic ) ) { schemaForAlltopic = schema ; } } } | This method is used for fetching all ORC schemas from config | 122 | 14 |
25,286 | public Map < String , String > getPropertyMapForPrefix ( String prefix ) { Iterator < String > keys = mProperties . getKeys ( prefix ) ; Map < String , String > map = new HashMap < String , String > ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; String value = mProperties . getString ( key ) ; map . put ( key . substring ( prefix . length ( ) + 1 ) , value ) ; } return map ; } | This method is used for fetching all the properties which start with the given prefix . It returns a Map of all those key - val . | 112 | 28 |
25,287 | private void exportToStatsD ( List < Stat > stats ) { // group stats by kafka group for ( Stat stat : stats ) { @ SuppressWarnings ( "unchecked" ) Map < String , String > tags = ( Map < String , String > ) stat . get ( Stat . STAT_KEYS . TAGS . getName ( ) ) ; long value = Long . parseLong ( ( String ) stat . get ( Stat . STAT_KEYS . VALUE . getName ( ) ) ) ; if ( mConfig . getStatsdDogstatdsTagsEnabled ( ) ) { String metricName = ( String ) stat . get ( Stat . STAT_KEYS . METRIC . getName ( ) ) ; String [ ] tagArray = new String [ tags . size ( ) ] ; int i = 0 ; for ( Map . Entry < String , String > e : tags . entrySet ( ) ) { tagArray [ i ++ ] = e . getKey ( ) + ' ' + e . getValue ( ) ; } mStatsDClient . recordGaugeValue ( metricName , value , tagArray ) ; } else { StringBuilder builder = new StringBuilder ( ) ; if ( mConfig . getStatsDPrefixWithConsumerGroup ( ) ) { builder . append ( tags . get ( Stat . STAT_KEYS . GROUP . getName ( ) ) ) . append ( PERIOD ) ; } String metricName = builder . append ( ( String ) stat . get ( Stat . STAT_KEYS . METRIC . getName ( ) ) ) . append ( PERIOD ) . append ( tags . get ( Stat . STAT_KEYS . TOPIC . getName ( ) ) ) . append ( PERIOD ) . append ( tags . get ( Stat . STAT_KEYS . PARTITION . getName ( ) ) ) . toString ( ) ; mStatsDClient . recordGaugeValue ( metricName , value ) ; } } } | Helper to publish stats to statsD client | 419 | 8 |
25,288 | public Collection < TopicPartition > getTopicPartitions ( ) { Collection < TopicPartitionGroup > topicPartitions = getTopicPartitionGroups ( ) ; Set < TopicPartition > tps = new HashSet < TopicPartition > ( ) ; if ( topicPartitions != null ) { for ( TopicPartitionGroup g : topicPartitions ) { tps . addAll ( g . getTopicPartitions ( ) ) ; } } return tps ; } | Get all topic partitions . | 99 | 5 |
25,289 | public Collection < LogFilePath > getPaths ( TopicPartitionGroup topicPartitionGroup ) { HashSet < LogFilePath > logFilePaths = mFiles . get ( topicPartitionGroup ) ; if ( logFilePaths == null ) { return new HashSet < LogFilePath > ( ) ; } return new HashSet < LogFilePath > ( logFilePaths ) ; } | Get paths in a given topic partition . | 84 | 8 |
25,290 | public FileWriter getOrCreateWriter ( LogFilePath path , CompressionCodec codec ) throws Exception { FileWriter writer = mWriters . get ( path ) ; if ( writer == null ) { // Just in case. FileUtil . delete ( path . getLogFilePath ( ) ) ; FileUtil . delete ( path . getLogFileCrcPath ( ) ) ; TopicPartitionGroup topicPartition = new TopicPartitionGroup ( path . getTopic ( ) , path . getKafkaPartitions ( ) ) ; HashSet < LogFilePath > files = mFiles . get ( topicPartition ) ; if ( files == null ) { files = new HashSet < LogFilePath > ( ) ; mFiles . put ( topicPartition , files ) ; } if ( ! files . contains ( path ) ) { files . add ( path ) ; } writer = ReflectionUtil . createFileWriter ( mConfig . getFileReaderWriterFactory ( ) , path , codec , mConfig ) ; mWriters . put ( path , writer ) ; mCreationTimes . put ( path , System . currentTimeMillis ( ) / 1000L ) ; LOG . debug ( "created writer for path {}" , path . getLogFilePath ( ) ) ; LOG . debug ( "Register deleteOnExit for path {}" , path . getLogFilePath ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileParentDir ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileDir ( ) ) ; FileUtil . deleteOnExit ( path . getLogFilePath ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileCrcPath ( ) ) ; } return writer ; } | Retrieve a writer for a given path or create a new one if it does not exist . | 374 | 19 |
25,291 | public void deletePath ( LogFilePath path ) throws IOException { TopicPartitionGroup topicPartition = new TopicPartitionGroup ( path . getTopic ( ) , path . getKafkaPartitions ( ) ) ; HashSet < LogFilePath > paths = mFiles . get ( topicPartition ) ; paths . remove ( path ) ; if ( paths . isEmpty ( ) ) { mFiles . remove ( topicPartition ) ; StatsUtil . clearLabel ( "secor.size." + topicPartition . getTopic ( ) + "." + topicPartition . getPartitions ( ) [ 0 ] ) ; StatsUtil . clearLabel ( "secor.modification_age_sec." + topicPartition . getTopic ( ) + "." + topicPartition . getPartitions ( ) [ 0 ] ) ; } deleteWriter ( path ) ; FileUtil . delete ( path . getLogFilePath ( ) ) ; FileUtil . delete ( path . getLogFileCrcPath ( ) ) ; } | Delete a given path the underlying file and the corresponding writer . | 220 | 12 |
25,292 | public void deleteWriter ( LogFilePath path ) throws IOException { FileWriter writer = mWriters . get ( path ) ; if ( writer == null ) { LOG . warn ( "No writer found for path {}" , path . getLogFilePath ( ) ) ; } else { LOG . info ( "Deleting writer for path {}" , path . getLogFilePath ( ) ) ; writer . close ( ) ; mWriters . remove ( path ) ; mCreationTimes . remove ( path ) ; } } | Delete writer for a given topic partition . Underlying file is not removed . | 111 | 15 |
25,293 | public static void unregisterProgressListener ( @ NonNull final Context context , @ NonNull final DfuProgressListener listener ) { if ( mProgressBroadcastReceiver != null ) { final boolean empty = mProgressBroadcastReceiver . removeProgressListener ( listener ) ; if ( empty ) { LocalBroadcastManager . getInstance ( context ) . unregisterReceiver ( mProgressBroadcastReceiver ) ; mProgressBroadcastReceiver = null ; } } } | Unregisters the previously registered progress listener . | 97 | 9 |
25,294 | public static void unregisterLogListener ( @ NonNull final Context context , @ NonNull final DfuLogListener listener ) { if ( mLogBroadcastReceiver != null ) { final boolean empty = mLogBroadcastReceiver . removeLogListener ( listener ) ; if ( empty ) { LocalBroadcastManager . getInstance ( context ) . unregisterReceiver ( mLogBroadcastReceiver ) ; mLogBroadcastReceiver = null ; } } } | Unregisters the previously registered log listener . | 97 | 9 |
25,295 | public void fullReset ( ) { // Reset stream to SoftDevice if SD and BL firmware were given separately if ( softDeviceBytes != null && bootloaderBytes != null && currentSource == bootloaderBytes ) { currentSource = softDeviceBytes ; } // Reset the bytes count to 0 bytesReadFromCurrentSource = 0 ; mark ( 0 ) ; reset ( ) ; } | Resets to the beginning of current stream . If SD and BL were updated the stream will be reset to the beginning . If SD and BL were already sent and the current stream was changed to application this method will reset to the beginning of the application stream . | 77 | 51 |
25,296 | void writeInitData ( final BluetoothGattCharacteristic characteristic , final CRC32 crc32 ) throws DfuException , DeviceDisconnectedException , UploadAbortedException { try { byte [ ] data = mBuffer ; int size ; while ( ( size = mInitPacketStream . read ( data , 0 , data . length ) ) != - 1 ) { writeInitPacket ( characteristic , data , size ) ; if ( crc32 != null ) crc32 . update ( data , 0 , size ) ; } } catch ( final IOException e ) { loge ( "Error while reading Init packet file" , e ) ; throw new DfuException ( "Error while reading Init packet file" , DfuBaseService . ERROR_FILE_ERROR ) ; } } | Wends the whole init packet stream to the given characteristic . | 162 | 12 |
25,297 | void uploadFirmwareImage ( final BluetoothGattCharacteristic packetCharacteristic ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { if ( mAborted ) throw new UploadAbortedException ( ) ; mReceivedData = null ; mError = 0 ; mFirmwareUploadInProgress = true ; mPacketsSentSinceNotification = 0 ; final byte [ ] buffer = mBuffer ; try { final int size = mFirmwareStream . read ( buffer ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Sending firmware to characteristic " + packetCharacteristic . getUuid ( ) + "..." ) ; writePacket ( mGatt , packetCharacteristic , buffer , size ) ; } catch ( final HexFileValidationException e ) { throw new DfuException ( "HEX file not valid" , DfuBaseService . ERROR_FILE_INVALID ) ; } catch ( final IOException e ) { throw new DfuException ( "Error while reading file" , DfuBaseService . ERROR_FILE_IO_EXCEPTION ) ; } try { synchronized ( mLock ) { while ( ( mFirmwareUploadInProgress && mReceivedData == null && mConnected && mError == 0 ) || mPaused ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( ! mConnected ) throw new DeviceDisconnectedException ( "Uploading Firmware Image failed: device disconnected" ) ; if ( mError != 0 ) throw new DfuException ( "Uploading Firmware Image failed" , mError ) ; } | Starts sending the data . This method is SYNCHRONOUS and terminates when the whole file will be uploaded or the device get disconnected . If connection state will change or an error will occur an exception will be thrown . | 371 | 46 |
25,298 | private void writePacket ( final BluetoothGatt gatt , final BluetoothGattCharacteristic characteristic , final byte [ ] buffer , final int size ) { byte [ ] locBuffer = buffer ; if ( size <= 0 ) // This should never happen return ; if ( buffer . length != size ) { locBuffer = new byte [ size ] ; System . arraycopy ( buffer , 0 , locBuffer , 0 , size ) ; } characteristic . setWriteType ( BluetoothGattCharacteristic . WRITE_TYPE_NO_RESPONSE ) ; characteristic . setValue ( locBuffer ) ; gatt . writeCharacteristic ( characteristic ) ; } | Writes the buffer to the characteristic . The maximum size of the buffer is dependent on MTU . This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue . | 133 | 39 |
25,299 | private int readVersion ( final BluetoothGatt gatt , final BluetoothGattCharacteristic characteristic ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read version number: device disconnected" ) ; if ( mAborted ) throw new UploadAbortedException ( ) ; // If the DFU Version characteristic is not available we return 0. if ( characteristic == null ) return 0 ; mReceivedData = null ; mError = 0 ; logi ( "Reading DFU version number..." ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Reading DFU version number..." ) ; characteristic . setValue ( ( byte [ ] ) null ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.readCharacteristic(" + characteristic . getUuid ( ) + ")" ) ; gatt . readCharacteristic ( characteristic ) ; // We have to wait until device receives a response or an error occur try { synchronized ( mLock ) { while ( ( ( ! mRequestCompleted || characteristic . getValue ( ) == null ) && mConnected && mError == 0 && ! mAborted ) || mPaused ) { mRequestCompleted = false ; mLock . wait ( ) ; } } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read version number: device disconnected" ) ; if ( mError != 0 ) throw new DfuException ( "Unable to read version number" , mError ) ; // The version is a 16-bit unsigned int return characteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT16 , 0 ) ; } | Reads the DFU Version characteristic if such exists . Otherwise it returns 0 . | 406 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.