idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
24,900 | public String compress ( int drawableID ) throws IOException { Bitmap bitmap = BitmapFactory . decodeResource ( mContext . getApplicationContext ( ) . getResources ( ) , drawableID ) ; if ( null != bitmap ) { String timeStamp = new SimpleDateFormat ( "yyyyMMdd_HHmmss" , Locale . ENGLISH ) . format ( new Date ( ) ) ; String imageFileName = "JPEG_" + timeStamp + "_" ; File storageDir = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) ; File image = File . createTempFile ( imageFileName , ".jpg" , storageDir ) ; FileOutputStream out = new FileOutputStream ( image ) ; bitmap . compress ( Bitmap . CompressFormat . JPEG , 100 , out ) ; Uri copyImageUri = FileProvider . getUriForFile ( mContext , FILE_PROVIDER_AUTHORITY , image ) ; String compressedImagePath = compressImage ( image . getAbsolutePath ( ) , new File ( Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) , "Silicompressor/images" ) ) ; if ( image . exists ( ) ) { deleteImageFile ( image . getAbsolutePath ( ) ) ; } return compressedImagePath ; } return null ; } | Compress drawable file with specified drawableID |
24,901 | public Bitmap getCompressBitmap ( String imagePath , boolean deleteSourceImage ) throws IOException { File imageFile = new File ( compressImage ( imagePath , new File ( Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) , "Silicompressor/images" ) ) ) ; Uri newImageUri = FileProvider . getUriForFile ( mContext , FILE_PROVIDER_AUTHORITY , imageFile ) ; Bitmap bitmap = MediaStore . Images . Media . getBitmap ( mContext . getContentResolver ( ) , newImageUri ) ; if ( deleteSourceImage ) { boolean isdeleted = deleteImageFile ( imagePath ) ; Log . d ( LOG_TAG , ( isdeleted ) ? "Source image file deleted" : "Error: Source image file not deleted." ) ; } deleteImageFile ( imageFile . getAbsolutePath ( ) ) ; return bitmap ; } | Compress the image at with the specified path and return the bitmap data of the compressed image . |
24,902 | public String compressVideo ( String videoFilePath , String destinationDir ) throws URISyntaxException { return compressVideo ( videoFilePath , destinationDir , 0 , 0 , 0 ) ; } | Perform background video compression . Make sure the videofileUri and destinationUri are valid resources because this method does not account for missing directories hence your converted file could be in an unknown location This uses default values for the converted videos |
24,903 | public String compressVideo ( String videoFilePath , String destinationDir , int outWidth , int outHeight , int bitrate ) throws URISyntaxException { boolean isconverted = MediaController . getInstance ( ) . convertVideo ( videoFilePath , new File ( destinationDir ) , outWidth , outHeight , bitrate ) ; if ( isconverted ) { Log . v ( LOG_TAG , "Video Conversion Complete" ) ; } else { Log . v ( LOG_TAG , "Video conversion in progress" ) ; } return MediaController . cachedFile . getPath ( ) ; } | Perform background video compression . Make sure the videofileUri and destinationUri are valid resources because this method does not account for missing directories hence your converted file could be in an unknown location |
24,904 | private String getFilename ( String filename , File file ) { if ( ! file . exists ( ) ) { file . mkdirs ( ) ; } String ext = ".jpg" ; return ( file . getAbsolutePath ( ) + "/IMG_" + new SimpleDateFormat ( "yyyyMMdd_HHmmss" ) . format ( new Date ( ) ) + ext ) ; } | Get the file path of the compressed file |
24,905 | private String getRealPathFromURI ( String contentURI ) { Uri contentUri = Uri . parse ( contentURI ) ; Cursor cursor = mContext . getContentResolver ( ) . query ( contentUri , null , null , null , null ) ; if ( cursor == null ) { return contentUri . getPath ( ) ; } else { cursor . moveToFirst ( ) ; int index = cursor . getColumnIndex ( MediaStore . Images . ImageColumns . DATA ) ; Log . e ( LOG_TAG , String . format ( "%d" , index ) ) ; String str = cursor . getString ( index ) ; cursor . close ( ) ; return str ; } } | Gets a valid path from the supply contentURI |
24,906 | static boolean deleteImageFile ( String imagePath ) { File imageFile = new File ( imagePath ) ; boolean deleted = false ; if ( imageFile . exists ( ) ) { deleted = imageFile . delete ( ) ; } return deleted ; } | Deletes image file for a given path . |
24,907 | public < K > CassandraJavaPairRDD < K , R > keyBy ( ClassTag < K > keyClassTag , RowReaderFactory < K > rrf , RowWriterFactory < K > rwf , ColumnRef ... columns ) { Seq < ColumnRef > columnRefs = JavaApiHelper . toScalaSeq ( columns ) ; CassandraRDD < Tuple2 < K , R > > resultRDD = columns . length == 0 ? rdd ( ) . keyBy ( keyClassTag , rrf , rwf ) : rdd ( ) . keyBy ( columnRefs , keyClassTag , rrf , rwf ) ; return new CassandraJavaPairRDD < > ( resultRDD , keyClassTag , classTag ( ) ) ; } | Selects a subset of columns mapped to the key of a JavaPairRDD . The selected columns must be available in the CassandraRDD . If no selected columns are given all available columns are selected . |
24,908 | public JavaPairRDD < K , Collection < V > > spanByKey ( ClassTag < K > keyClassTag ) { ClassTag < Tuple2 < K , Collection < V > > > tupleClassTag = classTag ( Tuple2 . class ) ; ClassTag < Collection < V > > vClassTag = classTag ( Collection . class ) ; RDD < Tuple2 < K , Collection < V > > > newRDD = pairRDDFunctions . spanByKey ( ) . map ( JavaApiHelper . < K , V , Seq < V > > valuesAsJavaCollection ( ) , tupleClassTag ) ; return new JavaPairRDD < > ( newRDD , keyClassTag , vClassTag ) ; } | Groups items with the same key assuming the items with the same key are next to each other in the collection . It does not perform shuffle therefore it is much faster than using much more universal Spark RDD groupByKey . For this method to be useful with Cassandra tables the key must represent a prefix of the primary key containing at least the partition key of the Cassandra table . |
24,909 | @ SuppressWarnings ( "RedundantCast" ) public ColumnRef [ ] selectedColumnRefs ( ) { ClassTag < ColumnRef > classTag = getClassTag ( ColumnRef . class ) ; return ( ColumnRef [ ] ) rdd ( ) . selectedColumnRefs ( ) . toArray ( classTag ) ; } | Returns the columns to be selected from the table . |
24,910 | @ SuppressWarnings ( "RedundantCast" ) public String [ ] selectedColumnNames ( ) { ClassTag < String > classTag = getClassTag ( String . class ) ; return ( String [ ] ) rdd ( ) . selectedColumnNames ( ) . toArray ( classTag ) ; } | Returns the names of columns to be selected from the table . |
24,911 | public static String addFileExtension ( String fileName , VectorGraphicsFormat vectorGraphicsFormat ) { String fileNameWithFileExtension = fileName ; final String newFileExtension = "." + vectorGraphicsFormat . toString ( ) . toLowerCase ( ) ; if ( fileName . length ( ) <= newFileExtension . length ( ) || ! fileName . substring ( fileName . length ( ) - newFileExtension . length ( ) , fileName . length ( ) ) . equalsIgnoreCase ( newFileExtension ) ) { fileNameWithFileExtension = fileName + newFileExtension ; } return fileNameWithFileExtension ; } | Only adds the extension of the VectorGraphicsFormat to the filename if the filename doesn t already have it . |
24,912 | private void overrideMinMaxForXAxis ( ) { double overrideXAxisMinValue = xAxis . getMin ( ) ; double overrideXAxisMaxValue = xAxis . getMax ( ) ; if ( chart . getStyler ( ) . getXAxisMin ( ) != null ) { overrideXAxisMinValue = chart . getStyler ( ) . getXAxisMin ( ) ; } if ( chart . getStyler ( ) . getXAxisMax ( ) != null ) { overrideXAxisMaxValue = chart . getStyler ( ) . getXAxisMax ( ) ; } xAxis . setMin ( overrideXAxisMinValue ) ; xAxis . setMax ( overrideXAxisMaxValue ) ; } | Here we can add special case min max calculations and take care of manual min max settings . |
24,913 | boolean willLabelsFitInTickSpaceHint ( List < String > tickLabels , int tickSpacingHint ) { if ( this . axisDirection == Direction . Y ) { return true ; } String sampleLabel = " " ; for ( String tickLabel : tickLabels ) { if ( tickLabel != null && tickLabel . length ( ) > sampleLabel . length ( ) ) { sampleLabel = tickLabel ; } } TextLayout textLayout = new TextLayout ( sampleLabel , styler . getAxisTickLabelsFont ( ) , new FontRenderContext ( null , true , false ) ) ; AffineTransform rot = styler . getXAxisLabelRotation ( ) == 0 ? null : AffineTransform . getRotateInstance ( - 1 * Math . toRadians ( styler . getXAxisLabelRotation ( ) ) ) ; Shape shape = textLayout . getOutline ( rot ) ; Rectangle2D rectangle = shape . getBounds ( ) ; double largestLabelWidth = rectangle . getWidth ( ) ; return ( largestLabelWidth * 1.1 < tickSpacingHint ) ; } | Given the generated tickLabels will they fit side - by - side without overlapping each other and looking bad? Sometimes the given tickSpacingHint is simply too small . |
24,914 | public static XYChart getChart ( String chartTitle , String xTitle , String yTitle , String [ ] seriesNames , double [ ] xData , double [ ] [ ] yData ) { XYChart chart = new XYChart ( WIDTH , HEIGHT ) ; chart . setTitle ( chartTitle ) ; chart . setXAxisTitle ( xTitle ) ; chart . setYAxisTitle ( yTitle ) ; for ( int i = 0 ; i < yData . length ; i ++ ) { XYSeries series ; if ( seriesNames != null ) { series = chart . addSeries ( seriesNames [ i ] , xData , yData [ i ] ) ; } else { chart . getStyler ( ) . setLegendVisible ( false ) ; series = chart . addSeries ( " " + i , xData , yData [ i ] ) ; } series . setMarker ( SeriesMarkers . NONE ) ; } return chart ; } | Creates a Chart with multiple Series for the same X - Axis data with default style |
24,915 | public RadarSeries addSeries ( String seriesName , double [ ] values , String [ ] tooltipOverrides ) { sanityCheck ( seriesName , values , tooltipOverrides ) ; RadarSeries series = new RadarSeries ( seriesName , values , tooltipOverrides ) ; seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a Radar type chart |
24,916 | private static String [ ] getSeriesDataFromCSVRows ( File csvFile ) { String [ ] xAndYData = new String [ 3 ] ; BufferedReader bufferedReader = null ; try { int counter = 0 ; String line ; bufferedReader = new BufferedReader ( new FileReader ( csvFile ) ) ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { xAndYData [ counter ++ ] = line ; } } catch ( Exception e ) { System . out . println ( "Exception while reading csv file: " + e ) ; } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return xAndYData ; } | Get the series s data from a file |
24,917 | private static File [ ] getAllFiles ( String dirName , String regex ) { File [ ] allFiles = getAllFiles ( dirName ) ; List < File > matchingFiles = new ArrayList < File > ( ) ; for ( File allFile : allFiles ) { if ( allFile . getName ( ) . matches ( regex ) ) { matchingFiles . add ( allFile ) ; } } return matchingFiles . toArray ( new File [ matchingFiles . size ( ) ] ) ; } | This method returns the files found in the given directory matching the given regular expression . |
24,918 | private static File [ ] getAllFiles ( String dirName ) { File dir = new File ( dirName ) ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { List < File > filteredFiles = new ArrayList < File > ( ) ; for ( File file : files ) { if ( file . isFile ( ) ) { filteredFiles . add ( file ) ; } } return filteredFiles . toArray ( new File [ filteredFiles . size ( ) ] ) ; } else { System . out . println ( dirName + " does not denote a valid directory!" ) ; return new File [ 0 ] ; } } | This method returns the Files found in the given directory |
24,919 | public RadarSeries setLineStyle ( BasicStroke basicStroke ) { stroke = basicStroke ; if ( this . lineWidth > 0.0f ) { stroke = new BasicStroke ( lineWidth , this . stroke . getEndCap ( ) , this . stroke . getLineJoin ( ) , this . stroke . getMiterLimit ( ) , this . stroke . getDashArray ( ) , this . stroke . getDashPhase ( ) ) ; } return this ; } | Set the line style of the series |
24,920 | public DialSeries addSeries ( String seriesName , double value , String annotation ) { sanityCheck ( seriesName , value ) ; DialSeries series = new DialSeries ( seriesName , value , annotation ) ; seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a Dial type chart |
24,921 | public BubbleSeries addSeries ( String seriesName , List < ? extends Number > xData , List < ? extends Number > yData , List < ? extends Number > bubbleData ) { return addSeries ( seriesName , Utils . getDoubleArrayFromNumberList ( xData ) , Utils . getDoubleArrayFromNumberList ( yData ) , Utils . getDoubleArrayFromNumberList ( bubbleData ) ) ; } | Add a series for a Bubble type chart using using double arrays |
24,922 | public BubbleSeries addSeries ( String seriesName , double [ ] xData , double [ ] yData , double [ ] bubbleData ) { sanityCheck ( seriesName , xData , yData , bubbleData ) ; BubbleSeries series ; if ( xData != null ) { if ( xData . length != yData . length ) { throw new IllegalArgumentException ( "X and Y-Axis sizes are not the same!!!" ) ; } series = new BubbleSeries ( seriesName , xData , yData , bubbleData ) ; } else { series = new BubbleSeries ( seriesName , Utils . getGeneratedDataAsArray ( yData . length ) , yData , bubbleData ) ; } seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a Bubble type chart using using Lists |
24,923 | public PieSeries addSeries ( String seriesName , Number value ) { PieSeries series = new PieSeries ( seriesName , value ) ; if ( seriesMap . keySet ( ) . contains ( seriesName ) ) { throw new IllegalArgumentException ( "Series name >" + seriesName + "< has already been used. Use unique names for each series!!!" ) ; } seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a Pie type chart |
24,924 | public PieSeries updatePieSeries ( String seriesName , Number value ) { Map < String , PieSeries > seriesMap = getSeriesMap ( ) ; PieSeries series = seriesMap . get ( seriesName ) ; if ( series == null ) { throw new IllegalArgumentException ( "Series name >" + seriesName + "< not found!!!" ) ; } series . replaceData ( value ) ; return series ; } | Update a series by updating the pie slide value |
24,925 | public CategorySeries addSeries ( String seriesName , double [ ] xData , double [ ] yData ) { return addSeries ( seriesName , xData , yData , null ) ; } | Add a series for a Category type chart using using double arrays |
24,926 | public CategorySeries addSeries ( String seriesName , double [ ] xData , double [ ] yData , double [ ] errorBars ) { return addSeries ( seriesName , Utils . getNumberListFromDoubleArray ( xData ) , Utils . getNumberListFromDoubleArray ( yData ) , Utils . getNumberListFromDoubleArray ( errorBars ) ) ; } | Add a series for a Category type chart using using double arrays with error bars |
24,927 | public CategorySeries addSeries ( String seriesName , List < ? > xData , List < ? extends Number > yData , List < ? extends Number > errorBars ) { sanityCheck ( seriesName , xData , yData , errorBars ) ; CategorySeries series ; if ( xData != null ) { if ( xData . size ( ) != yData . size ( ) ) { throw new IllegalArgumentException ( "X and Y-Axis sizes are not the same!!!" ) ; } series = new CategorySeries ( seriesName , xData , yData , errorBars , getDataType ( xData ) ) ; } else { xData = Utils . getGeneratedDataAsList ( yData . size ( ) ) ; series = new CategorySeries ( seriesName , xData , yData , errorBars , getDataType ( xData ) ) ; } seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a Category type chart using Lists with error bars |
24,928 | public void setCustomCategoryLabels ( Map < Object , Object > customCategoryLabels ) { AxesChartSeriesCategory axesChartSeries = getSeriesMap ( ) . values ( ) . iterator ( ) . next ( ) ; List < ? > categories = ( List < ? > ) axesChartSeries . getXData ( ) ; Map < Double , Object > axisTickValueLabelMap = new LinkedHashMap < Double , Object > ( ) ; for ( Entry < Object , Object > entry : customCategoryLabels . entrySet ( ) ) { int index = categories . indexOf ( entry . getKey ( ) ) ; if ( index == - 1 ) { throw new IllegalArgumentException ( "Could not find category index for " + entry . getKey ( ) ) ; } axisTickValueLabelMap . put ( ( double ) index , entry . getValue ( ) ) ; } setXAxisLabelOverrideMap ( axisTickValueLabelMap ) ; } | Set custom X - Axis category labels |
24,929 | private static double [ ] getRandomWalk ( int numPoints ) { double [ ] y = new double [ numPoints ] ; y [ 0 ] = 0 ; for ( int i = 1 ; i < y . length ; i ++ ) { y [ i ] = y [ i - 1 ] + Math . random ( ) - .5 ; } return y ; } | Generates a set of random walk data |
24,930 | public static void writeCSVRows ( XYSeries series , String path2Dir ) { File newFile = new File ( path2Dir + series . getName ( ) + ".csv" ) ; Writer out = null ; try { out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( newFile ) , "UTF8" ) ) ; String csv = join ( series . getXData ( ) , "," ) + System . getProperty ( "line.separator" ) ; out . write ( csv ) ; csv = join ( series . getYData ( ) , "," ) + System . getProperty ( "line.separator" ) ; out . write ( csv ) ; if ( series . getExtraValues ( ) != null ) { csv = join ( series . getExtraValues ( ) , "," ) + System . getProperty ( "line.separator" ) ; out . write ( csv ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { } } } } | Export a XYChart series into rows in a CSV file . |
24,931 | private static String join ( double [ ] seriesData , String separator ) { StringBuilder sb = new StringBuilder ( 256 ) ; sb . append ( seriesData [ 0 ] ) ; for ( int i = 1 ; i < seriesData . length ; i ++ ) { if ( separator != null ) { sb . append ( separator ) ; } sb . append ( seriesData [ i ] ) ; } return sb . toString ( ) ; } | Joins a series into an entire row of comma separated values . |
24,932 | public static void writeCSVColumns ( XYChart chart , String path2Dir ) { for ( XYSeries xySeries : chart . getSeriesMap ( ) . values ( ) ) { writeCSVColumns ( xySeries , path2Dir ) ; } } | Export all XYChart series as columns in separate CSV files . |
24,933 | public static void writeCSVColumns ( XYSeries series , String path2Dir ) { File newFile = new File ( path2Dir + series . getName ( ) + ".csv" ) ; Writer out = null ; try { out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( newFile ) , "UTF8" ) ) ; double [ ] xData = series . getXData ( ) ; double [ ] yData = series . getYData ( ) ; double [ ] errorBarData = series . getExtraValues ( ) ; for ( int i = 0 ; i < xData . length ; i ++ ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( xData [ i ] ) . append ( "," ) ; sb . append ( yData [ i ] ) . append ( "," ) ; if ( errorBarData != null ) { sb . append ( errorBarData [ i ] ) . append ( "," ) ; } sb . setLength ( sb . length ( ) - 1 ) ; sb . append ( System . getProperty ( "line.separator" ) ) ; out . write ( sb . toString ( ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { } } } } | Export a Chart series in columns in a CSV file . |
24,934 | public XYSeries addSeries ( String seriesName , int [ ] xData , int [ ] yData ) { return addSeries ( seriesName , xData , yData , null ) ; } | Add a series for a X - Y type chart using using int arrays |
24,935 | public XYSeries addSeries ( String seriesName , int [ ] xData , int [ ] yData , int [ ] errorBars ) { return addSeries ( seriesName , Utils . getDoubleArrayFromIntArray ( xData ) , Utils . getDoubleArrayFromIntArray ( yData ) , Utils . getDoubleArrayFromIntArray ( errorBars ) , DataType . Number ) ; } | Add a series for a X - Y type chart using using int arrays with error bars |
24,936 | public XYSeries addSeries ( String seriesName , List < ? > xData , List < ? extends Number > yData , List < ? extends Number > errorBars ) { DataType dataType = getDataType ( xData ) ; switch ( dataType ) { case Date : return addSeries ( seriesName , Utils . getDoubleArrayFromDateList ( xData ) , Utils . getDoubleArrayFromNumberList ( yData ) , Utils . getDoubleArrayFromNumberList ( errorBars ) , DataType . Date ) ; default : return addSeries ( seriesName , Utils . getDoubleArrayFromNumberList ( xData ) , Utils . getDoubleArrayFromNumberList ( yData ) , Utils . getDoubleArrayFromNumberList ( errorBars ) , DataType . Number ) ; } } | Add a series for a X - Y type chart using Lists |
24,937 | private XYSeries addSeries ( String seriesName , double [ ] xData , double [ ] yData , double [ ] errorBars , DataType dataType ) { sanityCheck ( seriesName , xData , yData , errorBars ) ; XYSeries series ; if ( xData != null ) { if ( xData . length != yData . length ) { throw new IllegalArgumentException ( "X and Y-Axis sizes are not the same!!!" ) ; } series = new XYSeries ( seriesName , xData , yData , errorBars , dataType ) ; } else { series = new XYSeries ( seriesName , Utils . getGeneratedDataAsArray ( yData . length ) , yData , errorBars , dataType ) ; } seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a X - Y type chart using Lists with error bars |
24,938 | public void repaintChart ( int index ) { chartPanels . get ( index ) . revalidate ( ) ; chartPanels . get ( index ) . repaint ( ) ; } | Repaint the XChartPanel given the provided index . |
24,939 | private Rectangle2D getBoundsHintVertical ( ) { if ( ! chart . getStyler ( ) . isLegendVisible ( ) ) { return new Rectangle2D . Double ( ) ; } boolean containsBox = false ; double legendTextContentMaxWidth = 0 ; double legendContentHeight = 0 ; Map < String , S > map = chart . getSeriesMap ( ) ; for ( S series : map . values ( ) ) { if ( ! series . isShowInLegend ( ) ) { continue ; } if ( ! series . isEnabled ( ) ) { continue ; } Map < String , Rectangle2D > seriesTextBounds = getSeriesTextBounds ( series ) ; double legendEntryHeight = 0 ; for ( Map . Entry < String , Rectangle2D > entry : seriesTextBounds . entrySet ( ) ) { legendEntryHeight += entry . getValue ( ) . getHeight ( ) + MULTI_LINE_SPACE ; legendTextContentMaxWidth = Math . max ( legendTextContentMaxWidth , entry . getValue ( ) . getWidth ( ) ) ; } legendEntryHeight -= MULTI_LINE_SPACE ; legendEntryHeight = Math . max ( legendEntryHeight , ( getSeriesLegendRenderGraphicHeight ( series ) ) ) ; legendContentHeight += legendEntryHeight + chart . getStyler ( ) . getLegendPadding ( ) ; if ( series . getLegendRenderType ( ) == LegendRenderType . Box ) { containsBox = true ; } } double legendContentWidth ; if ( ! containsBox ) { legendContentWidth = chart . getStyler ( ) . getLegendSeriesLineLength ( ) + chart . getStyler ( ) . getLegendPadding ( ) + legendTextContentMaxWidth ; } else { legendContentWidth = BOX_SIZE + chart . getStyler ( ) . getLegendPadding ( ) + legendTextContentMaxWidth ; } double width = legendContentWidth + 2 * chart . getStyler ( ) . getLegendPadding ( ) ; double height = legendContentHeight + chart . getStyler ( ) . getLegendPadding ( ) ; return new Rectangle2D . Double ( 0 , 0 , width , height ) ; } | determine the width and height of the chart legend |
24,940 | private Rectangle2D getBoundsHintHorizontal ( ) { if ( ! chart . getStyler ( ) . isLegendVisible ( ) ) { return new Rectangle2D . Double ( ) ; } double legendTextContentMaxHeight = 0 ; double legendContentWidth = 0 ; Map < String , S > map = chart . getSeriesMap ( ) ; for ( S series : map . values ( ) ) { if ( ! series . isShowInLegend ( ) ) { continue ; } if ( ! series . isEnabled ( ) ) { continue ; } Map < String , Rectangle2D > seriesTextBounds = getSeriesTextBounds ( series ) ; double legendEntryHeight = 0 ; double legendEntryMaxWidth = 0 ; for ( Map . Entry < String , Rectangle2D > entry : seriesTextBounds . entrySet ( ) ) { legendEntryHeight += entry . getValue ( ) . getHeight ( ) + MULTI_LINE_SPACE ; legendEntryMaxWidth = Math . max ( legendEntryMaxWidth , entry . getValue ( ) . getWidth ( ) ) ; } legendEntryHeight -= MULTI_LINE_SPACE ; legendTextContentMaxHeight = Math . max ( legendEntryHeight , getSeriesLegendRenderGraphicHeight ( series ) ) ; legendContentWidth += legendEntryMaxWidth + chart . getStyler ( ) . getLegendPadding ( ) ; if ( series . getLegendRenderType ( ) == LegendRenderType . Line ) { legendContentWidth = chart . getStyler ( ) . getLegendSeriesLineLength ( ) + chart . getStyler ( ) . getLegendPadding ( ) + legendContentWidth ; } else { legendContentWidth = BOX_SIZE + chart . getStyler ( ) . getLegendPadding ( ) + legendContentWidth ; } } double width = legendContentWidth + chart . getStyler ( ) . getLegendPadding ( ) ; double height = legendTextContentMaxHeight + chart . getStyler ( ) . getLegendPadding ( ) * 2 ; return new Rectangle2D . Double ( 0 , 0 , width , height ) ; } | determine the width and height of the chart legend with horizontal layout |
24,941 | Map < String , Rectangle2D > getSeriesTextBounds ( S series ) { String lines [ ] = series . getName ( ) . split ( "\\n" ) ; Map < String , Rectangle2D > seriesTextBounds = new LinkedHashMap < String , Rectangle2D > ( lines . length ) ; for ( String line : lines ) { TextLayout textLayout = new TextLayout ( line , chart . getStyler ( ) . getLegendFont ( ) , new FontRenderContext ( null , true , false ) ) ; Shape shape = textLayout . getOutline ( null ) ; Rectangle2D bounds = shape . getBounds2D ( ) ; seriesTextBounds . put ( line , bounds ) ; } return seriesTextBounds ; } | Normally each legend entry just has one line of text but it can be made multi - line by adding \\ n . This method returns a Map for each single legend entry which is normally just a Map with one single entry . |
24,942 | public OHLCSeries addSeries ( String seriesName , int [ ] xData , int [ ] openData , int [ ] highData , int [ ] lowData , int [ ] closeData ) { return addSeries ( seriesName , Utils . getDoubleArrayFromIntArray ( xData ) , Utils . getDoubleArrayFromIntArray ( openData ) , Utils . getDoubleArrayFromIntArray ( highData ) , Utils . getDoubleArrayFromIntArray ( lowData ) , Utils . getDoubleArrayFromIntArray ( closeData ) , DataType . Number ) ; } | Add a series for a OHLC type chart using using int arrays |
24,943 | private OHLCSeries addSeries ( String seriesName , double [ ] xData , double [ ] openData , double [ ] highData , double [ ] lowData , double [ ] closeData , DataType dataType ) { if ( seriesMap . keySet ( ) . contains ( seriesName ) ) { throw new IllegalArgumentException ( "Series name >" + seriesName + "< has already been used. Use unique names for each series!!!" ) ; } sanityCheck ( seriesName , openData , highData , lowData , closeData ) ; final double [ ] xDataToUse ; if ( xData != null ) { checkDataLengths ( seriesName , "X-Axis" , "Close" , xData , closeData ) ; xDataToUse = xData ; } else { xDataToUse = Utils . getGeneratedDataAsArray ( closeData . length ) ; } OHLCSeries series = new OHLCSeries ( seriesName , xDataToUse , openData , highData , lowData , closeData , dataType ) ; ; seriesMap . put ( seriesName , series ) ; return series ; } | Add a series for a OHLC type chart |
24,944 | private void setSeriesStyles ( ) { SeriesColorMarkerLineStyleCycler seriesColorMarkerLineStyleCycler = new SeriesColorMarkerLineStyleCycler ( getStyler ( ) . getSeriesColors ( ) , getStyler ( ) . getSeriesMarkers ( ) , getStyler ( ) . getSeriesLines ( ) ) ; for ( OHLCSeries series : getSeriesMap ( ) . values ( ) ) { SeriesColorMarkerLineStyle seriesColorMarkerLineStyle = seriesColorMarkerLineStyleCycler . getNextSeriesColorMarkerLineStyle ( ) ; if ( series . getLineStyle ( ) == null ) { series . setLineStyle ( seriesColorMarkerLineStyle . getStroke ( ) ) ; } if ( series . getLineColor ( ) == null ) { series . setLineColor ( seriesColorMarkerLineStyle . getColor ( ) ) ; } if ( series . getFillColor ( ) == null ) { series . setFillColor ( seriesColorMarkerLineStyle . getColor ( ) ) ; } if ( series . getUpColor ( ) == null ) { series . setUpColor ( Color . GREEN ) ; } if ( series . getDownColor ( ) == null ) { series . setDownColor ( Color . RED ) ; } } } | set the series color marker and line style based on theme |
24,945 | private double getXAxisHeightHint ( double workingSpace ) { double titleHeight = 0.0 ; if ( chart . getXAxisTitle ( ) != null && ! chart . getXAxisTitle ( ) . trim ( ) . equalsIgnoreCase ( "" ) && axesChartStyler . isXAxisTitleVisible ( ) ) { TextLayout textLayout = new TextLayout ( chart . getXAxisTitle ( ) , axesChartStyler . getAxisTitleFont ( ) , new FontRenderContext ( null , true , false ) ) ; Rectangle2D rectangle = textLayout . getBounds ( ) ; titleHeight = rectangle . getHeight ( ) + axesChartStyler . getAxisTitlePadding ( ) ; } this . axisTickCalculator = getAxisTickCalculator ( workingSpace ) ; double axisTickLabelsHeight = 0.0 ; if ( axesChartStyler . isXAxisTicksVisible ( ) ) { String sampleLabel = "" ; for ( int i = 0 ; i < axisTickCalculator . getTickLabels ( ) . size ( ) ; i ++ ) { if ( axisTickCalculator . getTickLabels ( ) . get ( i ) != null && axisTickCalculator . getTickLabels ( ) . get ( i ) . length ( ) > sampleLabel . length ( ) ) { sampleLabel = axisTickCalculator . getTickLabels ( ) . get ( i ) ; } } TextLayout textLayout = new TextLayout ( sampleLabel . length ( ) == 0 ? " " : sampleLabel , axesChartStyler . getAxisTickLabelsFont ( ) , new FontRenderContext ( null , true , false ) ) ; AffineTransform rot = axesChartStyler . getXAxisLabelRotation ( ) == 0 ? null : AffineTransform . getRotateInstance ( - 1 * Math . toRadians ( axesChartStyler . getXAxisLabelRotation ( ) ) ) ; Shape shape = textLayout . getOutline ( rot ) ; Rectangle2D rectangle = shape . getBounds ( ) ; axisTickLabelsHeight = rectangle . getHeight ( ) + axesChartStyler . getAxisTickPadding ( ) + axesChartStyler . getAxisTickMarkLength ( ) ; } return titleHeight + axisTickLabelsHeight ; } | The vertical Y - Axis is drawn first but to know the lower bounds of it we need to know how high the X - Axis paint zone is going to be . Since the tick labels could be rotated we need to actually determine the tick labels first to get an idea of how tall the X - Axis tick labels will be . |
24,946 | public double getChartValue ( double screenPoint ) { if ( min == max ) { return min ; } double minVal = min ; double maxVal = max ; if ( min > max ) { if ( getDirection ( ) == Direction . X ) { if ( axesChartStyler instanceof CategoryStyler ) { AxesChartSeriesCategory axesChartSeries = ( AxesChartSeriesCategory ) chart . getSeriesMap ( ) . values ( ) . iterator ( ) . next ( ) ; int count = axesChartSeries . getXData ( ) . size ( ) ; minVal = 0 ; maxVal = count ; } } } double workingSpace ; double startOffset ; if ( direction == Direction . X ) { startOffset = bounds . getX ( ) ; workingSpace = bounds . getWidth ( ) ; } else { startOffset = 0 ; workingSpace = bounds . getHeight ( ) ; screenPoint = bounds . getHeight ( ) - screenPoint + bounds . getY ( ) ; } double tickSpace = axesChartStyler . getPlotContentSize ( ) * workingSpace ; if ( tickSpace < axesChartStyler . getXAxisTickMarkSpacingHint ( ) ) { return minVal ; } double margin = Utils . getTickStartOffset ( workingSpace , tickSpace ) ; double value = ( ( screenPoint - margin - startOffset ) * ( maxVal - minVal ) / tickSpace ) + minVal ; return value ; } | Converts a screen coordinate to chart coordinate value . Reverses the AxisTickCalculators calculation . |
24,947 | private Rectangle2D getBoundsHint ( ) { if ( chart . getStyler ( ) . isChartTitleVisible ( ) && chart . getTitle ( ) . length ( ) > 0 ) { TextLayout textLayout = new TextLayout ( chart . getTitle ( ) , chart . getStyler ( ) . getChartTitleFont ( ) , new FontRenderContext ( null , true , false ) ) ; Rectangle2D rectangle = textLayout . getBounds ( ) ; double width = 2 * chart . getStyler ( ) . getChartTitlePadding ( ) + rectangle . getWidth ( ) ; double height = 2 * chart . getStyler ( ) . getChartTitlePadding ( ) + rectangle . getHeight ( ) ; return new Rectangle2D . Double ( Double . NaN , Double . NaN , width , height ) ; } else { return new Rectangle2D . Double ( ) ; } } | get the height of the chart title including the chart title padding |
24,948 | void closePath ( Graphics2D g , Path2D . Double path , double previousX , Rectangle2D bounds , double yTopMargin ) { if ( path != null ) { double yBottomOfArea = getBounds ( ) . getY ( ) + getBounds ( ) . getHeight ( ) - yTopMargin ; path . lineTo ( previousX , yBottomOfArea ) ; path . closePath ( ) ; g . fill ( path ) ; } } | Closes a path for area charts if one is available . |
24,949 | public SeriesColorMarkerLineStyle getNextSeriesColorMarkerLineStyle ( ) { if ( colorCounter >= seriesColorList . length ) { colorCounter = 0 ; strokeCounter ++ ; } Color seriesColor = seriesColorList [ colorCounter ++ ] ; if ( strokeCounter >= seriesLineStyleList . length ) { strokeCounter = 0 ; } BasicStroke seriesLineStyle = seriesLineStyleList [ strokeCounter ] ; if ( markerCounter >= seriesMarkerList . length ) { markerCounter = 0 ; } Marker marker = seriesMarkerList [ markerCounter ++ ] ; return new SeriesColorMarkerLineStyle ( seriesColor , marker , seriesLineStyle ) ; } | Get the next ColorMarkerLineStyle |
24,950 | private static List < Object > arrayToList ( final Object array ) { if ( array instanceof Object [ ] ) return Arrays . asList ( ( Object [ ] ) array ) ; List < Object > result = new ArrayList < Object > ( ) ; if ( array instanceof int [ ] ) for ( int value : ( int [ ] ) array ) result . add ( value ) ; else if ( array instanceof boolean [ ] ) for ( boolean value : ( boolean [ ] ) array ) result . add ( value ) ; else if ( array instanceof long [ ] ) for ( long value : ( long [ ] ) array ) result . add ( value ) ; else if ( array instanceof float [ ] ) for ( float value : ( float [ ] ) array ) result . add ( value ) ; else if ( array instanceof double [ ] ) for ( double value : ( double [ ] ) array ) result . add ( value ) ; else if ( array instanceof short [ ] ) for ( short value : ( short [ ] ) array ) result . add ( value ) ; else if ( array instanceof byte [ ] ) for ( byte value : ( byte [ ] ) array ) result . add ( value ) ; else if ( array instanceof char [ ] ) for ( char value : ( char [ ] ) array ) result . add ( value ) ; return result ; } | Represents array of any type as list of objects so we can easily iterate over it |
24,951 | public static HttpRequest head ( final CharSequence baseUrl , final Map < ? , ? > params , final boolean encode ) { String url = append ( baseUrl , params ) ; return head ( encode ? encode ( url ) : url ) ; } | Start a HEAD request to the given URL along with the query params |
24,952 | public String getBodyStr ( ) { ArrayList < String > arr = new ArrayList < String > ( ) ; if ( bodyFormat . equals ( EBodyFormat . FORM_KV ) ) { for ( Map . Entry < String , Object > entry : body . entrySet ( ) ) { if ( entry . getValue ( ) == null || entry . getValue ( ) . equals ( "" ) ) { arr . add ( Util . uriEncode ( entry . getKey ( ) , true ) ) ; } else { arr . add ( String . format ( "%s=%s" , Util . uriEncode ( entry . getKey ( ) , true ) , Util . uriEncode ( entry . getValue ( ) . toString ( ) , true ) ) ) ; } } return Util . mkString ( arr . iterator ( ) , '&' ) ; } else if ( bodyFormat . equals ( EBodyFormat . RAW_JSON ) ) { JSONObject json = new JSONObject ( ) ; for ( Map . Entry < String , Object > entry : body . entrySet ( ) ) { json . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return json . toString ( ) ; } else if ( bodyFormat . equals ( EBodyFormat . RAW_JSON_ARRAY ) ) { return ( String ) body . get ( "body" ) ; } return "" ; } | get body content depending on bodyFormat |
24,953 | protected synchronized void getAccessToken ( AipClientConfiguration config ) { if ( ! needAuth ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( String . format ( "app[%s] no need to auth" , this . appId ) ) ; } return ; } JSONObject res = DevAuth . oauth ( aipKey , aipToken , config ) ; if ( res == null ) { LOGGER . warn ( "oauth get null response" ) ; return ; } if ( ! res . isNull ( "access_token" ) ) { state . transfer ( true ) ; accessToken = res . getString ( "access_token" ) ; LOGGER . info ( "get access_token success. current state: " + state . toString ( ) ) ; Integer expireSec = res . getInt ( "expires_in" ) ; Calendar c = Calendar . getInstance ( ) ; c . add ( Calendar . SECOND , expireSec ) ; expireDate = c ; String [ ] scope = res . getString ( "scope" ) . split ( " " ) ; boolean hasRight = false ; for ( String str : scope ) { if ( AipClientConst . AI_ACCESS_RIGHT . contains ( str ) ) { hasRight = true ; break ; } } state . transfer ( hasRight ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "current state after check priviledge: " + state . toString ( ) ) ; } } else if ( ! res . isNull ( "error_code" ) ) { state . transfer ( false ) ; LOGGER . warn ( "oauth get error, current state: " + state . toString ( ) ) ; } } | get OAuth access token synchronized function |
24,954 | protected JSONObject requestServer ( AipRequest request ) { AipResponse response = AipHttpClient . post ( request ) ; String resData = response . getBodyStr ( ) ; Integer status = response . getStatus ( ) ; if ( status . equals ( 200 ) && ! resData . equals ( "" ) ) { try { JSONObject res = new JSONObject ( resData ) ; if ( state . getState ( ) . equals ( EAuthState . STATE_POSSIBLE_CLOUD_USER ) ) { boolean cloudAuthState = res . isNull ( "error_code" ) || res . getInt ( "error_code" ) != AipClientConst . IAM_ERROR_CODE ; state . transfer ( cloudAuthState ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "state after cloud auth: " + state . toString ( ) ) ; } if ( ! cloudAuthState ) { return Util . getGeneralError ( AipClientConst . OPENAPI_NO_ACCESS_ERROR_CODE , AipClientConst . OPENAPI_NO_ACCESS_ERROR_MSG ) ; } } return res ; } catch ( JSONException e ) { return Util . getGeneralError ( - 1 , resData ) ; } } else { LOGGER . warn ( String . format ( "call failed! response status: %d, data: %s" , status , resData ) ) ; return AipError . NET_TIMEOUT_ERROR . toJsonResult ( ) ; } } | send request to server |
24,955 | public static JSONObject oauth ( String apiKey , String secretKey , AipClientConfiguration config ) { try { AipRequest request = new AipRequest ( ) ; request . setUri ( new URI ( AipClientConst . OAUTH_URL ) ) ; request . addBody ( "grant_type" , "client_credentials" ) ; request . addBody ( "client_id" , apiKey ) ; request . addBody ( "client_secret" , secretKey ) ; request . setConfig ( config ) ; int statusCode = 500 ; AipResponse response = null ; int cnt = 0 ; while ( statusCode == 500 && cnt < 3 ) { response = AipHttpClient . post ( request ) ; statusCode = response . getStatus ( ) ; cnt ++ ; } String res = response . getBodyStr ( ) ; if ( res != null && ! res . equals ( "" ) ) { return new JSONObject ( res ) ; } else { return Util . getGeneralError ( statusCode , "Server response code: " + statusCode ) ; } } catch ( URISyntaxException e ) { e . printStackTrace ( ) ; } return Util . getGeneralError ( - 1 , "unknown error" ) ; } | get access_token from openapi |
24,956 | public static String encode ( byte [ ] from ) { StringBuilder to = new StringBuilder ( ( int ) ( from . length * 1.34 ) + 3 ) ; int num = 0 ; char currentByte = 0 ; for ( int i = 0 ; i < from . length ; i ++ ) { num = num % 8 ; while ( num < 8 ) { switch ( num ) { case 0 : currentByte = ( char ) ( from [ i ] & lead6byte ) ; currentByte = ( char ) ( currentByte >>> 2 ) ; break ; case 2 : currentByte = ( char ) ( from [ i ] & last6byte ) ; break ; case 4 : currentByte = ( char ) ( from [ i ] & last4byte ) ; currentByte = ( char ) ( currentByte << 2 ) ; if ( ( i + 1 ) < from . length ) { currentByte |= ( from [ i + 1 ] & lead2byte ) >>> 6 ; } break ; case 6 : currentByte = ( char ) ( from [ i ] & last2byte ) ; currentByte = ( char ) ( currentByte << 4 ) ; if ( ( i + 1 ) < from . length ) { currentByte |= ( from [ i + 1 ] & lead4byte ) >>> 4 ; } break ; default : break ; } to . append ( encodeTable [ currentByte ] ) ; num += 6 ; } } if ( to . length ( ) % 4 != 0 ) { for ( int i = 4 - to . length ( ) % 4 ; i > 0 ; i -- ) { to . append ( "=" ) ; } } return to . toString ( ) ; } | Base64 encoding . |
24,957 | public void onBindViewHolder ( RecyclerView . ViewHolder viewHolder , int position , List < Object > payloads ) { Object tag = viewHolder . itemView . getTag ( R . id . fastadapter_item_adapter ) ; if ( tag instanceof FastAdapter ) { FastAdapter fastAdapter = ( ( FastAdapter ) tag ) ; IItem item = fastAdapter . getItem ( position ) ; if ( item != null ) { item . bindView ( viewHolder , payloads ) ; if ( viewHolder instanceof FastAdapter . ViewHolder ) { ( ( FastAdapter . ViewHolder ) viewHolder ) . bindView ( item , payloads ) ; } viewHolder . itemView . setTag ( R . id . fastadapter_item , item ) ; } } } | is called in onBindViewHolder to bind the data on the ViewHolder |
24,958 | public void unBindViewHolder ( RecyclerView . ViewHolder viewHolder , int position ) { IItem item = FastAdapter . getHolderAdapterItemTag ( viewHolder ) ; if ( item != null ) { item . unbindView ( viewHolder ) ; if ( viewHolder instanceof FastAdapter . ViewHolder ) { ( ( FastAdapter . ViewHolder ) viewHolder ) . unbindView ( item ) ; } viewHolder . itemView . setTag ( R . id . fastadapter_item , null ) ; viewHolder . itemView . setTag ( R . id . fastadapter_item_adapter , null ) ; } else { Log . e ( "FastAdapter" , "The bindView method of this item should set the `Tag` on its itemView (https://github.com/mikepenz/FastAdapter/blob/develop/library-core/src/main/java/com/mikepenz/fastadapter/items/AbstractItem.java#L189)" ) ; } } | is called in onViewRecycled to unbind the data on the ViewHolder |
24,959 | public void onViewAttachedToWindow ( RecyclerView . ViewHolder viewHolder , int position ) { IItem item = FastAdapter . getHolderAdapterItem ( viewHolder , position ) ; if ( item != null ) { try { item . attachToWindow ( viewHolder ) ; if ( viewHolder instanceof FastAdapter . ViewHolder ) { ( ( FastAdapter . ViewHolder ) viewHolder ) . attachToWindow ( item ) ; } } catch ( AbstractMethodError e ) { Log . e ( "FastAdapter" , e . toString ( ) ) ; } } } | is called in onViewAttachedToWindow when the view is detached from the window |
24,960 | public void onViewDetachedFromWindow ( RecyclerView . ViewHolder viewHolder , int position ) { IItem item = FastAdapter . getHolderAdapterItemTag ( viewHolder ) ; if ( item != null ) { item . detachFromWindow ( viewHolder ) ; if ( viewHolder instanceof FastAdapter . ViewHolder ) { ( ( FastAdapter . ViewHolder ) viewHolder ) . detachFromWindow ( item ) ; } } } | is called in onViewDetachedFromWindow when the view is detached from the window |
24,961 | public RecyclerView . ViewHolder onPreCreateViewHolder ( FastAdapter < Item > fastAdapter , ViewGroup parent , int viewType ) { return fastAdapter . getTypeInstance ( viewType ) . getViewHolder ( parent ) ; } | is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp |
24,962 | public RecyclerView . ViewHolder onPostCreateViewHolder ( FastAdapter < Item > fastAdapter , RecyclerView . ViewHolder viewHolder ) { EventHookUtil . bind ( viewHolder , fastAdapter . getEventHooks ( ) ) ; return viewHolder ; } | is called after the viewHolder was created and the default listeners were added |
24,963 | private void setItemOffsetsForHeader ( Rect itemOffsets , View header , int orientation ) { mDimensionCalculator . initMargins ( mTempRect , header ) ; if ( orientation == LinearLayoutManager . VERTICAL ) { itemOffsets . top = header . getHeight ( ) + mTempRect . top + mTempRect . bottom ; } else { itemOffsets . left = header . getWidth ( ) + mTempRect . left + mTempRect . right ; } } | Sets the offsets for the first item in a section to make room for the header view |
24,964 | public ItemFilter < Model , Item > withFilterPredicate ( IItemAdapter . Predicate < Item > filterPredicate ) { this . mFilterPredicate = filterPredicate ; return this ; } | define the predicate used to filter the list inside the ItemFilter |
24,965 | public int getAdapterPosition ( long identifier ) { for ( int i = 0 , size = mOriginalItems . size ( ) ; i < size ; i ++ ) { if ( mOriginalItems . get ( i ) . getIdentifier ( ) == identifier ) { return i ; } } return - 1 ; } | Searches for the given identifier and calculates its relative position |
24,966 | public ModelAdapter < ? , Item > add ( List < Item > items ) { if ( mOriginalItems != null && items . size ( ) > 0 ) { if ( mItemAdapter . isUseIdDistributor ( ) ) { mItemAdapter . getIdDistributor ( ) . checkIds ( items ) ; } mOriginalItems . addAll ( items ) ; publishResults ( mConstraint , performFiltering ( mConstraint ) ) ; return mItemAdapter ; } else { return mItemAdapter . addInternal ( items ) ; } } | add a list of items to the end of the existing items will prior check if we are currently filtering |
24,967 | public ModelAdapter < ? , Item > clear ( ) { if ( mOriginalItems != null ) { mOriginalItems . clear ( ) ; publishResults ( mConstraint , performFiltering ( mConstraint ) ) ; return mItemAdapter ; } else { return mItemAdapter . clear ( ) ; } } | removes all items of this adapter |
24,968 | public static void bindDragHandle ( final RecyclerView . ViewHolder holder , final IExtendedDraggable item ) { if ( item . getTouchHelper ( ) != null && item . getDragView ( holder ) != null ) { item . getDragView ( holder ) . setOnTouchListener ( new View . OnTouchListener ( ) { public boolean onTouch ( View v , MotionEvent event ) { if ( MotionEventCompat . getActionMasked ( event ) == MotionEvent . ACTION_DOWN ) { if ( item . isDraggable ( ) ) item . getTouchHelper ( ) . startDrag ( holder ) ; } return false ; } } ) ; } } | this functions binds the view s touch listener to start the drag via the touch helper ... |
24,969 | public static < Item extends IItem > void bind ( RecyclerView . ViewHolder viewHolder , final List < EventHook < Item > > eventHooks ) { if ( eventHooks == null ) { return ; } for ( final EventHook < Item > event : eventHooks ) { View view = event . onBind ( viewHolder ) ; if ( view != null ) { attachToView ( event , viewHolder , view ) ; } List < ? extends View > views = event . onBindMany ( viewHolder ) ; if ( views != null ) { for ( View v : views ) { attachToView ( event , viewHolder , v ) ; } } } } | binds the hooks to the viewHolder |
24,970 | public static < Item extends IItem > void attachToView ( final EventHook < Item > event , final RecyclerView . ViewHolder viewHolder , View view ) { if ( event instanceof ClickEventHook ) { view . setOnClickListener ( new View . OnClickListener ( ) { public void onClick ( View v ) { Object tagAdapter = viewHolder . itemView . getTag ( R . id . fastadapter_item_adapter ) ; if ( tagAdapter instanceof FastAdapter ) { FastAdapter < Item > adapter = ( FastAdapter < Item > ) tagAdapter ; int pos = adapter . getHolderAdapterPosition ( viewHolder ) ; if ( pos != RecyclerView . NO_POSITION ) { Item item = adapter . getItem ( pos ) ; if ( item != null ) { ( ( ClickEventHook < Item > ) event ) . onClick ( v , pos , adapter , item ) ; } } } } } ) ; } else if ( event instanceof LongClickEventHook ) { view . setOnLongClickListener ( new View . OnLongClickListener ( ) { public boolean onLongClick ( View v ) { Object tagAdapter = viewHolder . itemView . getTag ( R . id . fastadapter_item_adapter ) ; if ( tagAdapter instanceof FastAdapter ) { FastAdapter < Item > adapter = ( FastAdapter < Item > ) tagAdapter ; int pos = adapter . getHolderAdapterPosition ( viewHolder ) ; if ( pos != RecyclerView . NO_POSITION ) { Item item = adapter . getItem ( pos ) ; if ( item != null ) { return ( ( LongClickEventHook < Item > ) event ) . onLongClick ( v , pos , adapter , item ) ; } } } return false ; } } ) ; } else if ( event instanceof TouchEventHook ) { view . setOnTouchListener ( new View . OnTouchListener ( ) { public boolean onTouch ( View v , MotionEvent e ) { Object tagAdapter = viewHolder . itemView . getTag ( R . id . fastadapter_item_adapter ) ; if ( tagAdapter instanceof FastAdapter ) { FastAdapter < Item > adapter = ( FastAdapter < Item > ) tagAdapter ; int pos = adapter . getHolderAdapterPosition ( viewHolder ) ; if ( pos != RecyclerView . NO_POSITION ) { Item item = adapter . getItem ( pos ) ; if ( item != null ) { return ( ( TouchEventHook < Item > ) event ) . onTouch ( v , e , pos , adapter , item ) ; } } } return false ; } } ) ; } else if ( event instanceof CustomEventHook ) { ( ( CustomEventHook < Item > ) event ) . attachEvent ( view , viewHolder ) ; } } | attaches the specific event to a view |
24,971 | public boolean onLongClick ( int index , boolean selectItem ) { if ( mLastLongPressIndex == null ) { if ( mFastAdapter . getAdapterItem ( index ) . isSelectable ( ) ) { mLastLongPressIndex = index ; if ( selectItem ) mFastAdapter . select ( index ) ; if ( mActionModeHelper != null ) mActionModeHelper . checkActionMode ( null ) ; return true ; } } else if ( mLastLongPressIndex != index ) { selectRange ( mLastLongPressIndex , index , true ) ; mLastLongPressIndex = null ; } return false ; } | will take care to save the long pressed index or to select all items in the range between the current long pressed item and the last long pressed item |
24,972 | public RangeSelectorHelper withSavedInstanceState ( Bundle savedInstanceState , String prefix ) { if ( savedInstanceState != null && savedInstanceState . containsKey ( BUNDLE_LAST_LONG_PRESS + prefix ) ) mLastLongPressIndex = savedInstanceState . getInt ( BUNDLE_LAST_LONG_PRESS + prefix ) ; return this ; } | restore the index of the last long pressed index IMPORTANT! Call this method only after all items where added to the adapters again . Otherwise it may select wrong items! |
24,973 | private static void collapseIfPossible ( FastAdapter fastAdapter ) { try { Class c = Class . forName ( "com.mikepenz.fastadapter.expandable.ExpandableExtension" ) ; if ( c != null ) { IAdapterExtension extension = fastAdapter . getExtension ( c ) ; if ( extension != null ) { Method method = extension . getClass ( ) . getMethod ( "collapse" ) ; method . invoke ( extension ) ; } } } catch ( Exception ignored ) { } } | Uses Reflection to collapse all items if this adapter uses expandable items |
24,974 | public int getItemViewType ( int position ) { if ( shouldInsertItemAtPosition ( position ) ) { return getItem ( position ) . getType ( ) ; } else { return mAdapter . getItemViewType ( position - itemInsertedBeforeCount ( position ) ) ; } } | overwrite the getItemViewType to correctly return the value from the FastAdapter |
24,975 | public long getItemId ( int position ) { if ( shouldInsertItemAtPosition ( position ) ) { return getItem ( position ) . getIdentifier ( ) ; } else { return mAdapter . getItemId ( position - itemInsertedBeforeCount ( position ) ) ; } } | overwrite the getItemId to correctly return the value from the FastAdapter |
24,976 | public Item getItem ( int position ) { if ( shouldInsertItemAtPosition ( position ) ) { return mItems . get ( itemInsertedBeforeCount ( position - 1 ) ) ; } return null ; } | make sure we return the Item from the FastAdapter so we retrieve the item from all adapters |
24,977 | public SparseIntArray getExpanded ( ) { SparseIntArray expandedItems = new SparseIntArray ( ) ; Item item ; for ( int i = 0 , size = mFastAdapter . getItemCount ( ) ; i < size ; i ++ ) { item = mFastAdapter . getItem ( i ) ; if ( item instanceof IExpandable && ( ( IExpandable ) item ) . isExpanded ( ) ) { expandedItems . put ( i , ( ( IExpandable ) item ) . getSubItems ( ) . size ( ) ) ; } } return expandedItems ; } | returns the expanded items this contains position and the count of items which are expanded by this position |
24,978 | public void toggleExpandable ( int position ) { Item item = mFastAdapter . getItem ( position ) ; if ( item instanceof IExpandable && ( ( IExpandable ) item ) . isExpanded ( ) ) { collapse ( position ) ; } else { expand ( position ) ; } } | toggles the expanded state of the given expandable item at the given position |
24,979 | public void collapse ( boolean notifyItemChanged ) { int [ ] expandedItems = getExpandedItems ( ) ; for ( int i = expandedItems . length - 1 ; i >= 0 ; i -- ) { collapse ( expandedItems [ i ] , notifyItemChanged ) ; } } | collapses all expanded items |
24,980 | public void expand ( boolean notifyItemChanged ) { int length = mFastAdapter . getItemCount ( ) ; for ( int i = length - 1 ; i >= 0 ; i -- ) { expand ( i , notifyItemChanged ) ; } } | expands all expandable items |
24,981 | public void expand ( int position , boolean notifyItemChanged ) { Item item = mFastAdapter . getItem ( position ) ; if ( item != null && item instanceof IExpandable ) { IExpandable expandable = ( IExpandable ) item ; if ( ! expandable . isExpanded ( ) && expandable . getSubItems ( ) != null && expandable . getSubItems ( ) . size ( ) > 0 ) { IAdapter < Item > adapter = mFastAdapter . getAdapter ( position ) ; if ( adapter != null && adapter instanceof IItemAdapter ) { ( ( IItemAdapter < ? , Item > ) adapter ) . addInternal ( position + 1 , expandable . getSubItems ( ) ) ; } expandable . withIsExpanded ( true ) ; if ( notifyItemChanged ) { mFastAdapter . notifyItemChanged ( position ) ; } } } } | opens the expandable item at the given position |
24,982 | public int getExpandedItemsCount ( int from , int position ) { int totalAddedItems = 0 ; Item tmp ; for ( int i = from ; i < position ; i ++ ) { tmp = mFastAdapter . getItem ( i ) ; if ( tmp instanceof IExpandable ) { IExpandable tmpExpandable = ( ( IExpandable ) tmp ) ; if ( tmpExpandable . getSubItems ( ) != null && tmpExpandable . isExpanded ( ) ) { totalAddedItems = totalAddedItems + tmpExpandable . getSubItems ( ) . size ( ) ; } } } return totalAddedItems ; } | calculates the count of expandable items before a given position |
24,983 | public void deselect ( ) { SelectExtension < Item > selectExtension = mFastAdapter . getExtension ( SelectExtension . class ) ; if ( selectExtension == null ) { return ; } for ( Item item : AdapterUtil . getAllItems ( mFastAdapter ) ) { selectExtension . deselect ( item ) ; } mFastAdapter . notifyDataSetChanged ( ) ; } | deselects all selections |
24,984 | public View generateView ( Context ctx ) { VH viewHolder = getViewHolder ( createView ( ctx , null ) ) ; bindView ( viewHolder , Collections . EMPTY_LIST ) ; return viewHolder . itemView ; } | generates a view by the defined LayoutRes |
24,985 | public VH getViewHolder ( ViewGroup parent ) { return getViewHolder ( createView ( parent . getContext ( ) , parent ) ) ; } | Generates a ViewHolder from this Item with the given parent |
24,986 | public static < Model , Item extends IItem > ModelAdapter < Model , Item > models ( IInterceptor < Model , Item > interceptor ) { return new ModelAdapter < > ( interceptor ) ; } | static method to retrieve a new ItemAdapter |
24,987 | public List < Item > intercept ( List < Model > models ) { List < Item > items = new ArrayList < > ( models . size ( ) ) ; Item item ; for ( Model model : models ) { item = intercept ( model ) ; if ( item == null ) continue ; items . add ( item ) ; } return items ; } | Generates a List of Item based on it s List of Model using the interceptor |
24,988 | public ModelAdapter < Model , Item > withItemFilter ( ItemFilter < Model , Item > itemFilter ) { this . mItemFilter = itemFilter ; return this ; } | allows you to define your own Filter implementation instead of the default ItemFilter |
24,989 | public List < Model > getModels ( ) { ArrayList < Model > list = new ArrayList < > ( mItems . size ( ) ) ; for ( Item item : mItems . getItems ( ) ) { if ( mReverseInterceptor != null ) { list . add ( mReverseInterceptor . intercept ( item ) ) ; } else if ( item instanceof IModelItem ) { list . add ( ( Model ) ( ( IModelItem ) item ) . getModel ( ) ) ; } else { throw new RuntimeException ( "to get the list of models, the item either needs to implement `IModelItem` or you have to provide a `reverseInterceptor`" ) ; } } return list ; } | the ModelAdapter does not keep a list of input model s to get retrieve them a reverseInterceptor is required usually it is used to get the Model from a IModelItem |
24,990 | public final ModelAdapter < Model , Item > add ( Model ... items ) { return add ( asList ( items ) ) ; } | add an array of items to the end of the existing items |
24,991 | public ModelAdapter < Model , Item > add ( List < Model > list ) { List < Item > items = intercept ( list ) ; return addInternal ( items ) ; } | add a list of items to the end of the existing items |
24,992 | public FastAdapterDialog < Item > withOnClickListener ( com . mikepenz . fastadapter . listeners . OnClickListener < Item > onClickListener ) { this . mFastAdapter . withOnClickListener ( onClickListener ) ; return this ; } | Define the OnClickListener which will be used for a single item |
24,993 | private List < SimpleItem > generateUnsortedList ( ) { ArrayList < SimpleItem > result = new ArrayList < > ( 26 ) ; for ( int i = 0 ; i < 26 ; i ++ ) { result . add ( makeItem ( i ) ) ; } Collections . shuffle ( result ) ; return result ; } | Generates a simple list consisting of the letters of the alphabet unordered on purpose . |
24,994 | private SimpleItem makeItem ( @ IntRange ( from = 0 , to = 25 ) int position ) { SimpleItem result = new SimpleItem ( ) ; result . withName ( ALPHABET [ position ] ) ; position ++ ; String description = "The " + ( position ) ; if ( position == 1 || position == 21 ) { description += "st" ; } else if ( position == 2 || position == 22 ) { description += "nd" ; } else if ( position == 3 || position == 23 ) { description += "rd" ; } else { description += "th" ; } return result . withDescription ( description + " letter in the alphabet" ) ; } | Build a simple item with one letter of the alphabet . |
24,995 | public View generateView ( Context ctx , ViewGroup parent ) { ViewHolder viewHolder = getViewHolder ( LayoutInflater . from ( ctx ) . inflate ( getLayoutRes ( ) , parent , false ) ) ; bindView ( viewHolder , Collections . EMPTY_LIST ) ; return viewHolder . itemView ; } | generates a view by the defined LayoutRes and pass the LayoutParams from the parent |
24,996 | public Boolean onClick ( AppCompatActivity act , IItem item ) { if ( mActionMode != null && ( mSelectExtension . getSelectedItems ( ) . size ( ) == 1 ) && item . isSelected ( ) ) { mActionMode . finish ( ) ; mSelectExtension . deselect ( ) ; return true ; } if ( mActionMode != null ) { int selected = mSelectExtension . getSelectedItems ( ) . size ( ) ; if ( item . isSelected ( ) ) selected -- ; else if ( item . isSelectable ( ) ) selected ++ ; checkActionMode ( act , selected ) ; } return null ; } | implements the basic behavior of a CAB and multi select behavior including logics if the clicked item is collapsible |
24,997 | public ActionMode onLongClick ( AppCompatActivity act , int position ) { if ( mActionMode == null && mFastAdapter . getItem ( position ) . isSelectable ( ) ) { mActionMode = act . startSupportActionMode ( mInternalCallback ) ; mSelectExtension . select ( position ) ; checkActionMode ( act , 1 ) ; return mActionMode ; } return mActionMode ; } | implements the basic behavior of a CAB and multi select behavior onLongClick |
24,998 | public ActionMode checkActionMode ( AppCompatActivity act ) { int selected = mSelectExtension . getSelectedItems ( ) . size ( ) ; return checkActionMode ( act , selected ) ; } | check if the ActionMode should be shown or not depending on the currently selected items Additionally it will also update the title in the CAB for you |
24,999 | private void updateTitle ( int selected ) { if ( mActionMode != null ) { if ( mTitleProvider != null ) mActionMode . setTitle ( mTitleProvider . getTitle ( selected ) ) ; else mActionMode . setTitle ( String . valueOf ( selected ) ) ; } } | updates the title to reflect the current selected items or to show a user defined title |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.