idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
15,200 | protected void dirtyIndicator ( SceneObjectIndicator indic ) { if ( indic != null ) { Rectangle r = indic . getBounds ( ) ; if ( r != null ) { _remgr . invalidateRegion ( r ) ; } } } | Dirties the specified indicator . |
15,201 | protected void changeHoverObject ( Object newHover ) { if ( newHover == _hobject ) { return ; } Object oldHover = _hobject ; _hobject = newHover ; hoverObjectChanged ( oldHover , newHover ) ; } | Change the hover object to the new object . |
15,202 | protected void hoverObjectChanged ( Object oldHover , Object newHover ) { if ( oldHover instanceof SceneObject ) { SceneObject oldhov = ( SceneObject ) oldHover ; if ( oldhov . setHovered ( false ) ) { _remgr . invalidateRegion ( oldhov . bounds ) ; } } if ( newHover instanceof SceneObject ) { SceneObject newhov = ( SceneObject ) newHover ; if ( newhov . setHovered ( true ) ) { _remgr . invalidateRegion ( newhov . bounds ) ; } } dirtyIndicator ( _indicators . get ( oldHover ) ) ; dirtyIndicator ( _indicators . get ( newHover ) ) ; } | A place for subclasses to react to the hover object changing . One of the supplied arguments may be null . |
15,203 | protected void getHitObjects ( DirtyItemList list , int x , int y ) { for ( SceneObject scobj : _vizobjs ) { Rectangle pbounds = scobj . bounds ; if ( ! pbounds . contains ( x , y ) ) { continue ; } if ( skipHitObject ( scobj ) ) { continue ; } if ( ! scobj . tile . hitTest ( x - pbounds . x , y - pbounds . y ) ) { continue ; } list . appendDirtyObject ( scobj ) ; } } | Adds to the supplied dirty item list all of the object tiles that are hit by the specified point ( meaning the point is contained within their bounds and intersects a non - transparent pixel in the actual object image . |
15,204 | protected void paintBits ( Graphics2D gfx , int layer , Rectangle dirty ) { _animmgr . paint ( gfx , layer , dirty ) ; } | We don t want sprites rendered using the standard mechanism because we intersperse them with objects in our scene and need to manage their z - order . |
15,205 | protected void paintDirtyItems ( Graphics2D gfx , Rectangle clip ) { _dirtySprites . clear ( ) ; _spritemgr . getIntersectingSprites ( _dirtySprites , clip ) ; int size = _dirtySprites . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { Sprite sprite = _dirtySprites . get ( ii ) ; Rectangle bounds = sprite . getBounds ( ) ; if ( ! bounds . intersects ( clip ) ) { continue ; } appendDirtySprite ( _dirtyItems , sprite ) ; } for ( SceneObject scobj : _vizobjs ) { if ( ! scobj . bounds . intersects ( clip ) ) { continue ; } _dirtyItems . appendDirtyObject ( scobj ) ; } _dirtyItems . sort ( ) ; _dirtyItems . paintAndClear ( gfx ) ; } | Renders the dirty sprites and objects in the scene to the given graphics context . |
15,206 | protected void paintIndicators ( Graphics2D gfx , Rectangle clip ) { if ( ! _indicatorsLaidOut ) { for ( Map . Entry < SceneObject , SceneObjectIndicator > entry : _indicators . entrySet ( ) ) { SceneObjectIndicator indic = entry . getValue ( ) ; if ( ! indic . isLaidOut ( ) ) { indic . layout ( gfx , entry . getKey ( ) , _vbounds ) ; dirtyIndicator ( indic ) ; } } _indicatorsLaidOut = true ; } if ( checkShowFlag ( SHOW_TIPS ) ) { for ( SceneObjectIndicator indic : _indicators . values ( ) ) { paintIndicator ( gfx , clip , indic ) ; } } else { SceneObjectIndicator indic = _indicators . get ( _hobject ) ; if ( indic != null ) { paintIndicator ( gfx , clip , indic ) ; } } } | Paint all the appropriate indicators for our scene objects . |
15,207 | protected void paintIndicator ( Graphics2D gfx , Rectangle clip , SceneObjectIndicator tip ) { if ( clip . intersects ( tip . getBounds ( ) ) ) { tip . paint ( gfx ) ; } } | Paint the specified indicator if it intersects the clipping rectangle . |
15,208 | protected void paintTiles ( Graphics2D gfx , Rectangle clip ) { _paintOp . setGraphics ( gfx ) ; _applicator . applyToTiles ( clip , _paintOp ) ; _paintOp . setGraphics ( null ) ; } | Renders the base and fringe layer tiles that intersect the specified clipping rectangle . |
15,209 | protected void fillTile ( Graphics2D gfx , int tx , int ty , Color color ) { Composite ocomp = gfx . getComposite ( ) ; gfx . setComposite ( ALPHA_FILL_TILE ) ; Polygon poly = MisoUtil . getTilePolygon ( _metrics , tx , ty ) ; gfx . setColor ( color ) ; gfx . fill ( poly ) ; gfx . setComposite ( ocomp ) ; } | Fills the specified tile with the given color at 50% alpha . Intended for debug - only tile highlighting purposes . |
15,210 | protected BaseTile getBaseTile ( int tx , int ty ) { SceneBlock block = getBlock ( tx , ty ) ; return ( block == null ) ? null : block . getBaseTile ( tx , ty ) ; } | Returns the base tile for the specified tile coordinate . |
15,211 | protected BaseTile getFringeTile ( int tx , int ty ) { SceneBlock block = getBlock ( tx , ty ) ; return ( block == null ) ? null : block . getFringeTile ( tx , ty ) ; } | Returns the fringe tile for the specified tile coordinate . |
15,212 | protected void notifyListeners ( int event ) { int size = _listeners . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { _listeners . get ( ii ) . modelChanged ( event ) ; } } | Notifies all model listeners that the builder model has changed . |
15,213 | public List < Integer > getComponents ( ComponentClass cclass ) { List < Integer > list = _components . get ( cclass ) ; if ( list == null ) { list = Lists . newArrayList ( ) ; } return list ; } | Returns the list of components available in the specified class . |
15,214 | public int [ ] getSelectedComponents ( ) { int [ ] values = new int [ _selected . size ( ) ] ; Iterator < Integer > iter = _selected . values ( ) . iterator ( ) ; for ( int ii = 0 ; iter . hasNext ( ) ; ii ++ ) { values [ ii ] = iter . next ( ) . intValue ( ) ; } return values ; } | Returns the selected components in an array . |
15,215 | public void setSelectedComponent ( ComponentClass cclass , int cid ) { _selected . put ( cclass , Integer . valueOf ( cid ) ) ; notifyListeners ( BuilderModelListener . COMPONENT_CHANGED ) ; } | Sets the selected component for the given component class . |
15,216 | protected void gatherComponentInfo ( ComponentRepository crepo ) { Iterators . addAll ( _classes , crepo . enumerateComponentClasses ( ) ) ; for ( int ii = 0 ; ii < _classes . size ( ) ; ii ++ ) { ComponentClass cclass = _classes . get ( ii ) ; Iterator < Integer > iter = crepo . enumerateComponentIds ( cclass ) ; while ( iter . hasNext ( ) ) { Integer cid = iter . next ( ) ; ArrayList < Integer > clist = _components . get ( cclass ) ; if ( clist == null ) { _components . put ( cclass , clist = Lists . newArrayList ( ) ) ; } clist . add ( cid ) ; } } } | Gathers component class and component information from the character manager for later reference by others . |
15,217 | public static long getOldestLastModified ( File dir ) { long oldest = dir . lastModified ( ) ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { oldest = Math . min ( oldest , getOldestLastModified ( file ) ) ; } else { oldest = Math . min ( oldest , file . lastModified ( ) ) ; } } } return oldest ; } | Returns the timestamp of the oldest modification date of any file within the directory . |
15,218 | public Set < Integer > intKeySet ( ) { return data . keySet ( ) . stream ( ) . map ( Any2 :: getLeft ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . collect ( Collectors . toSet ( ) ) ; } | The numeric set of keys held by the resolver map . |
15,219 | public Set < String > stringKeySet ( ) { return data . keySet ( ) . stream ( ) . map ( Any2 :: getRight ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . collect ( Collectors . toSet ( ) ) ; } | The string set of keys held by the resolver map . |
15,220 | public Map < Any2 < Integer , String > , Any3 < Boolean , Integer , String > > getRawMap ( ) { return unmodifiableMap ( data ) ; } | Get the underlying map of data . |
15,221 | public Map < Any2 < Integer , String > , String > getStringMap ( ) { return data . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( Map . Entry :: getKey , entry -> entry . getValue ( ) . mapCombine ( Object :: toString , Object :: toString , Object :: toString ) ) ) ; } | Get the underlying map but with all values converted to string . |
15,222 | protected void generateSprite ( ) { int components [ ] = _model . getSelectedComponents ( ) ; CharacterDescriptor desc = new CharacterDescriptor ( components , null ) ; CharacterSprite sprite = _charmgr . getCharacter ( desc ) ; setSprite ( sprite ) ; } | Generates a new character sprite for display to reflect the currently selected character components . |
15,223 | protected void setSprite ( CharacterSprite sprite ) { sprite . setActionSequence ( StandardActions . STANDING ) ; sprite . setOrientation ( WEST ) ; _sprite = sprite ; centerSprite ( ) ; repaint ( ) ; } | Sets the sprite to be displayed . |
15,224 | protected void centerSprite ( ) { if ( _sprite != null ) { Dimension d = getSize ( ) ; int shei = _sprite . getHeight ( ) ; int x = d . width / 2 , y = ( d . height + shei ) / 2 ; _sprite . setLocation ( x , y ) ; } } | Sets the sprite s location to render it centered within the panel . |
15,225 | public SimpleMisoSceneModel parseScene ( InputStream in ) throws IOException , SAXException { _model = null ; _digester . push ( this ) ; _digester . parse ( in ) ; return _model ; } | Parses the XML file on the supplied input stream into a scene model instance . |
15,226 | public void setGain ( float gain ) { _gain = gain ; if ( _fadeMode == FadeMode . NONE ) { _source . setGain ( _gain ) ; } } | Sets the base gain of the stream . |
15,227 | public void play ( ) { if ( _state == AL10 . AL_PLAYING ) { log . warning ( "Tried to play stream already playing." ) ; return ; } if ( _state == AL10 . AL_INITIAL ) { _qidx = _qlen = 0 ; queueBuffers ( _buffers . length ) ; } _source . play ( ) ; _state = AL10 . AL_PLAYING ; } | Starts playing this stream . |
15,228 | public void pause ( ) { if ( _state != AL10 . AL_PLAYING ) { log . warning ( "Tried to pause stream that wasn't playing." ) ; return ; } _source . pause ( ) ; _state = AL10 . AL_PAUSED ; } | Pauses this stream . |
15,229 | public void stop ( ) { if ( _state == AL10 . AL_STOPPED ) { log . warning ( "Tried to stop stream that was already stopped." ) ; return ; } _source . stop ( ) ; _state = AL10 . AL_STOPPED ; } | Stops this stream . |
15,230 | public void fadeIn ( float interval ) { if ( _state != AL10 . AL_PLAYING ) { play ( ) ; } _source . setGain ( 0f ) ; _fadeMode = FadeMode . IN ; _fadeInterval = interval ; _fadeElapsed = 0f ; } | Fades this stream in over the specified interval . If the stream isn t playing it will be started . |
15,231 | public void fadeOut ( float interval , boolean dispose ) { _fadeMode = dispose ? FadeMode . OUT_DISPOSE : FadeMode . OUT ; _fadeInterval = interval ; _fadeElapsed = 0f ; } | Fades this stream out over the specified interval . |
15,232 | public void dispose ( ) { if ( _state != AL10 . AL_STOPPED ) { stop ( ) ; } _source . delete ( ) ; for ( Buffer buffer : _buffers ) { buffer . delete ( ) ; } _soundmgr . removeStream ( this ) ; } | Releases the resources held by this stream and removes it from the manager . |
15,233 | protected void updateFade ( float time ) { if ( _fadeMode == FadeMode . NONE ) { return ; } float alpha = Math . min ( ( _fadeElapsed += time ) / _fadeInterval , 1f ) ; _source . setGain ( _gain * ( _fadeMode == FadeMode . IN ? alpha : ( 1f - alpha ) ) ) ; if ( alpha == 1f ) { if ( _fadeMode == FadeMode . OUT ) { stop ( ) ; } else if ( _fadeMode == FadeMode . OUT_DISPOSE ) { dispose ( ) ; } _fadeMode = FadeMode . NONE ; } } | Updates the gain of the stream according to the fade state . |
15,234 | protected boolean populateBuffer ( Buffer buffer ) { if ( _abuf == null ) { _abuf = ByteBuffer . allocateDirect ( getBufferSize ( ) ) . order ( ByteOrder . nativeOrder ( ) ) ; } _abuf . clear ( ) ; int read = 0 ; try { read = Math . max ( populateBuffer ( _abuf ) , 0 ) ; } catch ( IOException e ) { log . warning ( "Error reading audio stream [error=" + e + "]." ) ; } if ( read <= 0 ) { return false ; } _abuf . rewind ( ) . limit ( read ) ; buffer . setData ( getFormat ( ) , _abuf , getFrequency ( ) ) ; return true ; } | Populates the identified buffer with as much data as it can hold . |
15,235 | private Map < MetricName , MetricValue > get_metrics_ ( DateTime now , Context ctx ) { final Consumer < Alert > alert_manager = ctx . getAlertManager ( ) ; final long failed_collections = registry_ . getFailedCollections ( ) ; final boolean has_config = registry_ . hasConfig ( ) ; final Optional < Duration > scrape_duration = registry_ . getScrapeDuration ( ) ; final Optional < Duration > rule_eval_duration = registry_ . getRuleEvalDuration ( ) ; final Optional < Duration > processor_duration = registry_ . getProcessorDuration ( ) ; first_scrape_ts_ . compareAndSet ( null , now ) ; final Duration uptime = new Duration ( first_scrape_ts_ . get ( ) , now ) ; final Optional < DateTime > last_scrape = last_scrape_ ; last_scrape_ = Optional . of ( now ) ; final long metric_count = ctx . getTSData ( ) . getCurrentCollection ( ) . getTSValues ( ) . stream ( ) . map ( TimeSeriesValue :: getMetrics ) . collect ( Collectors . summingLong ( Map :: size ) ) ; alert_manager . accept ( new Alert ( now , MONITOR_FAIL_ALERT , ( ) -> "builtin rule" , Optional . of ( failed_collections != 0 ) , MON_ALERT_DURATION , "builtin rule: some collectors failed" , EMPTY_MAP ) ) ; alert_manager . accept ( new Alert ( now , HAS_CONFIG_ALERT , ( ) -> "builtin rule" , Optional . of ( ! has_config ) , Duration . ZERO , "builtin rule: monitor has no configuration file" , EMPTY_MAP ) ) ; Map < MetricName , MetricValue > result = new HashMap < > ( ) ; result . put ( FAILED_COLLECTIONS_METRIC , MetricValue . fromIntValue ( failed_collections ) ) ; result . put ( GROUP_COUNT_METRIC , MetricValue . fromIntValue ( ctx . getTSData ( ) . getCurrentCollection ( ) . getGroups ( x -> true ) . size ( ) ) ) ; result . put ( METRIC_COUNT_METRIC , MetricValue . fromIntValue ( metric_count ) ) ; result . put ( CONFIG_PRESENT_METRIC , MetricValue . fromBoolean ( has_config ) ) ; result . put ( SCRAPE_DURATION , opt_duration_to_metricvalue_ ( scrape_duration ) ) ; result . put ( RULE_EVAL_DURATION , opt_duration_to_metricvalue_ ( rule_eval_duration ) ) ; result . put ( PROCESSOR_DURATION , opt_duration_to_metricvalue_ ( processor_duration ) ) ; result . put ( UPTIME_DURATION , duration_to_metricvalue_ ( uptime ) ) ; result . put ( SCRAPE_COUNT , MetricValue . fromIntValue ( ++ scrape_count_ ) ) ; result . put ( SCRAPE_INTERVAL , opt_duration_to_metricvalue_ ( last_scrape . map ( prev -> new Duration ( prev , now ) ) ) ) ; result . put ( SCRAPE_TS , MetricValue . fromIntValue ( now . getMillis ( ) ) ) ; return result ; } | Get metrics for the monitor . |
15,236 | public void transform ( Context < MutableTimeSeriesCollectionPair > ctx ) { DateTime now = ctx . getTSData ( ) . getCurrentCollection ( ) . getTimestamp ( ) ; ctx . getTSData ( ) . getCurrentCollection ( ) . addMetrics ( MONITOR_GROUP , get_metrics_ ( now , ctx ) ) ; ctx . getAlertManager ( ) . accept ( new Alert ( now , MONITOR_DOWN_ALERT , ( ) -> "builtin rule" , Optional . of ( false ) , Duration . ZERO , "builtin rule: monitor is not running for some time" , EMPTY_MAP ) ) ; } | Emit an alert monitor . down which is in the OK state . |
15,237 | private static MetricValue opt_duration_to_metricvalue_ ( Optional < Duration > duration ) { return duration . map ( MonitorMonitor :: duration_to_metricvalue_ ) . orElse ( MetricValue . EMPTY ) ; } | Convert an optional duration to a metric value . |
15,238 | private void validate ( ) { try { DateTime ts ; ts = current . getTimestamp ( ) ; for ( TimeSeriesCollection b : backward ) { if ( b . getTimestamp ( ) . isAfter ( ts ) ) throw new IllegalArgumentException ( "backwards collection must be before current and be ordered in reverse chronological order" ) ; ts = b . getTimestamp ( ) ; } ts = current . getTimestamp ( ) ; for ( TimeSeriesCollection f : forward ) { if ( f . getTimestamp ( ) . isBefore ( ts ) ) throw new IllegalArgumentException ( "forwards collection must be after current and be ordered in chronological order" ) ; ts = f . getTimestamp ( ) ; } } catch ( IllegalArgumentException ex ) { LOG . log ( Level . SEVERE , "programmer error in creating interpolated TimeSeriesCollection" , ex ) ; final List < DateTime > backward_ts = backward . stream ( ) . map ( TimeSeriesCollection :: getTimestamp ) . collect ( Collectors . toList ( ) ) ; final List < DateTime > forward_ts = forward . stream ( ) . map ( TimeSeriesCollection :: getTimestamp ) . collect ( Collectors . toList ( ) ) ; LOG . log ( Level . INFO , "current = {0}, backward = {1}, forward = {2}" , new Object [ ] { current . getTimestamp ( ) , backward_ts , forward_ts } ) ; throw ex ; } } | Check the forward and backward invariants . |
15,239 | private static Set < GroupName > calculateNames ( TimeSeriesCollection current , Collection < TimeSeriesCollection > backward , Collection < TimeSeriesCollection > forward ) { final Set < GroupName > names = backward . stream ( ) . flatMap ( tsc -> tsc . getGroups ( x -> true ) . stream ( ) ) . collect ( Collectors . toCollection ( THashSet :: new ) ) ; names . retainAll ( forward . stream ( ) . flatMap ( tsc -> tsc . getGroups ( x -> true ) . stream ( ) ) . collect ( Collectors . toSet ( ) ) ) ; names . removeAll ( current . getGroups ( x -> true ) ) ; return names ; } | Calculate all names that can be interpolated . The returned set will not have any names present in the current collection . |
15,240 | private TimeSeriesValue interpolateTSV ( GroupName name ) { final Map . Entry < DateTime , TimeSeriesValue > backTSV = findName ( backward , name ) , forwTSV = findName ( forward , name ) ; final long backMillis = max ( new Duration ( backTSV . getKey ( ) , getTimestamp ( ) ) . getMillis ( ) , 0 ) , forwMillis = max ( new Duration ( getTimestamp ( ) , forwTSV . getKey ( ) ) . getMillis ( ) , 0 ) ; final double totalMillis = forwMillis + backMillis ; final double backWeight = forwMillis / totalMillis ; final double forwWeight = backMillis / totalMillis ; return new InterpolatedTSV ( name , backTSV . getValue ( ) . getMetrics ( ) , forwTSV . getValue ( ) . getMetrics ( ) , backWeight , forwWeight ) ; } | Interpolates a group name based on the most recent backward and oldest forward occurence . |
15,241 | private static Map . Entry < DateTime , TimeSeriesValue > findName ( List < TimeSeriesCollection > c , GroupName name ) { ListIterator < TimeSeriesCollection > iter = c . listIterator ( ) ; while ( iter . hasNext ( ) ) { final int idx = iter . nextIndex ( ) ; final TimeSeriesCollection tsdata = iter . next ( ) ; final Optional < TimeSeriesValue > found = tsdata . get ( name ) ; if ( found . isPresent ( ) ) return SimpleMapEntry . create ( tsdata . getTimestamp ( ) , found . get ( ) ) ; } throw new IllegalStateException ( "name not present in list of time series collections" ) ; } | Finds the first resolution of name in the given TimeSeriesCollections . The cache is used and updated to skip the linear search phase . |
15,242 | protected void createBackBuffer ( GraphicsConfiguration gc ) { if ( _backimg != null ) { _backimg . flush ( ) ; _bgfx . dispose ( ) ; } int width = _window . getWidth ( ) , height = _window . getHeight ( ) ; _backimg = gc . createCompatibleVolatileImage ( width , height ) ; _bgfx = ( Graphics2D ) _backimg . getGraphics ( ) ; _bgfx . fillRect ( 0 , 0 , width , height ) ; if ( _fgfx != null ) { _fgfx . dispose ( ) ; _fgfx = null ; } } | Creates the off - screen buffer used to perform double buffered rendering of the animated panel . |
15,243 | public static void trimTileSet ( TileSet source , OutputStream destImage , TrimMetricsReceiver tmr ) throws IOException { trimTileSet ( source , destImage , tmr , FastImageIO . FILE_SUFFIX ) ; } | Convenience function to trim the tile set using FastImageIO to save the result . |
15,244 | public static void setRegisterWithVM ( final boolean registerWithVM ) { if ( Converters . registerWithVM != registerWithVM ) { Converters . registerWithVM = registerWithVM ; if ( registerWithVM ) { for ( Entry < Class , Converter > entry : REGISTRY . entrySet ( ) ) { Class type = entry . getKey ( ) ; Converter converter = entry . getValue ( ) ; PropertyEditorManager . registerEditor ( type , converter . getClass ( ) ) ; } } } } | Sets if converters registered with the VM PropertyEditorManager . If the new value is true all currently registered converters are immediately registered with the VM . |
15,245 | private static PropertyEditor findEditor ( final Type type ) { assert type != null ; Class clazz = toClass ( type ) ; PropertyEditor editor = PropertyEditorManager . findEditor ( clazz ) ; if ( editor != null ) { return editor ; } if ( clazz . isArray ( ) && ! clazz . getComponentType ( ) . isArray ( ) ) { editor = findEditor ( clazz . getComponentType ( ) ) ; if ( editor != null ) { return new ArrayConverter ( clazz , editor ) ; } } return null ; } | Locate a property editor for given class of object . |
15,246 | public static int [ ] quantizeImage ( int pixels [ ] [ ] , int max_colors ) { Cube cube = new Cube ( pixels , max_colors ) ; cube . classification ( ) ; cube . reduction ( ) ; cube . assignment ( ) ; return cube . colormap ; } | Reduce the image to the given number of colors . |
15,247 | public void paint ( Graphics2D gfx , int layer , Shape clip ) { for ( int ii = 0 , nn = _media . size ( ) ; ii < nn ; ii ++ ) { AbstractMedia media = _media . get ( ii ) ; int order = media . getRenderOrder ( ) ; try { if ( ( ( layer == ALL ) || ( layer == FRONT && order >= 0 ) || ( layer == BACK && order < 0 ) ) && clip . intersects ( media . getBounds ( ) ) ) { media . paint ( gfx ) ; } } catch ( Exception e ) { log . warning ( "Failed to render media" , "media" , media , e ) ; } } } | Renders all registered media in the given layer that intersect the supplied clipping rectangle to the given graphics context . |
15,248 | public void fastForward ( long timeDelta ) { if ( _tickStamp > 0 ) { log . warning ( "Egads! Asked to fastForward() during a tick." , new Exception ( ) ) ; } for ( int ii = 0 , nn = _media . size ( ) ; ii < nn ; ii ++ ) { _media . get ( ii ) . fastForward ( timeDelta ) ; } } | If the manager is paused for some length of time it should be fast forwarded by the appropriate number of milliseconds . This allows media to smoothly pick up where they left off rather than abruptly jumping into the future thinking that some outrageous amount of time passed since their last tick . |
15,249 | protected boolean insertMedia ( AbstractMedia media ) { if ( _media . contains ( media ) ) { log . warning ( "Attempt to insert media more than once [media=" + media + "]." , new Exception ( ) ) ; return false ; } media . init ( this ) ; int ipos = _media . insertSorted ( media , RENDER_ORDER ) ; if ( _tickStamp > 0L ) { if ( _tickpos == - 1 ) { tickMedia ( media , _tickStamp ) ; } else if ( ipos <= _tickpos ) { _tickpos ++ ; tickMedia ( media , _tickStamp ) ; } } return true ; } | Inserts the specified media into this manager return true on success . |
15,250 | protected boolean removeMedia ( AbstractMedia media ) { int mpos = _media . indexOf ( media ) ; if ( mpos != - 1 ) { _media . remove ( mpos ) ; media . invalidate ( ) ; media . shutdown ( ) ; if ( mpos <= _tickpos ) { _tickpos -- ; } return true ; } log . warning ( "Attempt to remove media that wasn't inserted [media=" + media + "]." ) ; return false ; } | Removes the specified media from this manager return true on success . |
15,251 | public void queueNotification ( ObserverList < Object > observers , ObserverOp < Object > event ) { _notify . add ( new Tuple < ObserverList < Object > , ObserverOp < Object > > ( observers , event ) ) ; } | Queues the notification for dispatching after we ve ticked all the media . |
15,252 | protected void dispatchNotifications ( ) { for ( int ii = 0 , nn = _notify . size ( ) ; ii < nn ; ii ++ ) { Tuple < ObserverList < Object > , ObserverOp < Object > > tuple = _notify . get ( ii ) ; tuple . left . apply ( tuple . right ) ; } _notify . clear ( ) ; } | Dispatches all queued media notifications . |
15,253 | public static < T > void addArrayIfNotNull ( JSONWriter writer , String field , Collection < T > items , JsonObjectWriter < T > objWriter ) throws JSONException { if ( items == null ) return ; addCollection ( writer , field , items , objWriter ) ; } | Adds a list . |
15,254 | protected void startAnimation ( Animation anim , long tickStamp ) { if ( _vdx != 0 || _vdy != 0 ) { anim . viewLocationDidChange ( _vdx , _vdy ) ; } _animmgr . registerAnimation ( anim ) ; } | Called when the time comes to start an animation . Derived classes may override this method and pass the animation on to their animation manager and do whatever else they need to do with operating animations . The default implementation simply adds them to the media panel supplied when we were constructed . |
15,255 | public void setScrollableArea ( int x , int y , int width , int height ) { Rectangle vb = _panel . getViewBounds ( ) ; int hmax = x + width , vmax = y + height , value ; if ( width > vb . width ) { value = MathUtil . bound ( x , _hrange . getValue ( ) , hmax - vb . width ) ; _hrange . setRangeProperties ( value , vb . width , x , hmax , false ) ; } else { int newx = x - ( vb . width - width ) / 2 ; _hrange . setRangeProperties ( newx , 0 , newx , newx , false ) ; } if ( height > vb . height ) { value = MathUtil . bound ( y , _vrange . getValue ( ) , vmax - vb . height ) ; _vrange . setRangeProperties ( value , vb . height , y , vmax , false ) ; } else { int newy = y - ( vb . height - height ) / 2 ; _vrange . setRangeProperties ( newy , 0 , newy , newy , false ) ; } } | Informs the virtual range model the extent of the area over which we can scroll . |
15,256 | public BufferedImage createImage ( int width , int height , int transparency ) { return _icreator . createImage ( width , height , transparency ) ; } | Creates a buffered image optimized for display on our graphics device . |
15,257 | public ImageKey getImageKey ( String rset , String path ) { return getImageKey ( getDataProvider ( rset ) , path ) ; } | Returns an image key that can be used to fetch the image identified by the specified resource set and image path . |
15,258 | public BufferedImage getImage ( ImageKey key , Colorization [ ] zations ) { CacheRecord crec = null ; synchronized ( _ccache ) { crec = _ccache . get ( key ) ; } if ( crec != null ) { return crec . getImage ( zations , _ccache ) ; } BufferedImage image = loadImage ( key ) ; if ( image == null ) { log . warning ( "Failed to load image " + key + "." ) ; image = new BufferedImage ( 10 , 10 , BufferedImage . TYPE_BYTE_INDEXED ) ; } crec = new CacheRecord ( key , image ) ; synchronized ( _ccache ) { _ccache . put ( key , crec ) ; } _keySet . add ( key ) ; reportCachePerformance ( ) ; return crec . getImage ( zations , _ccache ) ; } | Obtains the image identified by the specified key caching if possible . The image will be recolored using the supplied colorizations if requested . |
15,259 | public Mirage getMirage ( String rsrcPath ) { return getMirage ( getImageKey ( _defaultProvider , rsrcPath ) , null , null ) ; } | Creates a mirage which is an image optimized for display on our current display device and which will be stored into video memory if possible . |
15,260 | protected ImageDataProvider getDataProvider ( final String rset ) { if ( rset == null ) { return _defaultProvider ; } ImageDataProvider dprov = _providers . get ( rset ) ; if ( dprov == null ) { dprov = new ImageDataProvider ( ) { public BufferedImage loadImage ( String path ) throws IOException { try { return _rmgr . getImageResource ( rset , path ) ; } catch ( FileNotFoundException fnfe ) { return _rmgr . getImageResource ( path ) ; } } public String getIdent ( ) { return "rmgr:" + rset ; } } ; _providers . put ( rset , dprov ) ; } return dprov ; } | Returns the data provider configured to obtain image data from the specified resource set . |
15,261 | protected BufferedImage loadImage ( ImageKey key ) { BufferedImage image = null ; try { log . debug ( "Loading image " + key + "." ) ; image = key . daprov . loadImage ( key . path ) ; if ( image == null ) { log . warning ( "ImageDataProvider.loadImage(" + key + ") returned null." ) ; } } catch ( Exception e ) { log . warning ( "Unable to load image '" + key + "'." , e ) ; image = createImage ( 1 , 1 , Transparency . OPAQUE ) ; } return image ; } | Loads and returns the image with the specified key from the supplied data provider . |
15,262 | public void setPosition ( float x , float y , float z ) { if ( _source != null ) { _source . setPosition ( x , y , z ) ; } _px = x ; _py = y ; _pz = z ; } | Sets the position of the sound . |
15,263 | public void setVelocity ( float x , float y , float z ) { if ( _source != null ) { _source . setVelocity ( x , y , z ) ; } _vx = x ; _vy = y ; _vz = z ; } | Sets the velocity of the sound . |
15,264 | public void setDirection ( float x , float y , float z ) { if ( _source != null ) { _source . setDirection ( x , y , z ) ; } _dx = x ; _dy = y ; _dz = z ; } | Sets the direction of the sound . |
15,265 | public static MediaTimer createTimer ( ) { MediaTimer timer = null ; for ( String timerClass : PERF_TIMERS ) { try { timer = ( MediaTimer ) Class . forName ( timerClass ) . newInstance ( ) ; break ; } catch ( Throwable t ) { } } if ( timer == null ) { log . info ( "Can't use high performance timer, reverting to " + "System.currentTimeMillis() based timer." ) ; timer = new MillisTimer ( ) ; } return timer ; } | Attempts to create a high resolution timer but if that isn t possible uses a System . currentTimeMillis based timer . |
15,266 | public static FrameManager newInstance ( ManagedRoot root , MediaTimer timer ) { FrameManager fmgr = ( root instanceof ManagedJFrame && _useFlip . getValue ( ) ) ? new FlipFrameManager ( ) : new BackFrameManager ( ) ; fmgr . init ( root , timer ) ; return fmgr ; } | Constructs a frame manager that will do its rendering to the supplied root and use the supplied media timer for timing information . |
15,267 | public void registerFrameParticipant ( FrameParticipant participant ) { Object [ ] nparts = ListUtil . testAndAddRef ( _participants , participant ) ; if ( nparts == null ) { log . warning ( "Refusing to add duplicate frame participant! " + participant ) ; } else { _participants = nparts ; } } | Registers a frame participant . The participant will be given the opportunity to do processing and rendering on each frame . |
15,268 | public TrailingAverage [ ] getPerfMetrics ( ) { if ( _metrics == null ) { _metrics = new TrailingAverage [ ] { new TrailingAverage ( 150 ) , new TrailingAverage ( 150 ) , new TrailingAverage ( 150 ) } ; } return _metrics ; } | Returns debug performance metrics . |
15,269 | public static Component getRoot ( Component comp , Rectangle rect ) { for ( Component c = comp ; c != null ; c = c . getParent ( ) ) { if ( ! c . isVisible ( ) || ! c . isDisplayable ( ) ) { return null ; } if ( c instanceof Window || c instanceof Applet ) { return c ; } rect . x += c . getX ( ) ; rect . y += c . getY ( ) ; } return null ; } | Returns the root component for the supplied component or null if it is not part of a rooted hierarchy or if any parent along the way is found to be hidden or without a peer . Along the way it adjusts the supplied component - relative rectangle to be relative to the returned root component . |
15,270 | protected void init ( ManagedRoot root , MediaTimer timer ) { _window = root . getWindow ( ) ; _root = root ; _root . init ( this ) ; _timer = timer ; _repainter = new ActiveRepaintManager ( ( _root instanceof Component ) ? ( Component ) _root : _window ) ; RepaintManager . setCurrentManager ( _repainter ) ; _repainter . setDoubleBufferingEnabled ( false ) ; } | Initializes this frame manager and prepares it for operation . |
15,271 | protected void tick ( long tickStamp ) { long start = 0L , paint = 0L ; if ( _perfDebug . getValue ( ) ) { start = paint = _timer . getElapsedMicros ( ) ; } if ( _window . isShowing ( ) && _window . getWidth ( ) > 0 && _window . getHeight ( ) > 0 ) { tickParticipants ( tickStamp ) ; paint = _timer . getElapsedMicros ( ) ; paint ( tickStamp ) ; } if ( _perfDebug . getValue ( ) ) { long end = _timer . getElapsedMicros ( ) ; getPerfMetrics ( ) [ 1 ] . record ( ( int ) ( paint - start ) / 100 ) ; getPerfMetrics ( ) [ 2 ] . record ( ( int ) ( end - paint ) / 100 ) ; } } | Called to perform the frame processing and rendering . |
15,272 | protected boolean paint ( Graphics2D gfx ) { int painted = 0 ; for ( Object participant : _participants ) { FrameParticipant part = ( FrameParticipant ) participant ; if ( part == null ) { continue ; } Component pcomp = part . getComponent ( ) ; if ( pcomp == null || ! part . needsPaint ( ) ) { continue ; } long start = 0L ; if ( HANG_DEBUG ) { start = System . currentTimeMillis ( ) ; } pcomp . getBounds ( _tbounds ) ; _tbounds . setLocation ( 0 , 0 ) ; if ( getRoot ( pcomp , _tbounds ) == null ) { continue ; } try { gfx . translate ( _tbounds . x , _tbounds . y ) ; pcomp . paint ( gfx ) ; gfx . translate ( - _tbounds . x , - _tbounds . y ) ; painted ++ ; } catch ( Throwable t ) { String ptos = StringUtil . safeToString ( part ) ; log . warning ( "Frame participant choked during paint [part=" + ptos + "]." , t ) ; } _clipped [ 0 ] = false ; renderLayers ( gfx , pcomp , _tbounds , _clipped , _tbounds ) ; if ( HANG_DEBUG ) { long delay = ( System . currentTimeMillis ( ) - start ) ; if ( delay > HANG_GAP ) { log . warning ( "Whoa nelly! Painter took a long time" , "part" , part , "time" , delay + "ms" ) ; } } } if ( _overlay != null ) { _overlay . propagateDirtyRegions ( _repainter , _root . getRootPane ( ) ) ; } boolean pcomp = _repainter . paintComponents ( gfx , this ) ; if ( _overlay != null ) { pcomp |= _overlay . paint ( gfx ) ; } return ( ( painted > 0 ) || pcomp ) ; } | Paints our frame participants and any dirty components via the repaint manager . |
15,273 | protected void renderLayer ( Graphics2D g , Rectangle bounds , JLayeredPane pane , boolean [ ] clipped , Integer layer ) { int ccount = pane . getComponentCountInLayer ( layer . intValue ( ) ) ; if ( ccount == 0 ) { return ; } Component [ ] comps = pane . getComponentsInLayer ( layer . intValue ( ) ) ; for ( int ii = 0 ; ii < ccount ; ii ++ ) { Component comp = comps [ ii ] ; if ( ! comp . isVisible ( ) || comp instanceof SafeLayerComponent ) { continue ; } Rectangle compBounds = new Rectangle ( 0 , 0 , comp . getWidth ( ) , comp . getHeight ( ) ) ; getRoot ( comp , compBounds ) ; if ( ! compBounds . intersects ( bounds ) ) { continue ; } if ( ! clipped [ 0 ] ) { g . setClip ( bounds ) ; clipped [ 0 ] = true ; } g . translate ( compBounds . x , compBounds . y ) ; try { comp . paint ( g ) ; } catch ( Exception e ) { log . warning ( "Component choked while rendering." , e ) ; } g . translate ( - compBounds . x , - compBounds . y ) ; } } | Renders all components in the specified layer of the supplied layered pane that intersect the supplied bounds . |
15,274 | public static < T > Iterator < T > distinct ( final Iterator < T > iterator ) { requireNonNull ( iterator ) ; return new AbstractIterator < T > ( ) { private final PeekingIterator < T > peekingIterator = peekingIterator ( iterator ) ; private T curr = null ; protected T computeNext ( ) { while ( peekingIterator . hasNext ( ) && Objects . equals ( curr , peekingIterator . peek ( ) ) ) { peekingIterator . next ( ) ; } if ( ! peekingIterator . hasNext ( ) ) return endOfData ( ) ; curr = peekingIterator . next ( ) ; return curr ; } } ; } | If we can assume the iterator is sorted return the distinct elements . This only works if the data provided is sorted . |
15,275 | public ActionFrames getFrames ( String action , String type ) { return _frameProvider . getFrames ( this , action , type ) ; } | Returns the image frames for the specified action animation or null if no animation for the specified action is available for this component . |
15,276 | public String getFramePath ( String action , String type , Set < String > existentPaths ) { return _frameProvider . getFramePath ( this , action , type , existentPaths ) ; } | Returns the path to the image frames for the specified action animation or null if no animation for the specified action is available for this component . |
15,277 | protected OutputStream nextEntry ( OutputStream lastEntry , String path ) throws IOException { ( ( JarOutputStream ) lastEntry ) . putNextEntry ( new JarEntry ( path ) ) ; return lastEntry ; } | Advances to the next named entry in the bundle and returns the stream to which to write that entry . |
15,278 | public QueryBuilder map ( String query , String method_name , Object ... items ) throws Exception { JSONObject op = new JSONObject ( ) ; if ( query != null ) op . put ( Constants . REQUEST_QUERY , query ) ; java . util . Map < String , Object > operation = new LinkedHashMap < String , Object > ( ) ; operation . put ( Constants . REQUEST_METHOD_NAME , method_name ) ; if ( query != null ) queryStringRepresentation += query ; queryStringRepresentation += "." + method_name ; operation . put ( Constants . REQUEST_ARGUMENTS , buildArgsArray ( items ) ) ; op . put ( Constants . REQUEST_OPERATION , operation ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; } | Used to get the return from a method call |
15,279 | public QueryBuilder instantiate ( String query , Object ... items ) throws Exception { JSONObject op = new JSONObject ( ) ; if ( query != null ) op . put ( Constants . REQUEST_INSTANTIATE , query ) ; if ( query != null ) queryStringRepresentation += query ; op . put ( Constants . REQUEST_ARGUMENTS , buildArgsArray ( items ) ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; } | Used to instantiate a class |
15,280 | private JSONArray buildArgsArray ( Object ... items ) throws Exception { JSONArray args = new JSONArray ( ) ; for ( int i = 0 ; i < items . length ; i ++ ) { if ( items [ i ] instanceof java . lang . String ) { args . put ( ( String ) items [ i ] ) ; } else if ( items [ i ] instanceof Number ) { args . put ( ( Number ) items [ i ] ) ; } else if ( items [ i ] instanceof java . lang . Boolean ) { args . put ( ( Boolean ) items [ i ] ) ; } else if ( items [ i ] == null ) { args . put ( ( Object ) null ) ; } else { throw new Exception ( "Invalid type" ) ; } } return args ; } | Internal function used to build a JSON Array of arguments from a list of items |
15,281 | private QueryBuilder genericRequest ( String type , String value ) throws Exception { JSONObject op = new JSONObject ( ) ; op . put ( type , value ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; } | Creates a key value request |
15,282 | public JSONArray execute ( ) throws Exception { try { JSONArray retVal = Client . getInstance ( port ) . map ( toString ( ) ) ; return retVal ; } catch ( Exception e ) { throw new Exception ( queryStringRepresentation + ": " + e . getMessage ( ) ) ; } } | Execute a series of commands |
15,283 | protected Object getInstantiatedClass ( String query ) { if ( query . equals ( Constants . UIAUTOMATOR_UIDEVICE ) ) { return device ; } return null ; } | Implementation of getInstantiatedClass that returns a UiDevice if one is requested |
15,284 | public synchronized void setHistory ( CollectHistory history ) { history_ = Optional . of ( history ) ; history_ . ifPresent ( getApi ( ) :: setHistory ) ; data_ . initWithHistoricalData ( history , getDecoratorLookBack ( ) ) ; } | Set the history module that the push processor is to use . |
15,285 | protected synchronized CollectionContext beginCollection ( DateTime now ) { data_ . startNewCycle ( now , getDecoratorLookBack ( ) ) ; return new CollectionContext ( ) { final Map < GroupName , Alert > alerts = new HashMap < > ( ) ; public Consumer < Alert > alertManager ( ) { return ( Alert alert ) -> { Alert combined = combine_alert_with_past_ ( alert , alerts_ ) ; alerts . put ( combined . getName ( ) , combined ) ; } ; } public MutableTimeSeriesCollectionPair tsdata ( ) { return data_ ; } public void commit ( ) { alerts_ = unmodifiableMap ( alerts ) ; try { getHistory ( ) . ifPresent ( history -> history . add ( getCollectionData ( ) ) ) ; } catch ( Exception ex ) { logger . log ( Level . WARNING , "unable to add collection data to history (dropped)" , ex ) ; } } } ; } | Begin a new collection cycle . |
15,286 | private static Alert combine_alert_with_past_ ( Alert alert , Map < GroupName , Alert > previous ) { Alert result = Optional . ofNullable ( previous . get ( alert . getName ( ) ) ) . map ( ( prev ) -> prev . extend ( alert ) ) . orElse ( alert ) ; logger . log ( Level . FINE , "emitting alert {0} -> {1}" , new Object [ ] { result . getName ( ) , result . getAlertState ( ) . name ( ) } ) ; return result ; } | Combine a new alert with its previous state . |
15,287 | public static synchronized PushMetricRegistryInstance create ( Supplier < DateTime > now , boolean has_config , EndpointRegistration api ) { return new PushMetricRegistryInstance ( now , has_config , api ) ; } | Create a plain uninitialized metric registry . |
15,288 | public static Mirage newNinePatchContaining ( NinePatch ninePatch , Rectangle content ) { Rectangle bounds = ninePatch . getBoundsSurrounding ( content ) ; Mirage mirage = new NinePatchMirage ( ninePatch , bounds . width , bounds . height ) ; return new TransformedMirage ( mirage , AffineTransform . getTranslateInstance ( bounds . x , bounds . y ) , false ) ; } | Returns a new Mirage that s a NinePatch stretched and positioned to contain the given Rectangle . |
15,289 | public static boolean isDisjoint ( Collection < Range > ranges ) { List < Range > rangesList = new ArrayList < Range > ( ranges . size ( ) ) ; rangesList . addAll ( ranges ) ; Collections . sort ( rangesList ) ; for ( int i = 0 ; i < rangesList . size ( ) - 1 ; i ++ ) { Range rCurrent = rangesList . get ( i ) ; Range rNext = rangesList . get ( i + 1 ) ; if ( rCurrent . overlapsWith ( rNext ) ) { return false ; } } return true ; } | Checks weather the given set of ranges are disjoint i . e . none of the ranges overlap . |
15,290 | private static EscapeStringResult escapeString ( String s , char quote ) { final String [ ] octal_strings = { "\\0" , "\\001" , "\\002" , "\\003" , "\\004" , "\\005" , "\\006" , "\\a" , "\\b" , "\\t" , "\\n" , "\\v" , "\\f" , "\\r" , "\\016" , "\\017" , "\\020" , "\\021" , "\\022" , "\\023" , "\\024" , "\\025" , "\\026" , "\\027" , "\\030" , "\\031" , "\\032" , "\\033" , "\\034" , "\\035" , "\\036" , "\\037" , } ; StringBuilder result = new StringBuilder ( s ) ; boolean needQuotes = s . isEmpty ( ) ; for ( int i = 0 , next_i ; i < result . length ( ) ; i = next_i ) { final int code_point = result . codePointAt ( i ) ; next_i = result . offsetByCodePoints ( i , 1 ) ; if ( code_point == 0 ) { result . replace ( i , next_i , "\\0" ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point == ( int ) '\\' ) { result . replace ( i , next_i , "\\\\" ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point == ( int ) quote ) { result . replace ( i , next_i , "\\" + quote ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point < 32 ) { String octal = octal_strings [ code_point ] ; result . replace ( i , next_i , octal ) ; next_i = i + octal . length ( ) ; needQuotes = true ; } else if ( code_point >= 65536 ) { String repl = String . format ( "\\U%08x" , code_point ) ; result . replace ( i , next_i , repl ) ; next_i = i + repl . length ( ) ; needQuotes = true ; } else if ( code_point >= 128 ) { String repl = String . format ( "\\u%04x" , code_point ) ; result . replace ( i , next_i , repl ) ; next_i = i + repl . length ( ) ; needQuotes = true ; } } return new EscapeStringResult ( needQuotes , result ) ; } | Escape a string configuration element . |
15,291 | public static StringBuilder quotedString ( String s ) { final EscapeStringResult escapeString = escapeString ( s , '\"' ) ; final StringBuilder result = escapeString . buffer ; result . insert ( 0 , '\"' ) ; result . append ( '\"' ) ; return result ; } | Create a quoted string configuration element . |
15,292 | public static StringBuilder maybeQuoteIdentifier ( String s ) { final EscapeStringResult escapeString = escapeString ( s , '\'' ) ; final StringBuilder result = escapeString . buffer ; final boolean need_quotes = s . isEmpty ( ) || escapeString . needQuotes || KEYWORDS . contains ( s ) || ! IDENTIFIER_MATCHER . test ( s ) ; if ( need_quotes ) { result . insert ( 0 , '\'' ) ; result . append ( '\'' ) ; } return result ; } | Create an identifier configuration element . |
15,293 | public static StringBuilder durationConfigString ( Duration duration ) { Duration remainder = duration ; long days = remainder . getStandardDays ( ) ; remainder = remainder . minus ( Duration . standardDays ( days ) ) ; long hours = remainder . getStandardHours ( ) ; remainder = remainder . minus ( Duration . standardHours ( hours ) ) ; long minutes = remainder . getStandardMinutes ( ) ; remainder = remainder . minus ( Duration . standardMinutes ( minutes ) ) ; long seconds = remainder . getStandardSeconds ( ) ; remainder = remainder . minus ( Duration . standardSeconds ( seconds ) ) ; if ( ! remainder . isEqual ( Duration . ZERO ) ) Logger . getLogger ( ConfigSupport . class . getName ( ) ) . log ( Level . WARNING , "Duration is more precise than configuration will handle: {0}, dropping remainder: {1}" , new Object [ ] { duration , remainder } ) ; StringBuilder result = new StringBuilder ( ) ; if ( days != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( days ) . append ( 'd' ) ; } if ( hours != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( hours ) . append ( 'h' ) ; } if ( minutes != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( minutes ) . append ( 'm' ) ; } if ( result . length ( ) == 0 || seconds != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( seconds ) . append ( 's' ) ; } return result ; } | Convert duration to an representation accepted by Configuration parser . |
15,294 | public < R > R download ( String uri , ContentHandler < BasicHttpResponse , R > handler ) throws RedmineException { final HttpGet request = new HttpGet ( uri ) ; return errorCheckingCommunicator . sendRequest ( request , handler ) ; } | Downloads a redmine content . |
15,295 | public String upload ( InputStream content ) throws RedmineException { final URI uploadURI = getURIConfigurator ( ) . getUploadURI ( ) ; final HttpPost request = new HttpPost ( uploadURI ) ; final AbstractHttpEntity entity = new InputStreamEntity ( content , - 1 ) ; entity . setContentType ( "application/octet-stream" ) ; request . setEntity ( entity ) ; final String result = getCommunicator ( ) . sendRequest ( request ) ; return parseResponse ( result , "upload" , RedmineJSONParser . UPLOAD_TOKEN_PARSER ) ; } | UPloads content on a server . |
15,296 | public < T > List < T > getObjectsList ( Class < T > objectClass , Collection < ? extends NameValuePair > params ) throws RedmineException { final EntityConfig < T > config = getConfig ( objectClass ) ; final List < T > result = new ArrayList < T > ( ) ; final List < NameValuePair > newParams = new ArrayList < NameValuePair > ( params ) ; newParams . add ( new BasicNameValuePair ( "limit" , String . valueOf ( objectsPerPage ) ) ) ; int offset = 0 ; int totalObjectsFoundOnServer ; do { List < NameValuePair > paramsList = new ArrayList < NameValuePair > ( newParams ) ; paramsList . add ( new BasicNameValuePair ( "offset" , String . valueOf ( offset ) ) ) ; final URI uri = getURIConfigurator ( ) . getObjectsURI ( objectClass , paramsList ) ; logger . debug ( uri . toString ( ) ) ; final HttpGet http = new HttpGet ( uri ) ; final String response = getCommunicator ( ) . sendRequest ( http ) ; logger . debug ( "received: " + response ) ; final List < T > foundItems ; try { final JSONObject responseObject = RedmineJSONParser . getResponse ( response ) ; foundItems = JsonInput . getListOrNull ( responseObject , config . multiObjectName , config . parser ) ; result . addAll ( foundItems ) ; if ( ! responseObject . has ( KEY_TOTAL_COUNT ) ) { break ; } totalObjectsFoundOnServer = JsonInput . getInt ( responseObject , KEY_TOTAL_COUNT ) ; } catch ( JSONException e ) { throw new RedmineFormatException ( e ) ; } if ( foundItems . size ( ) == 0 ) { break ; } offset += foundItems . size ( ) ; } while ( offset < totalObjectsFoundOnServer ) ; return result ; } | Returns an object list . |
15,297 | protected Completer discoverCompleter ( ) { log . debug ( "Discovering completer" ) ; CliProcessor cli = new CliProcessor ( ) ; cli . addBean ( this ) ; List < ArgumentDescriptor > argumentDescriptors = cli . getArgumentDescriptors ( ) ; Collections . sort ( argumentDescriptors ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Argument descriptors:" ) ; argumentDescriptors . forEach ( descriptor -> log . debug ( " {}" , descriptor ) ) ; } List < Completer > completers = new LinkedList < > ( ) ; argumentDescriptors . forEach ( descriptor -> { AccessibleObject accessible = descriptor . getSetter ( ) . getAccessible ( ) ; if ( accessible != null ) { Complete complete = accessible . getAnnotation ( Complete . class ) ; if ( complete != null ) { Completer completer = namedCompleters . get ( complete . value ( ) ) ; checkState ( completer != null , "Missing named completer: %s" , complete . value ( ) ) ; completers . add ( completer ) ; } } } ) ; if ( completers . isEmpty ( ) ) { return NullCompleter . INSTANCE ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Discovered completers:" ) ; completers . forEach ( completer -> { log . debug ( " {}" , completer ) ; } ) ; } completers . add ( NullCompleter . INSTANCE ) ; ArgumentCompleter completer = new ArgumentCompleter ( completers ) ; completer . setStrict ( true ) ; return completer ; } | Discover the completer for the command . |
15,298 | public static SimpleGraph < String , DefaultEdge > getSimpleGraphFromUser ( ) { Scanner sc = new Scanner ( System . in ) ; SimpleGraph < String , DefaultEdge > graph = new SimpleGraph < String , DefaultEdge > ( DefaultEdge . class ) ; int verticeAmount ; do { System . out . print ( "Enter the number of vertices (more than one): " ) ; verticeAmount = sc . nextInt ( ) ; } while ( verticeAmount <= 1 ) ; for ( int i = 1 ; i <= verticeAmount ; i ++ ) { System . out . print ( "Enter vertex name " + i + ": " ) ; String input = sc . next ( ) ; if ( graph . vertexSet ( ) . contains ( input ) ) { System . err . println ( "vertex with that name already exists" ) ; i -- ; } else { graph . addVertex ( input ) ; } } System . out . println ( "\nEnter edge (name => name)" ) ; String userWantsToContinue ; do { String e1 , e2 ; do { System . out . print ( "Edge from: " ) ; e1 = sc . next ( ) ; } while ( ! graph . vertexSet ( ) . contains ( e1 ) ) ; do { System . out . print ( "Edge to: " ) ; e2 = sc . next ( ) ; } while ( ! graph . vertexSet ( ) . contains ( e2 ) ) ; graph . addEdge ( e1 , e2 ) ; System . out . print ( "Add more edges? (y/n): " ) ; userWantsToContinue = sc . next ( ) ; } while ( userWantsToContinue . equals ( "y" ) || userWantsToContinue . equals ( "yes" ) || userWantsToContinue . equals ( "1" ) ) ; return graph ; } | Asks the user to input an graph |
15,299 | public void getTrimmedBounds ( Rectangle tbounds ) { tbounds . setBounds ( _tbounds . x , _tbounds . y , _mirage . getWidth ( ) , _mirage . getHeight ( ) ) ; } | Fills in the bounds of the trimmed image within the coordinate system defined by the complete virtual tile . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.