idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
152,900
public List < SourceCount > getSources ( ) { final SQLiteDatabase db = getDb ( ) ; List < SourceCount > ret = new ArrayList <> ( ) ; if ( db == null ) { return ret ; } Cursor cur = null ; try { cur = db . rawQuery ( "select " + COLUMN_PROVIDER + ",count(*) " + ",min(length(" + COLUMN_TILE + ")) " + ",max(length(" + COLUMN_TILE + ")) " + ",sum(length(" + COLUMN_TILE + ")) " + "from " + TABLE + " " + "group by " + COLUMN_PROVIDER , null ) ; while ( cur . moveToNext ( ) ) { final SourceCount c = new SourceCount ( ) ; c . source = cur . getString ( 0 ) ; c . rowCount = cur . getLong ( 1 ) ; c . sizeMin = cur . getLong ( 2 ) ; c . sizeMax = cur . getLong ( 3 ) ; c . sizeTotal = cur . getLong ( 4 ) ; c . sizeAvg = c . sizeTotal / c . rowCount ; ret . add ( c ) ; } } catch ( Exception e ) { catchException ( e ) ; } finally { if ( cur != null ) { cur . close ( ) ; } } return ret ; }
gets all the tiles sources that we have tiles for in the cache database and their counts
299
17
152,901
public boolean isCloseTo ( GeoPoint point , double tolerance , MapView mapView ) { return getCloseTo ( point , tolerance , mapView ) != null ; }
Detection is done is screen coordinates .
35
8
152,902
protected void setDefaultInfoWindowLocation ( ) { int s = mOriginalPoints . size ( ) ; if ( s > 0 ) mInfoWindowLocation = mOriginalPoints . get ( s / 2 ) ; else mInfoWindowLocation = new GeoPoint ( 0.0 , 0.0 ) ; }
Internal method used to ensure that the infowindow will have a default position in all cases so that the user can call showInfoWindow even if no tap occured before . Currently set the position on the middle point of the polyline .
63
49
152,903
public void onDetach ( ) { this . getOverlayManager ( ) . onDetach ( this ) ; mTileProvider . detach ( ) ; mOldZoomController . setVisible ( false ) ; if ( mZoomController != null ) { mZoomController . onDetach ( ) ; } //https://github.com/osmdroid/osmdroid/issues/390 if ( mTileRequestCompleteHandler instanceof SimpleInvalidationHandler ) { ( ( SimpleInvalidationHandler ) mTileRequestCompleteHandler ) . destroy ( ) ; } mTileRequestCompleteHandler = null ; if ( mProjection != null ) mProjection . detach ( ) ; mProjection = null ; mRepository . onDetach ( ) ; mListners . clear ( ) ; }
destroys the map view all references to listeners all overlays etc
168
14
152,904
private static boolean parallelSideEffect ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection ) { if ( pXA == pXB ) { return parallelSideEffectSameX ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) ; } if ( pXC == pXD ) { return parallelSideEffectSameX ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) ; } // formula like "y = k*x + b" final double k1 = ( pYB - pYA ) / ( pXB - pXA ) ; final double k2 = ( pYD - pYC ) / ( pXD - pXC ) ; if ( k1 != k2 ) { // not parallel return false ; } final double b1 = pYA - k1 * pXA ; final double b2 = pYC - k2 * pXC ; if ( b1 != b2 ) { // strictly parallel, no overlap return false ; } final double xi = middle ( pXA , pXB , pXC , pXD ) ; final double yi = middle ( pYA , pYB , pYC , pYD ) ; return check ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection , xi , yi ) ; }
When the segments are parallels and overlap the middle of the overlap is considered as the intersection
379
17
152,905
private static boolean check ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection , final double pXI , final double pYI ) { if ( pXI < Math . min ( pXA , pXB ) || pXI > Math . max ( pXA , pXB ) ) { return false ; } if ( pXI < Math . min ( pXC , pXD ) || pXI > Math . max ( pXC , pXD ) ) { return false ; } if ( pYI < Math . min ( pYA , pYB ) || pYI > Math . max ( pYA , pYB ) ) { return false ; } if ( pYI < Math . min ( pYC , pYD ) || pYI > Math . max ( pYC , pYD ) ) { return false ; } if ( pIntersection != null ) { pIntersection . x = Math . round ( pXI ) ; pIntersection . y = Math . round ( pYI ) ; } return true ; }
Checks if computed intersection is valid and sets output accordingly
272
11
152,906
private static boolean divisionByZeroSideEffect ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection ) { return divisionByZeroSideEffectX ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) || divisionByZeroSideEffectX ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) || divisionByZeroSideEffectY ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) || divisionByZeroSideEffectY ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) ; }
Main intersection formula works only without division by zero
228
9
152,907
@ Override public boolean onSingleTapConfirmed ( final MotionEvent event , final MapView mapView ) { return ( activateSelectedItems ( event , mapView , new ActiveItem ( ) { @ Override public boolean run ( final int index ) { final ItemizedIconOverlay < Item > that = ItemizedIconOverlay . this ; if ( that . mOnItemGestureListener == null ) { return false ; } return onSingleTapUpHelper ( index , that . mItemList . get ( index ) , mapView ) ; } } ) ) ? true : super . onSingleTapConfirmed ( event , mapView ) ; }
Each of these methods performs a item sensitive check . If the item is located its corresponding method is called . The result of the call is returned .
137
29
152,908
private boolean activateSelectedItems ( final MotionEvent event , final MapView mapView , final ActiveItem task ) { final int eventX = Math . round ( event . getX ( ) ) ; final int eventY = Math . round ( event . getY ( ) ) ; for ( int i = 0 ; i < this . mItemList . size ( ) ; ++ i ) { if ( isEventOnItem ( getItem ( i ) , eventX , eventY , mapView ) ) { if ( task . run ( i ) ) { return true ; } } } return false ; }
When a content sensitive action is performed the content item needs to be identified . This method does that and then performs the assigned task on that item .
125
29
152,909
public void garbageCollection ( ) { // number of tiles to remove from cache int toBeRemoved = Integer . MAX_VALUE ; // MAX_VALUE for stressed memory case final int size = mCachedTiles . size ( ) ; if ( ! mStressedMemory ) { toBeRemoved = size - mCapacity ; if ( toBeRemoved <= 0 ) { return ; } } refreshAdditionalLists ( ) ; if ( mAutoEnsureCapacity ) { final int target = mMapTileArea . size ( ) + mAdditionalMapTileList . size ( ) ; if ( ensureCapacity ( target ) ) { if ( ! mStressedMemory ) { toBeRemoved = size - mCapacity ; if ( toBeRemoved <= 0 ) { return ; } } } } populateSyncCachedTiles ( mGC ) ; for ( int i = 0 ; i < mGC . getSize ( ) ; i ++ ) { final long index = mGC . get ( i ) ; if ( shouldKeepTile ( index ) ) { continue ; } remove ( index ) ; if ( -- toBeRemoved == 0 ) { break ; } ; } }
Removes from the memory cache all the tiles that should no longer be there
242
15
152,910
private void populateSyncCachedTiles ( final MapTileList pList ) { synchronized ( mCachedTiles ) { pList . ensureCapacity ( mCachedTiles . size ( ) ) ; pList . clear ( ) ; for ( final long index : mCachedTiles . keySet ( ) ) { pList . put ( index ) ; } } }
Just a helper method in order to parse all indices without concurrency side effects
80
15
152,911
@ Override public boolean startOrientationProvider ( IOrientationConsumer orientationConsumer ) { mOrientationConsumer = orientationConsumer ; boolean result = false ; final Sensor sensor = mSensorManager . getDefaultSensor ( Sensor . TYPE_ORIENTATION ) ; if ( sensor != null ) { result = mSensorManager . registerListener ( this , sensor , SensorManager . SENSOR_DELAY_UI ) ; } return result ; }
Enable orientation updates from the internal compass sensor and show the compass .
93
13
152,912
@ Override public void draw ( Canvas canvas , Projection pj ) { if ( mIcon == null ) return ; if ( mPosition == null ) return ; pj . toPixels ( mPosition , mPositionPixels ) ; int width = mIcon . getIntrinsicWidth ( ) ; int height = mIcon . getIntrinsicHeight ( ) ; Rect rect = new Rect ( 0 , 0 , width , height ) ; rect . offset ( - ( int ) ( mAnchorU * width ) , - ( int ) ( mAnchorV * height ) ) ; mIcon . setBounds ( rect ) ; mIcon . setAlpha ( ( int ) ( mAlpha * 255 ) ) ; float rotationOnScreen = ( mFlat ? - mBearing : pj . getOrientation ( ) - mBearing ) ; drawAt ( canvas , mIcon , mPositionPixels . x , mPositionPixels . y , false , rotationOnScreen ) ; }
Draw the icon .
216
4
152,913
public double getX01FromLongitude ( double longitude , boolean wrapEnabled ) { longitude = wrapEnabled ? Clip ( longitude , getMinLongitude ( ) , getMaxLongitude ( ) ) : longitude ; final double result = getX01FromLongitude ( longitude ) ; return wrapEnabled ? Clip ( result , 0 , 1 ) : result ; }
Converts a longitude to its X01 value id est a double between 0 and 1 for the whole longitude range
78
24
152,914
public double getY01FromLatitude ( double latitude , boolean wrapEnabled ) { latitude = wrapEnabled ? Clip ( latitude , getMinLatitude ( ) , getMaxLatitude ( ) ) : latitude ; final double result = getY01FromLatitude ( latitude ) ; return wrapEnabled ? Clip ( result , 0 , 1 ) : result ; }
Converts a latitude to its Y01 value id est a double between 0 and 1 for the whole latitude range
73
22
152,915
public void open ( Object object , GeoPoint position , int offsetX , int offsetY ) { close ( ) ; //if it was already opened mRelatedObject = object ; mPosition = position ; mOffsetX = offsetX ; mOffsetY = offsetY ; onOpen ( object ) ; MapView . LayoutParams lp = new MapView . LayoutParams ( MapView . LayoutParams . WRAP_CONTENT , MapView . LayoutParams . WRAP_CONTENT , mPosition , MapView . LayoutParams . BOTTOM_CENTER , mOffsetX , mOffsetY ) ; if ( mMapView != null && mView != null ) { mMapView . addView ( mView , lp ) ; mIsVisible = true ; } else { Log . w ( IMapView . LOGTAG , "Error trapped, InfoWindow.open mMapView: " + ( mMapView == null ? "null" : "ok" ) + " mView: " + ( mView == null ? "null" : "ok" ) ) ; } }
open the InfoWindow at the specified GeoPosition + offset . If it was already opened close it before reopening .
233
23
152,916
public void close ( ) { if ( mIsVisible ) { mIsVisible = false ; ( ( ViewGroup ) mView . getParent ( ) ) . removeView ( mView ) ; onClose ( ) ; } }
hides the info window which triggers another render of the map
49
12
152,917
public void onDetach ( ) { close ( ) ; if ( mView != null ) mView . setTag ( null ) ; mView = null ; mMapView = null ; if ( Configuration . getInstance ( ) . isDebugMode ( ) ) Log . d ( IMapView . LOGTAG , "Marked detached" ) ; }
this destroys the window and all references to views
73
9
152,918
public static void closeAllInfoWindowsOn ( MapView mapView ) { ArrayList < InfoWindow > opened = getOpenedInfoWindowsOn ( mapView ) ; for ( InfoWindow infoWindow : opened ) { infoWindow . close ( ) ; } }
close all InfoWindows currently opened on this MapView
53
10
152,919
public static ArrayList < InfoWindow > getOpenedInfoWindowsOn ( MapView mapView ) { int count = mapView . getChildCount ( ) ; ArrayList < InfoWindow > opened = new ArrayList < InfoWindow > ( count ) ; for ( int i = 0 ; i < count ; i ++ ) { final View child = mapView . getChildAt ( i ) ; Object tag = child . getTag ( ) ; if ( tag != null && tag instanceof InfoWindow ) { InfoWindow infoWindow = ( InfoWindow ) tag ; opened . add ( infoWindow ) ; } } return opened ; }
return all InfoWindows currently opened on this MapView
129
10
152,920
private MilestoneManager getHalfKilometerManager ( ) { final Path arrowPath = new Path ( ) ; // a simple arrow towards the right arrowPath . moveTo ( - 5 , - 5 ) ; arrowPath . lineTo ( 5 , 0 ) ; arrowPath . lineTo ( - 5 , 5 ) ; arrowPath . close ( ) ; final Paint backgroundPaint = getFillPaint ( COLOR_BACKGROUND ) ; return new MilestoneManager ( // display an arrow at 500m every 1km new MilestoneMeterDistanceLister ( 500 ) , new MilestonePathDisplayer ( 0 , true , arrowPath , backgroundPaint ) { @ Override protected void draw ( final Canvas pCanvas , final Object pParameter ) { final int halfKilometers = ( int ) Math . round ( ( ( double ) pParameter / 500 ) ) ; if ( halfKilometers % 2 == 0 ) { return ; } super . draw ( pCanvas , pParameter ) ; } } ) ; }
Half - kilometer milestones
215
5
152,921
public Point toWgs84 ( Point point ) { if ( projection != null ) { point = toWgs84 . transform ( point ) ; } return point ; }
Transform a projection point to WGS84
35
8
152,922
public Point toProjection ( Point point ) { if ( projection != null ) { point = fromWgs84 . transform ( point ) ; } return point ; }
Transform a WGS84 point to the projection
34
9
152,923
public static Polyline addPolylineToMap ( MapView map , Polyline polyline ) { if ( polyline . getInfoWindow ( ) == null ) polyline . setInfoWindow ( new BasicInfoWindow ( R . layout . bonuspack_bubble , map ) ) ; map . getOverlayManager ( ) . add ( polyline ) ; return polyline ; }
Add a Polyline to the map
79
7
152,924
public synchronized void close ( ) throws IOException { if ( journalWriter == null ) { return ; // Already closed. } for ( Entry entry : new ArrayList < Entry > ( lruEntries . values ( ) ) ) { if ( entry . currentEditor != null ) { entry . currentEditor . abort ( ) ; } } trimToSize ( ) ; journalWriter . close ( ) ; journalWriter = null ; }
Closes this cache . Stored values will remain on the filesystem .
88
14
152,925
protected boolean isSOFnMarker ( int marker ) { if ( marker <= 0xC3 && marker >= 0xC0 ) { return true ; } if ( marker <= 0xCB && marker >= 0xC5 ) { return true ; } if ( marker <= 0xCF && marker >= 0xCD ) { return true ; } return false ; }
can opt using array
77
4
152,926
protected void writeFull ( ) { byte [ ] imageData = rawImage . getData ( ) ; int numOfComponents = frameHeader . getNf ( ) ; int [ ] pixes = new int [ numOfComponents * DCTSIZE2 ] ; int blockIndex = 0 ; int startCoordinate = 0 , scanlineStride = numOfComponents * rawImage . getWidth ( ) , row = 0 ; x = 0 ; y = 0 ; for ( int m = 0 ; m < MCUsPerColumn * MCUsPerRow ; m ++ ) { blockIndex = 0 ; // one MCU for ( int v = 0 ; v < maxVSampleFactor ; v ++ ) { for ( int h = 0 ; h < maxHSampleFactor ; h ++ ) { row = y + 1 ; startCoordinate = ( y * rawImage . getWidth ( ) + x ) * numOfComponents ; // one block for ( int k = blockIndex * DCTSIZE2 , i = 0 ; k < blockIndex * DCTSIZE2 + DCTSIZE2 ; k ++ ) { pixes [ i ++ ] = allMCUDatas [ 0 ] [ m ] [ k ] ; if ( numOfComponents > 1 ) { pixes [ i ++ ] = allMCUDatas [ 1 ] [ m ] [ k ] ; pixes [ i ++ ] = allMCUDatas [ 2 ] [ m ] [ k ] ; } if ( numOfComponents > 3 ) { pixes [ i ++ ] = allMCUDatas [ 3 ] [ m ] [ k ] ; } x ++ ; if ( x % 8 == 0 ) { y ++ ; x -= 8 ; } } colorConvertor . convertBlock ( pixes , 0 , imageData , numOfComponents , startCoordinate , row , scanlineStride ) ; blockIndex ++ ; x += 8 ; y -= 8 ; } x -= maxHSampleFactor * 8 ; y += 8 ; } x += maxHSampleFactor * 8 ; y -= maxVSampleFactor * 8 ; if ( x >= rawImage . getWidth ( ) ) { x = 0 ; y += maxVSampleFactor * 8 ; } } }
Used by progressive mode
479
4
152,927
public int getValueId ( Clusterable c ) { currentItems ++ ; /* * if(isLeafNode()) { return id; } */ int index = TreeUtils . findNearestNodeIndex ( subNodes , c ) ; if ( index >= 0 ) { KMeansTreeNode node = subNodes . get ( index ) ; return node . getValueId ( c ) ; } return id ; }
Adds a clusterable to the current vocab tree for word creation
88
13
152,928
public static Node cloneNode ( Node node ) { if ( node == null ) { return null ; } IIOMetadataNode newNode = new IIOMetadataNode ( node . getNodeName ( ) ) ; //clone user object if ( node instanceof IIOMetadataNode ) { IIOMetadataNode iioNode = ( IIOMetadataNode ) node ; Object obj = iioNode . getUserObject ( ) ; if ( obj instanceof byte [ ] ) { byte [ ] copyBytes = ( ( byte [ ] ) obj ) . clone ( ) ; newNode . setUserObject ( copyBytes ) ; } } //clone attributes NamedNodeMap attrs = node . getAttributes ( ) ; for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { Node attr = attrs . item ( i ) ; newNode . setAttribute ( attr . getNodeName ( ) , attr . getNodeValue ( ) ) ; } //clone children NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node child = children . item ( i ) ; newNode . appendChild ( cloneNode ( child ) ) ; } return newNode ; }
Currently only use by GIFStreamMetadata and GIFImageMetadata
274
13
152,929
protected Cluster [ ] calculateInitialClusters ( List < ? extends Clusterable > values , int numClusters ) { Cluster [ ] clusters = new Cluster [ numClusters ] ; //choose centers and create the initial clusters Random random = new Random ( 1 ) ; Set < Integer > clusterCenters = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < numClusters ; i ++ ) { int index = random . nextInt ( values . size ( ) ) ; while ( clusterCenters . contains ( index ) ) { index = random . nextInt ( values . size ( ) ) ; } clusterCenters . add ( index ) ; clusters [ i ] = new Cluster ( values . get ( index ) . getLocation ( ) , i ) ; } return clusters ; }
Calculates the initial clusters randomly this could be replaced with a better algorithm
168
15
152,930
public float [ ] getClusterMean ( ) { float [ ] normedCurrentLocation = new float [ mCurrentMeanLocation . length ] ; for ( int i = 0 ; i < mCurrentMeanLocation . length ; i ++ ) { normedCurrentLocation [ i ] = mCurrentMeanLocation [ i ] / ( ( float ) mClusterItems . size ( ) ) ; } return normedCurrentLocation ; }
Get the current mean value of the cluster s items
92
10
152,931
private void setItem ( int index , Timepoint time ) { time = roundToValidTime ( time , index ) ; mCurrentTime = time ; reselectSelector ( time , false , index ) ; }
Set either the hour the minute or the second . Will set the internal value and set the selection .
44
20
152,932
private boolean isHourInnerCircle ( int hourOfDay ) { // We'll have the 00 hours on the outside circle. boolean isMorning = hourOfDay <= 12 && hourOfDay != 0 ; // In the version 2 layout the circles are swapped if ( mController . getVersion ( ) != TimePickerDialog . Version . VERSION_1 ) isMorning = ! isMorning ; return mIs24HourMode && isMorning ; }
Check if a given hour appears in the outer circle or the inner circle
93
14
152,933
private int getCurrentlyShowingValue ( ) { int currentIndex = getCurrentItemShowing ( ) ; switch ( currentIndex ) { case HOUR_INDEX : return mCurrentTime . getHour ( ) ; case MINUTE_INDEX : return mCurrentTime . getMinute ( ) ; case SECOND_INDEX : return mCurrentTime . getSecond ( ) ; default : return - 1 ; } }
If the hours are showing return the current hour . If the minutes are showing return the current minute .
88
20
152,934
private Timepoint roundToValidTime ( Timepoint newSelection , int currentItemShowing ) { switch ( currentItemShowing ) { case HOUR_INDEX : return mController . roundToNearest ( newSelection , null ) ; case MINUTE_INDEX : return mController . roundToNearest ( newSelection , Timepoint . TYPE . HOUR ) ; default : return mController . roundToNearest ( newSelection , Timepoint . TYPE . MINUTE ) ; } }
Snap the input to a selectable value
107
8
152,935
public boolean trySettingInputEnabled ( boolean inputEnabled ) { if ( mDoingTouch && ! inputEnabled ) { // If we're trying to disable input, but we're in the middle of a touch event, // we'll allow the touch event to continue before disabling input. return false ; } mInputEnabled = inputEnabled ; mGrayBox . setVisibility ( inputEnabled ? View . INVISIBLE : View . VISIBLE ) ; return true ; }
Set touch input as enabled or disabled for use with keyboard mode .
95
13
152,936
public static ObjectAnimator getPulseAnimator ( View labelToAnimate , float decreaseRatio , float increaseRatio ) { Keyframe k0 = Keyframe . ofFloat ( 0f , 1f ) ; Keyframe k1 = Keyframe . ofFloat ( 0.275f , decreaseRatio ) ; Keyframe k2 = Keyframe . ofFloat ( 0.69f , increaseRatio ) ; Keyframe k3 = Keyframe . ofFloat ( 1f , 1f ) ; PropertyValuesHolder scaleX = PropertyValuesHolder . ofKeyframe ( "scaleX" , k0 , k1 , k2 , k3 ) ; PropertyValuesHolder scaleY = PropertyValuesHolder . ofKeyframe ( "scaleY" , k0 , k1 , k2 , k3 ) ; ObjectAnimator pulseAnimator = ObjectAnimator . ofPropertyValuesHolder ( labelToAnimate , scaleX , scaleY ) ; pulseAnimator . setDuration ( PULSE_ANIMATOR_DURATION ) ; return pulseAnimator ; }
Render an animator to pulsate a view in place .
229
12
152,937
public static Calendar trimToMidnight ( Calendar calendar ) { calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; return calendar ; }
Trims off all time information effectively setting it to midnight Makes it easier to compare at just the day level
70
21
152,938
@ SuppressWarnings ( "unused" ) public static DatePickerDialog newInstance ( OnDateSetListener callback ) { Calendar now = Calendar . getInstance ( ) ; return DatePickerDialog . newInstance ( callback , now ) ; }
Create a new DatePickerDialog instance initialised to the current system date .
53
16
152,939
@ SuppressWarnings ( "unused" ) public void setHighlightedDays ( Calendar [ ] highlightedDays ) { for ( Calendar highlightedDay : highlightedDays ) { this . highlightedDays . add ( Utils . trimToMidnight ( ( Calendar ) highlightedDay . clone ( ) ) ) ; } if ( mDayPickerView != null ) mDayPickerView . onChange ( ) ; }
Sets an array of dates which should be highlighted when the picker is drawn
87
16
152,940
@ SuppressWarnings ( "DeprecatedIsStillUsed" ) @ Deprecated public void setTimeZone ( TimeZone timeZone ) { mTimezone = timeZone ; mCalendar . setTimeZone ( timeZone ) ; YEAR_FORMAT . setTimeZone ( timeZone ) ; MONTH_FORMAT . setTimeZone ( timeZone ) ; DAY_FORMAT . setTimeZone ( timeZone ) ; }
Set which timezone the picker should use
90
9
152,941
public void setLocale ( Locale locale ) { mLocale = locale ; mWeekStart = Calendar . getInstance ( mTimezone , mLocale ) . getFirstDayOfWeek ( ) ; YEAR_FORMAT = new SimpleDateFormat ( "yyyy" , locale ) ; MONTH_FORMAT = new SimpleDateFormat ( "MMM" , locale ) ; DAY_FORMAT = new SimpleDateFormat ( "dd" , locale ) ; }
Set a custom locale to be used when generating various strings in the picker
98
15
152,942
public void start ( ) { if ( hasVibratePermission ( mContext ) ) { mVibrator = ( Vibrator ) mContext . getSystemService ( Service . VIBRATOR_SERVICE ) ; } // Setup a listener for changes in haptic feedback settings mIsGloballyEnabled = checkGlobalSetting ( mContext ) ; Uri uri = Settings . System . getUriFor ( Settings . System . HAPTIC_FEEDBACK_ENABLED ) ; mContext . getContentResolver ( ) . registerContentObserver ( uri , false , mContentObserver ) ; }
Call to setup the controller .
133
6
152,943
private boolean hasVibratePermission ( Context context ) { PackageManager pm = context . getPackageManager ( ) ; int hasPerm = pm . checkPermission ( android . Manifest . permission . VIBRATE , context . getPackageName ( ) ) ; return hasPerm == PackageManager . PERMISSION_GRANTED ; }
Method to verify that vibrate permission has been granted .
73
11
152,944
@ SuppressWarnings ( "SameParameterValue" ) public static TimePickerDialog newInstance ( OnTimeSetListener callback , int hourOfDay , int minute , int second , boolean is24HourMode ) { TimePickerDialog ret = new TimePickerDialog ( ) ; ret . initialize ( callback , hourOfDay , minute , second , is24HourMode ) ; return ret ; }
Create a new TimePickerDialog instance with a given intial selection
84
14
152,945
public static TimePickerDialog newInstance ( OnTimeSetListener callback , int hourOfDay , int minute , boolean is24HourMode ) { return TimePickerDialog . newInstance ( callback , hourOfDay , minute , 0 , is24HourMode ) ; }
Create a new TimePickerDialog instance with a given initial selection
56
13
152,946
@ SuppressWarnings ( { "unused" , "SameParameterValue" } ) public static TimePickerDialog newInstance ( OnTimeSetListener callback , boolean is24HourMode ) { Calendar now = Calendar . getInstance ( ) ; return TimePickerDialog . newInstance ( callback , now . get ( Calendar . HOUR_OF_DAY ) , now . get ( Calendar . MINUTE ) , is24HourMode ) ; }
Create a new TimePickerDialog instance initialized to the current system time
94
14
152,947
private boolean processKeyUp ( int keyCode ) { if ( keyCode == KeyEvent . KEYCODE_TAB ) { if ( mInKbMode ) { if ( isTypedTimeFullyLegal ( ) ) { finishKbMode ( true ) ; } return true ; } } else if ( keyCode == KeyEvent . KEYCODE_ENTER ) { if ( mInKbMode ) { if ( ! isTypedTimeFullyLegal ( ) ) { return true ; } finishKbMode ( false ) ; } if ( mCallback != null ) { mCallback . onTimeSet ( this , mTimePicker . getHours ( ) , mTimePicker . getMinutes ( ) , mTimePicker . getSeconds ( ) ) ; } dismiss ( ) ; return true ; } else if ( keyCode == KeyEvent . KEYCODE_DEL ) { if ( mInKbMode ) { if ( ! mTypedTimes . isEmpty ( ) ) { int deleted = deleteLastTypedKey ( ) ; String deletedKeyStr ; if ( deleted == getAmOrPmKeyCode ( AM ) ) { deletedKeyStr = mAmText ; } else if ( deleted == getAmOrPmKeyCode ( PM ) ) { deletedKeyStr = mPmText ; } else { deletedKeyStr = String . format ( mLocale , "%d" , getValFromKeyCode ( deleted ) ) ; } Utils . tryAccessibilityAnnounce ( mTimePicker , String . format ( mDeletedKeyFormat , deletedKeyStr ) ) ; updateDisplay ( true ) ; } } } else if ( keyCode == KeyEvent . KEYCODE_0 || keyCode == KeyEvent . KEYCODE_1 || keyCode == KeyEvent . KEYCODE_2 || keyCode == KeyEvent . KEYCODE_3 || keyCode == KeyEvent . KEYCODE_4 || keyCode == KeyEvent . KEYCODE_5 || keyCode == KeyEvent . KEYCODE_6 || keyCode == KeyEvent . KEYCODE_7 || keyCode == KeyEvent . KEYCODE_8 || keyCode == KeyEvent . KEYCODE_9 || ( ! mIs24HourMode && ( keyCode == getAmOrPmKeyCode ( AM ) || keyCode == getAmOrPmKeyCode ( PM ) ) ) ) { if ( ! mInKbMode ) { if ( mTimePicker == null ) { // Something's wrong, because time picker should definitely not be null. Log . e ( TAG , "Unable to initiate keyboard mode, TimePicker was null." ) ; return true ; } mTypedTimes . clear ( ) ; tryStartingKbMode ( keyCode ) ; return true ; } // We're already in keyboard mode. if ( addKeyIfLegal ( keyCode ) ) { updateDisplay ( false ) ; } return true ; } return false ; }
For keyboard mode processes key events .
633
7
152,948
public void setMonthParams ( int selectedDay , int year , int month , int weekStart ) { if ( month == - 1 && year == - 1 ) { throw new InvalidParameterException ( "You must specify month and year for this view" ) ; } mSelectedDay = selectedDay ; // Allocate space for caching the day numbers and focus values mMonth = month ; mYear = year ; // Figure out what day today is //final Time today = new Time(Time.getCurrentTimezone()); //today.setToNow(); final Calendar today = Calendar . getInstance ( mController . getTimeZone ( ) , mController . getLocale ( ) ) ; mHasToday = false ; mToday = - 1 ; mCalendar . set ( Calendar . MONTH , mMonth ) ; mCalendar . set ( Calendar . YEAR , mYear ) ; mCalendar . set ( Calendar . DAY_OF_MONTH , 1 ) ; mDayOfWeekStart = mCalendar . get ( Calendar . DAY_OF_WEEK ) ; if ( weekStart != - 1 ) { mWeekStart = weekStart ; } else { mWeekStart = mCalendar . getFirstDayOfWeek ( ) ; } mNumCells = mCalendar . getActualMaximum ( Calendar . DAY_OF_MONTH ) ; for ( int i = 0 ; i < mNumCells ; i ++ ) { final int day = i + 1 ; if ( sameDay ( day , today ) ) { mHasToday = true ; mToday = day ; } } mNumRows = calculateNumRows ( ) ; // Invalidate cached accessibility information. mTouchHelper . invalidateRoot ( ) ; }
Sets all the parameters for displaying this week . The only required parameter is the week number . Other parameters have a default value and will only update if a new value is included except for focus month which will always default to no focus month if no value is passed in .
363
54
152,949
public int getDayFromLocation ( float x , float y ) { final int day = getInternalDayFromLocation ( x , y ) ; if ( day < 1 || day > mNumCells ) { return - 1 ; } return day ; }
Calculates the day that the given x position is in accounting for week number . Returns the day or - 1 if the position wasn t in a day .
52
32
152,950
protected int getInternalDayFromLocation ( float x , float y ) { int dayStart = mEdgePadding ; if ( x < dayStart || x > mWidth - mEdgePadding ) { return - 1 ; } // Selection is (x - start) / (pixels/day) == (x -s) * day / pixels int row = ( int ) ( y - getMonthHeaderSize ( ) ) / mRowHeight ; int column = ( int ) ( ( x - dayStart ) * mNumDays / ( mWidth - dayStart - mEdgePadding ) ) ; int day = column - findDayOffset ( ) + 1 ; day += row * mNumDays ; return day ; }
Calculates the day that the given x position is in accounting for week number .
150
17
152,951
private String getWeekDayLabel ( Calendar day ) { Locale locale = mController . getLocale ( ) ; // Localised short version of the string is not available on API < 18 if ( Build . VERSION . SDK_INT < 18 ) { String dayName = new SimpleDateFormat ( "E" , locale ) . format ( day . getTime ( ) ) ; String dayLabel = dayName . toUpperCase ( locale ) . substring ( 0 , 1 ) ; // Chinese labels should be fetched right to left if ( locale . equals ( Locale . CHINA ) || locale . equals ( Locale . CHINESE ) || locale . equals ( Locale . SIMPLIFIED_CHINESE ) || locale . equals ( Locale . TRADITIONAL_CHINESE ) ) { int len = dayName . length ( ) ; dayLabel = dayName . substring ( len - 1 , len ) ; } // Most hebrew labels should select the second to last character if ( locale . getLanguage ( ) . equals ( "he" ) || locale . getLanguage ( ) . equals ( "iw" ) ) { if ( mDayLabelCalendar . get ( Calendar . DAY_OF_WEEK ) != Calendar . SATURDAY ) { int len = dayName . length ( ) ; dayLabel = dayName . substring ( len - 2 , len - 1 ) ; } else { // I know this is duplication, but it makes the code easier to grok by // having all hebrew code in the same block dayLabel = dayName . toUpperCase ( locale ) . substring ( 0 , 1 ) ; } } // Catalan labels should be two digits in lowercase if ( locale . getLanguage ( ) . equals ( "ca" ) ) dayLabel = dayName . toLowerCase ( ) . substring ( 0 , 2 ) ; // Correct single character label in Spanish is X if ( locale . getLanguage ( ) . equals ( "es" ) && day . get ( Calendar . DAY_OF_WEEK ) == Calendar . WEDNESDAY ) dayLabel = "X" ; return dayLabel ; } // Getting the short label is a one liner on API >= 18 if ( weekDayLabelFormatter == null ) { weekDayLabelFormatter = new SimpleDateFormat ( "EEEEE" , locale ) ; } return weekDayLabelFormatter . format ( day . getTime ( ) ) ; }
Return a 1 or 2 letter String for use as a weekday label
516
13
152,952
private void calculateGridSizes ( float numbersRadius , float xCenter , float yCenter , float textSize , float [ ] textGridHeights , float [ ] textGridWidths ) { /* * The numbers need to be drawn in a 7x7 grid, representing the points on the Unit Circle. */ float offset1 = numbersRadius ; // cos(30) = a / r => r * cos(30) = a => r * √3/2 = a float offset2 = numbersRadius * ( ( float ) Math . sqrt ( 3 ) ) / 2f ; // sin(30) = o / r => r * sin(30) = o => r / 2 = a float offset3 = numbersRadius / 2f ; mPaint . setTextSize ( textSize ) ; mSelectedPaint . setTextSize ( textSize ) ; mInactivePaint . setTextSize ( textSize ) ; // We'll need yTextBase to be slightly lower to account for the text's baseline. yCenter -= ( mPaint . descent ( ) + mPaint . ascent ( ) ) / 2 ; textGridHeights [ 0 ] = yCenter - offset1 ; textGridWidths [ 0 ] = xCenter - offset1 ; textGridHeights [ 1 ] = yCenter - offset2 ; textGridWidths [ 1 ] = xCenter - offset2 ; textGridHeights [ 2 ] = yCenter - offset3 ; textGridWidths [ 2 ] = xCenter - offset3 ; textGridHeights [ 3 ] = yCenter ; textGridWidths [ 3 ] = xCenter ; textGridHeights [ 4 ] = yCenter + offset3 ; textGridWidths [ 4 ] = xCenter + offset3 ; textGridHeights [ 5 ] = yCenter + offset2 ; textGridWidths [ 5 ] = xCenter + offset2 ; textGridHeights [ 6 ] = yCenter + offset1 ; textGridWidths [ 6 ] = xCenter + offset1 ; }
Using the trigonometric Unit Circle calculate the positions that the text will need to be drawn at based on the specified circle radius . Place the values in the textGridHeights and textGridWidths parameters .
433
42
152,953
private void drawTexts ( Canvas canvas , float textSize , Typeface typeface , String [ ] texts , float [ ] textGridWidths , float [ ] textGridHeights ) { mPaint . setTextSize ( textSize ) ; mPaint . setTypeface ( typeface ) ; Paint [ ] textPaints = assignTextColors ( texts ) ; canvas . drawText ( texts [ 0 ] , textGridWidths [ 3 ] , textGridHeights [ 0 ] , textPaints [ 0 ] ) ; canvas . drawText ( texts [ 1 ] , textGridWidths [ 4 ] , textGridHeights [ 1 ] , textPaints [ 1 ] ) ; canvas . drawText ( texts [ 2 ] , textGridWidths [ 5 ] , textGridHeights [ 2 ] , textPaints [ 2 ] ) ; canvas . drawText ( texts [ 3 ] , textGridWidths [ 6 ] , textGridHeights [ 3 ] , textPaints [ 3 ] ) ; canvas . drawText ( texts [ 4 ] , textGridWidths [ 5 ] , textGridHeights [ 4 ] , textPaints [ 4 ] ) ; canvas . drawText ( texts [ 5 ] , textGridWidths [ 4 ] , textGridHeights [ 5 ] , textPaints [ 5 ] ) ; canvas . drawText ( texts [ 6 ] , textGridWidths [ 3 ] , textGridHeights [ 6 ] , textPaints [ 6 ] ) ; canvas . drawText ( texts [ 7 ] , textGridWidths [ 2 ] , textGridHeights [ 5 ] , textPaints [ 7 ] ) ; canvas . drawText ( texts [ 8 ] , textGridWidths [ 1 ] , textGridHeights [ 4 ] , textPaints [ 8 ] ) ; canvas . drawText ( texts [ 9 ] , textGridWidths [ 0 ] , textGridHeights [ 3 ] , textPaints [ 9 ] ) ; canvas . drawText ( texts [ 10 ] , textGridWidths [ 1 ] , textGridHeights [ 2 ] , textPaints [ 10 ] ) ; canvas . drawText ( texts [ 11 ] , textGridWidths [ 2 ] , textGridHeights [ 1 ] , textPaints [ 11 ] ) ; }
Draw the 12 text values at the positions specified by the textGrid parameters .
489
15
152,954
public void setSelection ( int selectionDegrees , boolean isInnerCircle , boolean forceDrawDot ) { mSelectionDegrees = selectionDegrees ; mSelectionRadians = selectionDegrees * Math . PI / 180 ; mForceDrawDot = forceDrawDot ; if ( mHasInnerCircle ) { if ( isInnerCircle ) { mNumbersRadiusMultiplier = mInnerNumbersRadiusMultiplier ; } else { mNumbersRadiusMultiplier = mOuterNumbersRadiusMultiplier ; } } }
Set the selection .
127
4
152,955
protected void setUpRecyclerView ( DatePickerDialog . ScrollOrientation scrollOrientation ) { setVerticalScrollBarEnabled ( false ) ; setFadingEdgeLength ( 0 ) ; int gravity = scrollOrientation == DatePickerDialog . ScrollOrientation . VERTICAL ? Gravity . TOP : Gravity . START ; GravitySnapHelper helper = new GravitySnapHelper ( gravity , position -> { // Leverage the fact that the SnapHelper figures out which position is shown and // pass this on to our PageListener after the snap has happened if ( pageListener != null ) pageListener . onPageChanged ( position ) ; } ) ; helper . attachToRecyclerView ( this ) ; }
Sets all the required fields for the list view . Override this method to set a different list view behavior .
150
23
152,956
@ Override public boolean dispatchPopulateAccessibilityEvent ( AccessibilityEvent event ) { if ( event . getEventType ( ) == AccessibilityEvent . TYPE_WINDOW_STATE_CHANGED ) { // Clear the event's current text so that only the current date will be spoken. event . getText ( ) . clear ( ) ; int flags = DateUtils . FORMAT_SHOW_DATE | DateUtils . FORMAT_SHOW_YEAR | DateUtils . FORMAT_SHOW_WEEKDAY ; String dateString = DateUtils . formatDateTime ( getContext ( ) , mDateMillis , flags ) ; event . getText ( ) . add ( dateString ) ; return true ; } return super . dispatchPopulateAccessibilityEvent ( event ) ; }
Announce the currently - selected date when launched .
171
10
152,957
public int getIsTouchingAmOrPm ( float xCoord , float yCoord ) { if ( ! mDrawValuesReady ) { return - 1 ; } int squaredYDistance = ( int ) ( ( yCoord - mAmPmYCenter ) * ( yCoord - mAmPmYCenter ) ) ; int distanceToAmCenter = ( int ) Math . sqrt ( ( xCoord - mAmXCenter ) * ( xCoord - mAmXCenter ) + squaredYDistance ) ; if ( distanceToAmCenter <= mAmPmCircleRadius && ! mAmDisabled ) { return AM ; } int distanceToPmCenter = ( int ) Math . sqrt ( ( xCoord - mPmXCenter ) * ( xCoord - mPmXCenter ) + squaredYDistance ) ; if ( distanceToPmCenter <= mAmPmCircleRadius && ! mPmDisabled ) { return PM ; } // Neither was close enough. return - 1 ; }
Calculate whether the coordinates are touching the AM or PM circle .
224
14
152,958
public void setExcludeFilter ( File filterFile ) { if ( filterFile != null && filterFile . length ( ) > 0 ) { excludeFile = filterFile ; } else { if ( filterFile != null ) { log ( "Warning: exclude filter file " + filterFile + ( filterFile . exists ( ) ? " is empty" : " does not exist" ) ) ; } excludeFile = null ; } }
Set the exclude filter file
88
5
152,959
public void setIncludeFilter ( File filterFile ) { if ( filterFile != null && filterFile . length ( ) > 0 ) { includeFile = filterFile ; } else { if ( filterFile != null ) { log ( "Warning: include filter file " + filterFile + ( filterFile . exists ( ) ? " is empty" : " does not exist" ) ) ; } includeFile = null ; } }
Set the include filter file
88
5
152,960
public void setBaselineBugs ( File baselineBugs ) { if ( baselineBugs != null && baselineBugs . length ( ) > 0 ) { this . baselineBugs = baselineBugs ; } else { if ( baselineBugs != null ) { log ( "Warning: baseline bugs file " + baselineBugs + ( baselineBugs . exists ( ) ? " is empty" : " does not exist" ) ) ; } this . baselineBugs = null ; } }
Set the baseline bugs file
102
5
152,961
public void setAuxClasspath ( Path src ) { boolean nonEmpty = false ; String [ ] elementList = src . list ( ) ; for ( String anElementList : elementList ) { if ( ! "" . equals ( anElementList ) ) { nonEmpty = true ; break ; } } if ( nonEmpty ) { if ( auxClasspath == null ) { auxClasspath = src ; } else { auxClasspath . append ( src ) ; } } }
the auxclasspath to use .
99
7
152,962
public void setAuxClasspathRef ( Reference r ) { Path path = createAuxClasspath ( ) ; path . setRefid ( r ) ; path . toString ( ) ; // Evaluated for its side-effects (throwing a // BuildException) }
Adds a reference to a sourcepath defined elsewhere .
57
10
152,963
public void setAuxAnalyzepath ( Path src ) { boolean nonEmpty = false ; String [ ] elementList = src . list ( ) ; for ( String anElementList : elementList ) { if ( ! "" . equals ( anElementList ) ) { nonEmpty = true ; break ; } } if ( nonEmpty ) { if ( auxAnalyzepath == null ) { auxAnalyzepath = src ; } else { auxAnalyzepath . append ( src ) ; } } }
the auxAnalyzepath to use .
107
9
152,964
public void setSourcePath ( Path src ) { if ( sourcePath == null ) { sourcePath = src ; } else { sourcePath . append ( src ) ; } }
the sourcepath to use .
36
6
152,965
public void setExcludePath ( Path src ) { if ( excludePath == null ) { excludePath = src ; } else { excludePath . append ( src ) ; } }
the excludepath to use .
37
8
152,966
public void setIncludePath ( Path src ) { if ( includePath == null ) { includePath = src ; } else { includePath . append ( src ) ; } }
the includepath to use .
37
7
152,967
@ Override protected void checkParameters ( ) { super . checkParameters ( ) ; if ( projectFile == null && classLocations . size ( ) == 0 && filesets . size ( ) == 0 && dirsets . size ( ) == 0 && auxAnalyzepath == null ) { throw new BuildException ( "either projectfile, <class/>, <fileset/> or <auxAnalyzepath/> child " + "elements must be defined for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( outputFormat != null && ! ( "xml" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "xml:withMessages" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "html" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "text" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "xdocs" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "emacs" . equalsIgnoreCase ( outputFormat . trim ( ) ) ) ) { throw new BuildException ( "output attribute must be either " + "'text', 'xml', 'html', 'xdocs' or 'emacs' for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( reportLevel != null && ! ( "experimental" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "low" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "medium" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "high" . equalsIgnoreCase ( reportLevel . trim ( ) ) ) ) { throw new BuildException ( "reportlevel attribute must be either " + "'experimental' or 'low' or 'medium' or 'high' for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } // FindBugs allows both, so there's no apparent reason for this check // if ( excludeFile != null && includeFile != null ) { // throw new BuildException("only one of excludeFile and includeFile " + // " attributes may be used in task <" + getTaskName() + "/>", // getLocation()); // } List < String > efforts = Arrays . asList ( "min" , "less" , "default" , "more" , "max" ) ; if ( effort != null && ! efforts . contains ( effort ) ) { throw new BuildException ( "effort attribute must be one of " + efforts ) ; } }
Check that all required attributes have been set
559
8
152,968
static boolean isEclipsePluginDisabled ( String pluginId , Map < URI , Plugin > allPlugins ) { for ( Plugin plugin : allPlugins . values ( ) ) { if ( pluginId . equals ( plugin . getPluginId ( ) ) ) { return false ; } } return true ; }
Eclipse plugin can be disabled ONLY by user so it must NOT be in the list of loaded plugins
64
20
152,969
public static < Fact , AnalysisType extends BasicAbstractDataflowAnalysis < Fact > > void printCFG ( Dataflow < Fact , AnalysisType > dataflow , PrintStream out ) { DataflowCFGPrinter < Fact , AnalysisType > printer = new DataflowCFGPrinter <> ( dataflow ) ; printer . print ( out ) ; }
Print CFG annotated with results from given dataflow analysis .
74
13
152,970
private void fillMenu ( ) { isBugItem = new MenuItem ( menu , SWT . RADIO ) ; isBugItem . setText ( "Bug" ) ; notBugItem = new MenuItem ( menu , SWT . RADIO ) ; notBugItem . setText ( "Not Bug" ) ; isBugItem . addSelectionListener ( new SelectionAdapter ( ) { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ @ Override public void widgetSelected ( SelectionEvent e ) { if ( bugInstance != null ) { classifyWarning ( bugInstance , true ) ; } } } ) ; notBugItem . addSelectionListener ( new SelectionAdapter ( ) { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ @ Override public void widgetSelected ( SelectionEvent e ) { if ( bugInstance != null ) { classifyWarning ( bugInstance , false ) ; } } } ) ; menu . addMenuListener ( new MenuAdapter ( ) { @ Override public void menuShown ( MenuEvent e ) { // Before showing the menu, sync its contents // with the current BugInstance (if any) if ( DEBUG ) { System . out . println ( "Synchronizing menu!" ) ; } syncMenu ( ) ; } } ) ; }
Fill the classification menu .
341
5
152,971
private void syncMenu ( ) { if ( bugInstance != null ) { isBugItem . setEnabled ( true ) ; notBugItem . setEnabled ( true ) ; BugProperty isBugProperty = bugInstance . lookupProperty ( BugProperty . IS_BUG ) ; if ( isBugProperty == null ) { // Unclassified isBugItem . setSelection ( false ) ; notBugItem . setSelection ( false ) ; } else { boolean isBug = isBugProperty . getValueAsBoolean ( ) ; isBugItem . setSelection ( isBug ) ; notBugItem . setSelection ( ! isBug ) ; } } else { // No bug instance, so uncheck and disable the menu items if ( DEBUG ) { System . out . println ( "No bug instance found, disabling menu items" ) ; } isBugItem . setEnabled ( false ) ; notBugItem . setEnabled ( false ) ; isBugItem . setSelection ( false ) ; notBugItem . setSelection ( false ) ; } }
Update menu to match currently selected BugInstance .
218
9
152,972
public PatternMatcher execute ( ) throws DataflowAnalysisException { workList . addLast ( cfg . getEntry ( ) ) ; while ( ! workList . isEmpty ( ) ) { BasicBlock basicBlock = workList . removeLast ( ) ; visitedBlockMap . put ( basicBlock , basicBlock ) ; // Scan instructions of basic block for possible matches BasicBlock . InstructionIterator i = basicBlock . instructionIterator ( ) ; while ( i . hasNext ( ) ) { attemptMatch ( basicBlock , i . duplicate ( ) ) ; i . next ( ) ; } // Add successors of the basic block (which haven't been visited // already) Iterator < BasicBlock > succIterator = cfg . successorIterator ( basicBlock ) ; while ( succIterator . hasNext ( ) ) { BasicBlock succ = succIterator . next ( ) ; if ( visitedBlockMap . get ( succ ) == null ) { workList . addLast ( succ ) ; } } } return this ; }
Search for examples of the ByteCodePattern .
207
9
152,973
private void attemptMatch ( BasicBlock basicBlock , BasicBlock . InstructionIterator instructionIterator ) throws DataflowAnalysisException { work ( new State ( basicBlock , instructionIterator , pattern . getFirst ( ) ) ) ; }
Attempt to begin a match .
45
6
152,974
public static final String getString ( Type type ) { if ( type instanceof GenericObjectType ) { return ( ( GenericObjectType ) type ) . toString ( true ) ; } else if ( type instanceof ArrayType ) { return TypeCategory . asString ( ( ArrayType ) type ) ; } else { return type . toString ( ) ; } }
Get String representation of a Type including Generic information
75
9
152,975
private boolean askToSave ( ) { if ( mainFrame . isProjectChanged ( ) ) { int response = JOptionPane . showConfirmDialog ( mainFrame , L10N . getLocalString ( "dlg.save_current_changes" , "The current project has been changed, Save current changes?" ) , L10N . getLocalString ( "dlg.save_changes" , "Save Changes?" ) , JOptionPane . YES_NO_CANCEL_OPTION , JOptionPane . WARNING_MESSAGE ) ; if ( response == JOptionPane . YES_OPTION ) { if ( mainFrame . getSaveFile ( ) != null ) { save ( ) ; } else { saveAs ( ) ; } } else if ( response == JOptionPane . CANCEL_OPTION ) { return true ; // IF no, do nothing. } } return false ; }
Returns true if cancelled
198
4
152,976
SaveReturn saveAnalysis ( final File f ) { Future < Object > waiter = mainFrame . getBackgroundExecutor ( ) . submit ( ( ) -> { BugSaver . saveBugs ( f , mainFrame . getBugCollection ( ) , mainFrame . getProject ( ) ) ; return null ; } ) ; try { waiter . get ( ) ; } catch ( InterruptedException e ) { return SaveReturn . SAVE_ERROR ; } catch ( ExecutionException e ) { return SaveReturn . SAVE_ERROR ; } mainFrame . setProjectChanged ( false ) ; return SaveReturn . SAVE_SUCCESSFUL ; }
Save current analysis as file passed in . Return SAVE_SUCCESSFUL if save successful . Method doesn t do much . This method is more if need to do other things in the future for saving analysis . And to keep saving naming convention .
133
50
152,977
public String getClassPath ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Entry entry : entryList ) { if ( buf . length ( ) > 0 ) { buf . append ( File . pathSeparator ) ; } buf . append ( entry . getURL ( ) ) ; } return buf . toString ( ) ; }
Return the classpath string .
73
6
152,978
private InputStream getInputStreamForResource ( String resourceName ) { // Try each classpath entry, in order, until we find one // that has the resource. Catch and ignore IOExceptions. // FIXME: The following code should throw IOException. // // URL.openStream() does not seem to distinguish // whether the resource does not exist, vs. some // transient error occurring while trying to access it. // This is unfortunate, because we really should throw // an exception out of this method in the latter case, // since it means our knowledge of the classpath is // incomplete. // // Short of reimplementing HTTP, etc., ourselves, // there is probably nothing we can do about this problem. for ( Entry entry : entryList ) { InputStream in ; try { in = entry . openStream ( resourceName ) ; if ( in != null ) { if ( URLClassPathRepository . DEBUG ) { System . out . println ( "\t==> found " + resourceName + " in " + entry . getURL ( ) ) ; } return in ; } } catch ( IOException ignore ) { // Ignore } } if ( URLClassPathRepository . DEBUG ) { System . out . println ( "\t==> could not find " + resourceName + " on classpath" ) ; } return null ; }
Open a stream to read given resource .
277
8
152,979
public JavaClass lookupClass ( String className ) throws ClassNotFoundException { if ( classesThatCantBeFound . contains ( className ) ) { throw new ClassNotFoundException ( "Error while looking for class " + className + ": class not found" ) ; } String resourceName = className . replace ( ' ' , ' ' ) + ".class" ; InputStream in = null ; boolean parsedClass = false ; try { in = getInputStreamForResource ( resourceName ) ; if ( in == null ) { classesThatCantBeFound . add ( className ) ; throw new ClassNotFoundException ( "Error while looking for class " + className + ": class not found" ) ; } ClassParser classParser = new ClassParser ( in , resourceName ) ; JavaClass javaClass = classParser . parse ( ) ; parsedClass = true ; return javaClass ; } catch ( IOException e ) { classesThatCantBeFound . add ( className ) ; throw new ClassNotFoundException ( "IOException while looking for class " + className , e ) ; } finally { if ( in != null && ! parsedClass ) { try { in . close ( ) ; } catch ( IOException ignore ) { // Ignore } } } }
Look up a class from the classpath .
267
9
152,980
public static String getURLProtocol ( String urlString ) { String protocol = null ; int firstColon = urlString . indexOf ( ' ' ) ; if ( firstColon >= 0 ) { String specifiedProtocol = urlString . substring ( 0 , firstColon ) ; if ( FindBugs . knownURLProtocolSet . contains ( specifiedProtocol ) ) { protocol = specifiedProtocol ; } } return protocol ; }
Get the URL protocol of given URL string .
92
9
152,981
public static String getFileExtension ( String fileName ) { int lastDot = fileName . lastIndexOf ( ' ' ) ; return ( lastDot >= 0 ) ? fileName . substring ( lastDot ) : null ; }
Get the file extension of given fileName .
52
9
152,982
public void killLoadsOfField ( XField field ) { if ( ! REDUNDANT_LOAD_ELIMINATION ) { return ; } HashSet < AvailableLoad > killMe = new HashSet <> ( ) ; for ( AvailableLoad availableLoad : getAvailableLoadMap ( ) . keySet ( ) ) { if ( availableLoad . getField ( ) . equals ( field ) ) { if ( RLE_DEBUG ) { System . out . println ( "KILLING Load of " + availableLoad + " in " + this ) ; } killMe . add ( availableLoad ) ; } } killAvailableLoads ( killMe ) ; }
Kill all loads of given field .
139
7
152,983
public void addMeta ( char meta , String replacement ) { metaCharacterSet . set ( meta ) ; replacementMap . put ( new String ( new char [ ] { meta } ) , replacement ) ; }
Add a metacharacter and its replacement .
42
10
152,984
public static String getResourceString ( String key ) { ResourceBundle bundle = FindbugsPlugin . getDefault ( ) . getResourceBundle ( ) ; try { return bundle . getString ( key ) ; } catch ( MissingResourceException e ) { return key ; } }
Returns the string from the plugin s resource bundle or key if not found .
57
15
152,985
public static String getFindBugsEnginePluginLocation ( ) { // findbugs.home should be set to the directory the plugin is // installed in. URL u = plugin . getBundle ( ) . getEntry ( "/" ) ; try { URL bundleRoot = FileLocator . resolve ( u ) ; String path = bundleRoot . getPath ( ) ; if ( FindBugsBuilder . DEBUG ) { System . out . println ( "Pluginpath: " + path ) ; //$NON-NLS-1$ } if ( path . endsWith ( "/eclipsePlugin/" ) ) { File f = new File ( path ) ; f = f . getParentFile ( ) ; f = new File ( f , "findbugs" ) ; path = f . getPath ( ) + "/" ; } return path ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "IO Exception locating engine plugin" ) ; } return null ; }
Find the filesystem path of the FindBugs plugin directory .
210
12
152,986
public void logException ( Throwable e , String message ) { logMessage ( IStatus . ERROR , message , e ) ; }
Log an exception .
27
4
152,987
public static IPath getBugCollectionFile ( IProject project ) { // IPath path = project.getWorkingLocation(PLUGIN_ID); // // project-specific but not user-specific? IPath path = getDefault ( ) . getStateLocation ( ) ; // user-specific but not // project-specific return path . append ( project . getName ( ) + ".fbwarnings.xml" ) ; }
Get the file resource used to store findbugs warnings for a project .
89
14
152,988
public static SortedBugCollection getBugCollection ( IProject project , IProgressMonitor monitor ) throws CoreException { SortedBugCollection bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; if ( bugCollection == null ) { try { readBugCollectionAndProject ( project , monitor ) ; bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read bug collection for project" ) ; bugCollection = createDefaultEmptyBugCollection ( project ) ; } catch ( DocumentException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read bug collection for project" ) ; bugCollection = createDefaultEmptyBugCollection ( project ) ; } } return bugCollection ; }
Get the stored BugCollection for project . If there is no stored bug collection for the project or if an error occurs reading the stored bug collection a default empty collection is created and returned .
203
37
152,989
private static void readBugCollectionAndProject ( IProject project , IProgressMonitor monitor ) throws IOException , DocumentException , CoreException { SortedBugCollection bugCollection ; IPath bugCollectionPath = getBugCollectionFile ( project ) ; // Don't turn the path to an IFile because it isn't local to the // project. // see the javadoc for org.eclipse.core.runtime.Plugin File bugCollectionFile = bugCollectionPath . toFile ( ) ; if ( ! bugCollectionFile . exists ( ) ) { // throw new // FileNotFoundException(bugCollectionFile.getLocation().toOSString()); getDefault ( ) . logInfo ( "creating new bug collection: " + bugCollectionPath . toOSString ( ) ) ; createDefaultEmptyBugCollection ( project ) ; // since we no longer // throw, have to do this // here return ; } UserPreferences prefs = getUserPreferences ( project ) ; bugCollection = new SortedBugCollection ( ) ; bugCollection . getProject ( ) . setGuiCallback ( new EclipseGuiCallback ( project ) ) ; bugCollection . readXML ( bugCollectionFile ) ; cacheBugCollectionAndProject ( project , bugCollection , bugCollection . getProject ( ) ) ; }
Read saved bug collection and findbugs project from file . Will populate the bug collection and findbugs project session properties if successful . If there is no saved bug collection and project for the eclipse project then FileNotFoundException will be thrown .
268
47
152,990
public static void storeBugCollection ( IProject project , final SortedBugCollection bugCollection , IProgressMonitor monitor ) throws IOException , CoreException { // Store the bug collection and findbugs project in the session project . setSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION , bugCollection ) ; if ( bugCollection != null ) { writeBugCollection ( project , bugCollection , monitor ) ; } }
Store a new bug collection for a project . The collection is stored in the session and also in a file in the project .
88
25
152,991
public static void saveCurrentBugCollection ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( isBugCollectionDirty ( project ) ) { SortedBugCollection bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; if ( bugCollection != null ) { writeBugCollection ( project , bugCollection , monitor ) ; } } }
If necessary save current bug collection for project to disk .
89
11
152,992
public static UserPreferences getProjectPreferences ( IProject project , boolean forceRead ) { try { UserPreferences prefs = ( UserPreferences ) project . getSessionProperty ( SESSION_PROPERTY_USERPREFS ) ; if ( prefs == null || forceRead ) { prefs = readUserPreferences ( project ) ; if ( prefs == null ) { prefs = getWorkspacePreferences ( ) . clone ( ) ; } project . setSessionProperty ( SESSION_PROPERTY_USERPREFS , prefs ) ; } return prefs ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error getting SpotBugs preferences for project" ) ; return getWorkspacePreferences ( ) . clone ( ) ; } }
Get project own preferences set .
171
6
152,993
public static void saveUserPreferences ( IProject project , final UserPreferences userPrefs ) throws CoreException { FileOutput userPrefsOutput = new FileOutput ( ) { @ Override public void writeFile ( OutputStream os ) throws IOException { userPrefs . write ( os ) ; } @ Override public String getTaskDescription ( ) { return "writing user preferences" ; } } ; if ( project != null ) { // Make the new user preferences current for the project project . setSessionProperty ( SESSION_PROPERTY_USERPREFS , userPrefs ) ; IFile userPrefsFile = getUserPreferencesFile ( project ) ; ensureReadWrite ( userPrefsFile ) ; IO . writeFile ( userPrefsFile , userPrefsOutput , null ) ; if ( project . getFile ( DEPRECATED_PREFS_PATH ) . equals ( userPrefsFile ) ) { String message = "Found old style FindBugs preferences for project '" + project . getName ( ) + "'. This preferences are not at the default location: '" + DEFAULT_PREFS_PATH + "'." + " Please move '" + DEPRECATED_PREFS_PATH + "' to '" + DEFAULT_PREFS_PATH + "'." ; getDefault ( ) . logWarning ( message ) ; } } else { // write the workspace preferences to the eclipse preference store ByteArrayOutputStream bos = new ByteArrayOutputStream ( 10000 ) ; try { userPrefs . write ( bos ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to write user preferences" ) ; return ; } Properties props = new Properties ( ) ; try { props . load ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to save user preferences" ) ; return ; } IPreferenceStore store = getDefault ( ) . getPreferenceStore ( ) ; // Reset any existing custom group entries resetStore ( store , UserPreferences . KEY_PLUGIN ) ; resetStore ( store , UserPreferences . KEY_EXCLUDE_BUGS ) ; resetStore ( store , UserPreferences . KEY_EXCLUDE_FILTER ) ; resetStore ( store , UserPreferences . KEY_INCLUDE_FILTER ) ; for ( Entry < Object , Object > entry : props . entrySet ( ) ) { store . putValue ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } if ( store instanceof IPersistentPreferenceStore ) { IPersistentPreferenceStore store2 = ( IPersistentPreferenceStore ) store ; try { store2 . save ( ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to save user preferences" ) ; } } } }
Save current UserPreferences for given project or workspace .
635
11
152,994
private static void resetStore ( IPreferenceStore store , String prefix ) { int start = 0 ; // 99 is paranoia. while ( start < 99 ) { String name = prefix + start ; if ( store . contains ( name ) ) { store . setToDefault ( name ) ; } else { break ; } start ++ ; } }
Removes all consequent enumerated keys from given store staring with given prefix
69
15
152,995
private static void ensureReadWrite ( IFile file ) throws CoreException { /* * fix for bug 1683264: we should checkout file before writing to it */ if ( file . isReadOnly ( ) ) { IStatus checkOutStatus = ResourcesPlugin . getWorkspace ( ) . validateEdit ( new IFile [ ] { file } , null ) ; if ( ! checkOutStatus . isOK ( ) ) { throw new CoreException ( checkOutStatus ) ; } } }
Ensure that a file is writable . If not currently writable check it as so that we can edit it .
100
24
152,996
private static UserPreferences readUserPreferences ( IProject project ) throws CoreException { IFile userPrefsFile = getUserPreferencesFile ( project ) ; if ( ! userPrefsFile . exists ( ) ) { return null ; } try { // force is preventing us for out-of-sync exception if file was // changed externally InputStream in = userPrefsFile . getContents ( true ) ; UserPreferences userPrefs = FindBugsPreferenceInitializer . createDefaultUserPreferences ( ) ; userPrefs . read ( in ) ; return userPrefs ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read user preferences for project" ) ; return null ; } }
Read UserPreferences for project from the file in the project directory . Returns null if the preferences have not been saved to a file or if there is an error reading the preferences file .
161
37
152,997
public RecursiveFileSearch search ( ) throws InterruptedException { File baseFile = new File ( baseDir ) ; String basePath = bestEffortCanonicalPath ( baseFile ) ; directoryWorkList . add ( baseFile ) ; directoriesScanned . add ( basePath ) ; directoriesScannedList . add ( basePath ) ; while ( ! directoryWorkList . isEmpty ( ) ) { File dir = directoryWorkList . removeFirst ( ) ; if ( ! dir . isDirectory ( ) ) { continue ; } File [ ] contentList = dir . listFiles ( ) ; if ( contentList == null ) { continue ; } for ( File aContentList : contentList ) { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } File file = aContentList ; if ( ! fileFilter . accept ( file ) ) { continue ; } if ( file . isDirectory ( ) ) { String myPath = bestEffortCanonicalPath ( file ) ; if ( myPath . startsWith ( basePath ) && directoriesScanned . add ( myPath ) ) { directoriesScannedList . add ( myPath ) ; directoryWorkList . add ( file ) ; } } else { resultList . add ( file . getPath ( ) ) ; } } } return this ; }
Perform the search .
279
5
152,998
public static MethodDescriptor getMethodDescriptor ( JavaClass jclass , Method method ) { return DescriptorFactory . instance ( ) . getMethodDescriptor ( jclass . getClassName ( ) . replace ( ' ' , ' ' ) , method . getName ( ) , method . getSignature ( ) , method . isStatic ( ) ) ; }
Construct a MethodDescriptor from JavaClass and method .
79
12
152,999
public static ClassDescriptor getClassDescriptor ( JavaClass jclass ) { return DescriptorFactory . instance ( ) . getClassDescriptor ( ClassName . toSlashedClassName ( jclass . getClassName ( ) ) ) ; }
Construct a ClassDescriptor from a JavaClass .
55
11