idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
7,700 | private static void mkdir ( final File directory , final boolean createParents ) throws IOException { Condition . INSTANCE . ensureNotNull ( directory , "The directory may not be null" ) ; boolean result = createParents ? directory . mkdirs ( ) : directory . mkdir ( ) ; if ( ! result && ! directory . exists ( ) ) { throw new IOException ( "Failed to create directory \"" + directory + "\"" ) ; } } | Creates a specific directory if it does not already exist . |
7,701 | public static void deleteRecursively ( final File file ) throws IOException { Condition . INSTANCE . ensureNotNull ( file , "The file or directory may not be null" ) ; if ( file . isDirectory ( ) ) { for ( File child : file . listFiles ( ) ) { deleteRecursively ( child ) ; } } delete ( file ) ; } | Deletes a specific file or directory . If the file is a directory all contained files and subdirectories are deleted recursively . |
7,702 | public static void createNewFile ( final File file , final boolean overwrite ) throws IOException { Condition . INSTANCE . ensureNotNull ( file , "The file may not be null" ) ; boolean result = file . createNewFile ( ) ; if ( ! result ) { if ( overwrite ) { try { delete ( file ) ; createNewFile ( file , false ) ; } catch ( IOException e ) { throw new IOException ( "Failed to overwrite file \"" + file + "\"" ) ; } } else if ( file . exists ( ) ) { throw new IOException ( "File \"" + file + "\" does already exist" ) ; } else { throw new IllegalArgumentException ( "The file must not be a directory" ) ; } } } | Creates a new empty file . |
7,703 | public void maybeDoOffset ( ) { long seen = tuplesSeen ; if ( offsetCommitInterval > 0 && seen % offsetCommitInterval == 0 && offsetStorage != null && fp . supportsOffsetManagement ( ) ) { doOffsetInternal ( ) ; } } | To do offset storage we let the topology drain itself out . Then we commit . |
7,704 | private static TypedArray obtainStyledAttributes ( final Context context , final int themeResourceId , final int resourceId ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Theme theme = context . getTheme ( ) ; int [ ] attrs = new int [ ] { resourceId } ; if ( themeResourceId != - 1 ) { return theme . obtainStyledAttributes ( themeResourceId , attrs ) ; } else { return theme . obtainStyledAttributes ( attrs ) ; } } | Obtains the attribute which corresponds to a specific resource id from a theme . |
7,705 | public static boolean getBoolean ( final Context context , final int themeResourceId , final int resourceId ) { TypedArray typedArray = null ; try { typedArray = obtainStyledAttributes ( context , themeResourceId , resourceId ) ; return typedArray . getBoolean ( 0 , false ) ; } finally { if ( typedArray != null ) { typedArray . recycle ( ) ; } } } | Obtains the boolean value which corresponds to a specific resource id from a specific theme . |
7,706 | public static boolean getBoolean ( final Context context , final int resourceId , final boolean defaultValue ) { return getBoolean ( context , - 1 , resourceId , defaultValue ) ; } | Obtains the boolean value which corresponds to a specific resource id from a context s theme . |
7,707 | public static int getInt ( final Context context , final int resourceId , final int defaultValue ) { return getInt ( context , - 1 , resourceId , defaultValue ) ; } | Obtains the integer value which corresponds to a specific resource id from a context s theme . |
7,708 | public static float getFloat ( final Context context , final int resourceId , final float defaultValue ) { return getFloat ( context , - 1 , resourceId , defaultValue ) ; } | Obtains the float value which corresponds to a specific resource id from a context s theme . |
7,709 | public static int getResId ( final Context context , final int resourceId , final int defaultValue ) { return getResId ( context , - 1 , resourceId , defaultValue ) ; } | Obtains the resource id which corresponds to a specific resource id from a context s theme . |
7,710 | void setRequest ( HttpUriRequest request ) { requestLock . lock ( ) ; try { if ( this . request != null ) { throw new SparqlException ( "Command is already executing a request." ) ; } this . request = request ; } finally { requestLock . unlock ( ) ; } } | Sets the currently executing request . |
7,711 | private Result execute ( ResultType cmdType ) throws SparqlException { String mimeType = contentType ; if ( mimeType != null && ! ResultFactory . supports ( mimeType , cmdType ) ) { logger . warn ( "Requested MIME content type '{}' does not support expected response type: {}" , mimeType , cmdType ) ; mimeType = null ; } if ( mimeType == null ) { mimeType = ResultFactory . getDefaultMediaType ( cmdType ) ; } if ( logger . isDebugEnabled ( ) ) { logRequest ( cmdType , mimeType ) ; } try { HttpResponse response = SparqlCall . executeRequest ( this , mimeType ) ; return ResultFactory . getResult ( this , response , cmdType ) ; } catch ( Throwable t ) { release ( ) ; throw SparqlException . convert ( "Error creating SPARQL result from server response" , t ) ; } } | Executes the request and parses the response . |
7,712 | private void logRequest ( ResultType cmdType , String mimeType ) { StringBuilder sb = new StringBuilder ( "Executing SPARQL protocol request " ) ; sb . append ( "to endpoint <" ) . append ( ( ( ProtocolDataSource ) getConnection ( ) . getDataSource ( ) ) . getUrl ( ) ) . append ( "> " ) ; if ( mimeType != null ) { sb . append ( "for content type '" ) . append ( mimeType ) . append ( "' " ) ; } else { sb . append ( "for unknown content type " ) ; } if ( cmdType != null ) { sb . append ( "with expected results of type " ) . append ( cmdType ) . append ( "." ) ; } else { sb . append ( "with unknown expected result type." ) ; } logger . debug ( sb . toString ( ) ) ; } | Log the enpoint URL and request parameters . |
7,713 | public void initialize ( ) { thread = new Thread ( collectorProcessor ) ; thread . start ( ) ; for ( DriverNode dn : this . children ) { dn . initialize ( ) ; } } | initialize driver node and all children of the node |
7,714 | public void addChild ( DriverNode dn ) { collectorProcessor . getChildren ( ) . add ( dn . operator ) ; children . add ( dn ) ; } | Method adds a child data node and binds the collect processor of this node to the operator of the next node |
7,715 | public static String getNamespace ( JsonNode node ) { JsonNode nodeNs = obj ( node ) . get ( ID_NAMESPACE ) ; return ( nodeNs != null ) ? nodeNs . asText ( ) : null ; } | Returns the namespace from a wrapped JsonNode |
7,716 | public static void setVersion ( JsonNode node , Long version ) { obj ( node ) . put ( ID_VERSION , version ) ; } | Sets the version on a wrapped JsonNode |
7,717 | public static Date getTimestamp ( JsonNode node ) { String text = obj ( node ) . get ( ID_TIMESTAMP ) . asText ( ) ; return isNotBlank ( text ) ? from ( instantUtc ( text ) ) . toDate ( ) : null ; } | Returns the timestamp from a wrapped JsonNode |
7,718 | public final void update ( final float position ) { if ( reset ) { reset = false ; distance = 0 ; thresholdReachedPosition = - 1 ; dragStartTime = - 1 ; dragStartPosition = position ; reachedThreshold = false ; minDragDistance = 0 ; maxDragDistance = 0 ; } if ( ! reachedThreshold ) { if ( reachedThreshold ( position - dragStartPosition ) ) { dragStartTime = System . currentTimeMillis ( ) ; reachedThreshold = true ; thresholdReachedPosition = position ; } } else { float newDistance = position - thresholdReachedPosition ; if ( minDragDistance != 0 && minDragDistance > newDistance ) { newDistance = minDragDistance ; thresholdReachedPosition = position - minDragDistance ; } if ( maxDragDistance != 0 && maxDragDistance < newDistance ) { newDistance = maxDragDistance ; thresholdReachedPosition = position - maxDragDistance ; } distance = newDistance ; } } | Updates the instance by adding a new position . This will cause all properties to be re - calculated depending on the new position . |
7,719 | public final void setMaxDragDistance ( final float maxDragDistance ) { if ( maxDragDistance != 0 ) { Condition . INSTANCE . ensureGreater ( maxDragDistance , threshold , "The maximum drag distance must be greater than " + threshold ) ; } this . maxDragDistance = maxDragDistance ; } | Sets the maximum drag distance . |
7,720 | public final void setMinDragDistance ( final float minDragDistance ) { if ( minDragDistance != 0 ) { Condition . INSTANCE . ensureSmaller ( minDragDistance , - threshold , "The minimum drag distance must be smaller than " + - threshold ) ; } this . minDragDistance = minDragDistance ; } | Sets the minimum drag distance . |
7,721 | public final float getDragSpeed ( ) { if ( hasThresholdBeenReached ( ) ) { long interval = System . currentTimeMillis ( ) - dragStartTime ; return Math . abs ( getDragDistance ( ) ) / ( float ) interval ; } else { return - 1 ; } } | Returns the speed of the drag gesture in pixels per millisecond . |
7,722 | private OnSeekBarChangeListener createSeekBarListener ( ) { return new OnSeekBarChangeListener ( ) { public void onProgressChanged ( final SeekBar seekBar , final int progress , final boolean fromUser ) { adaptElevation ( progress , parallelLightCheckBox . isChecked ( ) ) ; } public void onStartTrackingTouch ( final SeekBar seekBar ) { } public void onStopTrackingTouch ( final SeekBar seekBar ) { } } ; } | Creates and returns a listener which allows to adjust the elevation when the value of a seek bar has been changed . |
7,723 | private void adaptElevation ( final int elevation , final boolean parallelLight ) { elevationTextView . setText ( String . format ( getString ( R . string . elevation ) , elevation ) ) ; elevationLeft . setShadowElevation ( elevation ) ; elevationLeft . emulateParallelLight ( parallelLight ) ; elevationTopLeft . setShadowElevation ( elevation ) ; elevationTopLeft . emulateParallelLight ( parallelLight ) ; elevationTop . setShadowElevation ( elevation ) ; elevationTop . emulateParallelLight ( parallelLight ) ; elevationTopRight . setShadowElevation ( elevation ) ; elevationTopRight . emulateParallelLight ( parallelLight ) ; elevationRight . setShadowElevation ( elevation ) ; elevationRight . emulateParallelLight ( parallelLight ) ; elevationBottomRight . setShadowElevation ( elevation ) ; elevationBottomRight . emulateParallelLight ( parallelLight ) ; elevationBottom . setShadowElevation ( elevation ) ; elevationBottom . emulateParallelLight ( parallelLight ) ; elevationBottomLeft . setShadowElevation ( elevation ) ; elevationBottomLeft . emulateParallelLight ( parallelLight ) ; } | Adapts the elevation . |
7,724 | public Segment getSegment ( SEGMENT_TYPE segmentType ) { if ( segmentType == null ) { return null ; } if ( segmentType == SEGMENT_TYPE . LINEAR ) { return new LinearSegment ( ) ; } else if ( segmentType == SEGMENT_TYPE . SPATIAL ) { return new SpatialSegment ( ) ; } else if ( segmentType == SEGMENT_TYPE . TEMPORAL ) { return new TemporalSegment ( ) ; } else if ( segmentType == SEGMENT_TYPE . SPATIOTEMPORAL ) { return new SpatioTemporalSegment ( ) ; } return null ; } | use getShape method to get object of type shape |
7,725 | public String write ( T obj ) throws JsonProcessingException { Date ts = includeTimestamp ? Date . from ( now ( ) ) : null ; MetaWrapper wrapper = new MetaWrapper ( getHighestSourceVersion ( ) , getNamespace ( ) , obj , ts ) ; return mapper . writeValueAsString ( wrapper ) ; } | Serializes the given object to a String |
7,726 | private void obtainInsetForeground ( final TypedArray typedArray ) { int color = typedArray . getColor ( R . styleable . ScrimInsetsLayout_insetDrawable , - 1 ) ; if ( color == - 1 ) { Drawable drawable = typedArray . getDrawable ( R . styleable . ScrimInsetsLayout_insetDrawable ) ; if ( drawable != null ) { setInsetDrawable ( drawable ) ; } else { setInsetColor ( ContextCompat . getColor ( getContext ( ) , R . color . scrim_insets_layout_insets_drawable_default_value ) ) ; } } else { setInsetColor ( color ) ; } } | Obtains the drawable which should be shown in the layout s insets from a specific typed array . |
7,727 | public void parse ( final int nYear , final HolidayMap aHolidayMap , final Holidays aConfig ) { for ( final RelativeToEasterSunday aDay : aConfig . getRelativeToEasterSunday ( ) ) { if ( ! isValid ( aDay , nYear ) ) continue ; final ChronoLocalDate aEasterSunday = getEasterSunday ( nYear , aDay . getChronology ( ) ) ; aEasterSunday . plus ( aDay . getDays ( ) , ChronoUnit . DAYS ) ; final String sPropertiesKey = "christian." + aDay . getDescriptionPropertiesKey ( ) ; addChrstianHoliday ( aEasterSunday , sPropertiesKey , XMLHolidayHelper . getType ( aDay . getLocalizedType ( ) ) , aHolidayMap ) ; } } | Parses relative to Easter Sunday holidays . |
7,728 | protected final void addChrstianHoliday ( final ChronoLocalDate aDate , final String sPropertiesKey , final IHolidayType aHolidayType , final HolidayMap holidays ) { final LocalDate convertedDate = LocalDate . from ( aDate ) ; holidays . add ( convertedDate , new ResourceBundleHoliday ( aHolidayType , sPropertiesKey ) ) ; } | Adds the given day to the list of holidays . |
7,729 | public static ChronoLocalDate getEasterSunday ( final int nYear ) { return nYear <= CPDT . LAST_JULIAN_YEAR ? getJulianEasterSunday ( nYear ) : getGregorianEasterSunday ( nYear ) ; } | Returns the easter Sunday for a given year . |
7,730 | public static JulianDate getJulianEasterSunday ( final int nYear ) { final int a = nYear % 4 ; final int b = nYear % 7 ; final int c = nYear % 19 ; final int d = ( 19 * c + 15 ) % 30 ; final int e = ( 2 * a + 4 * b - d + 34 ) % 7 ; final int x = d + e + 114 ; final int nMonth = x / 31 ; final int nDay = ( x % 31 ) + 1 ; return JulianDate . of ( nYear , ( nMonth == 3 ? Month . MARCH : Month . APRIL ) . getValue ( ) , nDay ) ; } | Returns the easter Sunday within the julian chronology . |
7,731 | public static LocalDate getGregorianEasterSunday ( final int nYear ) { final int a = nYear % 19 ; final int b = nYear / 100 ; final int c = nYear % 100 ; final int d = b / 4 ; final int e = b % 4 ; final int f = ( b + 8 ) / 25 ; final int g = ( b - f + 1 ) / 3 ; final int h = ( 19 * a + b - d - g + 15 ) % 30 ; final int i = c / 4 ; final int j = c % 4 ; final int k = ( 32 + 2 * e + 2 * i - h - j ) % 7 ; final int l = ( a + 11 * h + 22 * k ) / 451 ; final int x = h + k - 7 * l + 114 ; final int nMonth = x / 31 ; final int nDay = ( x % 31 ) + 1 ; return LocalDate . of ( nYear , ( nMonth == 3 ? Month . MARCH : Month . APRIL ) , nDay ) ; } | Returns the easter Sunday within the gregorian chronology . |
7,732 | private static Bitmap createEdgeShadow ( final Context context , final int elevation , final Orientation orientation , final boolean parallelLight ) { if ( elevation == 0 ) { return null ; } else { float shadowWidth = getShadowWidth ( context , elevation , orientation , parallelLight ) ; int shadowColor = getShadowColor ( elevation , orientation , parallelLight ) ; int bitmapWidth = ( int ) Math . round ( ( orientation == Orientation . LEFT || orientation == Orientation . RIGHT ) ? Math . ceil ( shadowWidth ) : 1 ) ; int bitmapHeight = ( int ) Math . round ( ( orientation == Orientation . TOP || orientation == Orientation . BOTTOM ) ? Math . ceil ( shadowWidth ) : 1 ) ; Bitmap bitmap = Bitmap . createBitmap ( bitmapWidth , bitmapHeight , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( bitmap ) ; Shader linearGradient = createLinearGradient ( orientation , bitmapWidth , bitmapHeight , shadowWidth , shadowColor ) ; Paint paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; paint . setDither ( true ) ; paint . setShader ( linearGradient ) ; canvas . drawRect ( 0 , 0 , bitmapWidth , bitmapHeight , paint ) ; return bitmap ; } } | Creates and returns a bitmap which can be used to emulate a shadow which is located at a corner of an elevated view on pre - Lollipop devices . |
7,733 | private static Bitmap createCornerShadow ( final Context context , final int elevation , final Orientation orientation , final boolean parallelLight ) { if ( elevation == 0 ) { return null ; } else { float horizontalShadowWidth = getHorizontalShadowWidth ( context , elevation , orientation , parallelLight ) ; float verticalShadowWidth = getVerticalShadowWidth ( context , elevation , orientation , parallelLight ) ; int horizontalShadowColor = getHorizontalShadowColor ( elevation , orientation , parallelLight ) ; int verticalShadowColor = getVerticalShadowColor ( elevation , orientation , parallelLight ) ; int bitmapWidth = ( int ) Math . round ( Math . ceil ( verticalShadowWidth ) ) ; int bitmapHeight = ( int ) Math . round ( Math . ceil ( horizontalShadowWidth ) ) ; int bitmapSize = Math . max ( bitmapWidth , bitmapHeight ) ; Bitmap bitmap = Bitmap . createBitmap ( bitmapSize , bitmapSize , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( bitmap ) ; Paint paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; paint . setDither ( true ) ; RectF arcBounds = getCornerBounds ( orientation , bitmapSize ) ; float startAngle = getCornerAngle ( orientation ) ; int [ ] sweepColors = getCornerColors ( orientation , horizontalShadowColor , verticalShadowColor ) ; SweepGradient sweepGradient = new SweepGradient ( arcBounds . left + arcBounds . width ( ) / 2f , arcBounds . top + arcBounds . height ( ) / 2f , sweepColors , new float [ ] { startAngle / FULL_ARC_DEGRESS , startAngle / FULL_ARC_DEGRESS + QUARTER_ARC_DEGRESS / FULL_ARC_DEGRESS } ) ; paint . setShader ( sweepGradient ) ; canvas . drawArc ( arcBounds , startAngle , QUARTER_ARC_DEGRESS , true , paint ) ; Shader radialGradient = createRadialGradient ( orientation , bitmapSize , Math . max ( horizontalShadowWidth , verticalShadowWidth ) ) ; paint . setShader ( radialGradient ) ; paint . setColor ( Color . BLACK ) ; paint . setXfermode ( new PorterDuffXfermode ( PorterDuff . Mode . DST_OUT ) ) ; canvas . drawRect ( 0 , 0 , bitmapSize , bitmapSize , paint ) ; return BitmapUtil . resize ( bitmap , bitmapWidth , bitmapHeight ) ; } } | Creates and returns a bitmap which can be used to emulate a shadow which is located besides an edge of an elevated view on pre - Lollipop devices . |
7,734 | private static RectF getCornerBounds ( final Orientation orientation , final int size ) { switch ( orientation ) { case TOP_LEFT : return new RectF ( 0 , 0 , 2 * size , 2 * size ) ; case TOP_RIGHT : return new RectF ( - size , 0 , size , 2 * size ) ; case BOTTOM_LEFT : return new RectF ( 0 , - size , 2 * size , size ) ; case BOTTOM_RIGHT : return new RectF ( - size , - size , size , size ) ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Returns the bounds which should be used to draw a shadow which is located at a corner of an elevated view . |
7,735 | private static float getHorizontalShadowWidth ( final Context context , final int elevation , final Orientation orientation , final boolean parallelLight ) { switch ( orientation ) { case TOP_LEFT : case TOP_RIGHT : return getShadowWidth ( context , elevation , Orientation . TOP , parallelLight ) ; case BOTTOM_LEFT : case BOTTOM_RIGHT : return getShadowWidth ( context , elevation , Orientation . BOTTOM , parallelLight ) ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Returns the width of a shadow which is located next to a corner of an elevated view in horizontal direction . |
7,736 | private static float getShadowWidth ( final Context context , final int elevation , final Orientation orientation , final boolean parallelLight ) { float referenceElevationWidth = ( float ) elevation / ( float ) REFERENCE_ELEVATION * REFERENCE_SHADOW_WIDTH ; float shadowWidth ; if ( parallelLight ) { shadowWidth = referenceElevationWidth * BOTTOM_SCALE_FACTOR ; } else { switch ( orientation ) { case LEFT : shadowWidth = referenceElevationWidth * LEFT_SCALE_FACTOR ; break ; case TOP : shadowWidth = referenceElevationWidth * TOP_SCALE_FACTOR ; break ; case RIGHT : shadowWidth = referenceElevationWidth * RIGHT_SCALE_FACTOR ; break ; case BOTTOM : shadowWidth = referenceElevationWidth * BOTTOM_SCALE_FACTOR ; break ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } return dpToPixels ( context , shadowWidth ) ; } | Returns the width of a shadow which is located besides an edge of an elevated view . |
7,737 | private static int getHorizontalShadowColor ( final int elevation , final Orientation orientation , final boolean parallelLight ) { switch ( orientation ) { case TOP_LEFT : case TOP_RIGHT : return getShadowColor ( elevation , Orientation . TOP , parallelLight ) ; case BOTTOM_LEFT : case BOTTOM_RIGHT : return getShadowColor ( elevation , Orientation . BOTTOM , parallelLight ) ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Returns the color of a shadow which is located next to a corner of an elevated view in horizontal direction . |
7,738 | private static int getVerticalShadowColor ( final int elevation , final Orientation orientation , final boolean parallelLight ) { switch ( orientation ) { case TOP_LEFT : case BOTTOM_LEFT : return getShadowColor ( elevation , Orientation . LEFT , parallelLight ) ; case TOP_RIGHT : case BOTTOM_RIGHT : return getShadowColor ( elevation , Orientation . RIGHT , parallelLight ) ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Returns the color of a shadow which is located next to a corner of an elevated view in vertical direction . |
7,739 | private static int getShadowColor ( final int elevation , final Orientation orientation , final boolean parallelLight ) { int alpha ; if ( parallelLight ) { alpha = getShadowAlpha ( elevation , MIN_BOTTOM_ALPHA , MAX_BOTTOM_ALPHA ) ; } else { switch ( orientation ) { case LEFT : alpha = getShadowAlpha ( elevation , MIN_LEFT_ALPHA , MAX_LEFT_ALPHA ) ; break ; case TOP : alpha = getShadowAlpha ( elevation , MIN_TOP_ALPHA , MAX_TOP_ALPHA ) ; break ; case RIGHT : alpha = getShadowAlpha ( elevation , MIN_RIGHT_ALPHA , MAX_RIGHT_ALPHA ) ; break ; case BOTTOM : alpha = getShadowAlpha ( elevation , MIN_BOTTOM_ALPHA , MAX_BOTTOM_ALPHA ) ; break ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } return Color . argb ( alpha , 0 , 0 , 0 ) ; } | Returns the color of a shadow which is located besides an edge of an elevated view . |
7,740 | private static int getShadowAlpha ( final int elevation , final int minTransparency , final int maxTransparency ) { float ratio = ( float ) elevation / ( float ) MAX_ELEVATION ; int range = maxTransparency - minTransparency ; return Math . round ( minTransparency + ratio * range ) ; } | Returns the alpha value of a shadow by interpolating between a minimum and maximum alpha value depending on a specific elevation . |
7,741 | private static Shader createLinearGradient ( final Orientation orientation , final int bitmapWidth , final int bitmapHeight , final float shadowWidth , final int shadowColor ) { RectF bounds = new RectF ( ) ; switch ( orientation ) { case LEFT : bounds . left = bitmapWidth ; bounds . right = bitmapWidth - shadowWidth ; break ; case TOP : bounds . top = bitmapHeight ; bounds . bottom = bitmapHeight - shadowWidth ; break ; case RIGHT : bounds . right = shadowWidth ; break ; case BOTTOM : bounds . bottom = shadowWidth ; break ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } return new LinearGradient ( bounds . left , bounds . top , bounds . right , bounds . bottom , shadowColor , Color . TRANSPARENT , Shader . TileMode . CLAMP ) ; } | Creates and returns a shader which can be used to draw a shadow which located besides an edge of an elevated view . |
7,742 | private static Shader createRadialGradient ( final Orientation orientation , final int bitmapSize , final float radius ) { PointF center = new PointF ( ) ; switch ( orientation ) { case TOP_LEFT : center . x = bitmapSize ; center . y = bitmapSize ; break ; case TOP_RIGHT : center . y = bitmapSize ; break ; case BOTTOM_LEFT : center . x = bitmapSize ; break ; case BOTTOM_RIGHT : break ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } return new RadialGradient ( center . x , center . y , radius , Color . TRANSPARENT , Color . BLACK , Shader . TileMode . CLAMP ) ; } | Creates and returns a shader which can be used to draw a shadow which located at a corner of an elevated view . |
7,743 | private static float getCornerAngle ( final Orientation orientation ) { switch ( orientation ) { case TOP_LEFT : return QUARTER_ARC_DEGRESS * 2 ; case TOP_RIGHT : return QUARTER_ARC_DEGRESS * 3 ; case BOTTOM_LEFT : return QUARTER_ARC_DEGRESS ; case BOTTOM_RIGHT : return 0 ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Returns the angle which should be used to draw a shadow which is located at a corner of an elevated view . |
7,744 | public static Bitmap createElevationShadow ( final Context context , final int elevation , final Orientation orientation ) { return createElevationShadow ( context , elevation , orientation , false ) ; } | Creates and returns a bitmap which can be used to emulate a shadow of an elevated view on pre - Lollipop devices . By default a non - parallel illumination of the view is emulated which causes the shadow at its bottom to appear a bit more intense than the shadows to its left and right and a lot more intense than the shadow at its top . |
7,745 | public static Bitmap createElevationShadow ( final Context context , final int elevation , final Orientation orientation , final boolean parallelLight ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureAtLeast ( elevation , 0 , "The elevation must be at least 0" ) ; Condition . INSTANCE . ensureAtMaximum ( elevation , MAX_ELEVATION , "The elevation must be at maximum " + MAX_ELEVATION ) ; Condition . INSTANCE . ensureNotNull ( orientation , "The orientation may not be null" ) ; switch ( orientation ) { case LEFT : case TOP : case RIGHT : case BOTTOM : return createEdgeShadow ( context , elevation , orientation , parallelLight ) ; case TOP_LEFT : case TOP_RIGHT : case BOTTOM_LEFT : case BOTTOM_RIGHT : return createCornerShadow ( context , elevation , orientation , parallelLight ) ; default : throw new IllegalArgumentException ( "Invalid orientation: " + orientation ) ; } } | Creates and returns a bitmap which can be used to emulate a shadow of an elevated view on pre - Lollipop devices . This method furthermore allows to specify whether parallel illumination of the view should be emulated which causes the shadows at all of its sides to appear identically . |
7,746 | private void mergeTemplate ( String templateFilename , File folder , String javaFilename , boolean overwrite ) { final File javaFile = new File ( folder , javaFilename ) ; File destinationFolder = javaFile . getParentFile ( ) ; if ( false == destinationFolder . exists ( ) ) { destinationFolder . mkdirs ( ) ; } if ( false == javaFile . exists ( ) || overwrite ) { getLog ( ) . info ( "Merging " + templateFilename + " for " + javaFilename ) ; try { final PrintWriter writer = new PrintWriter ( javaFile ) ; Template template = Velocity . getTemplate ( templateFilename ) ; template . merge ( vc , writer ) ; writer . close ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ResourceNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ParseErrorException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { getLog ( ) . info ( "Skipping " + templateFilename + " for " + javaFilename ) ; } } | Merges a Velocity template for a specified file unless it already exists . |
7,747 | private static void processResource ( String resourceName , AbstractProcessor processor ) { InputStream lastNameStream = NameDbUsa . class . getClassLoader ( ) . getResourceAsStream ( resourceName ) ; BufferedReader lastNameReader = new BufferedReader ( new InputStreamReader ( lastNameStream ) ) ; try { int index = 0 ; while ( lastNameReader . ready ( ) ) { String line = lastNameReader . readLine ( ) ; processor . processLine ( line , index ++ ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } | Processes a given resource using provided closure |
7,748 | private int binarySearch ( final List < ItemType > list , final ItemType item , final Comparator < ItemType > comparator ) { int index = Collections . binarySearch ( list , item , comparator ) ; if ( index < 0 ) { index = ~ index ; } return index ; } | Returns the index an item should be added at according to a specific comparator . |
7,749 | public final void setComparator ( final Comparator < ItemType > comparator ) { this . comparator = comparator ; if ( comparator != null ) { if ( items . size ( ) > 0 ) { List < ItemType > newItems = new ArrayList < > ( ) ; List < View > views = new ArrayList < > ( ) ; for ( int i = items . size ( ) - 1 ; i >= 0 ; i -- ) { ItemType item = items . get ( i ) ; int index = binarySearch ( newItems , item , comparator ) ; newItems . add ( index , item ) ; View view = parent . getChildAt ( i ) ; parent . removeViewAt ( i ) ; views . add ( index , view ) ; } parent . removeAllViews ( ) ; for ( View view : views ) { parent . addView ( view ) ; } this . items = newItems ; getLogger ( ) . logDebug ( getClass ( ) , "Comparator changed. Views have been reordered" ) ; } else { getLogger ( ) . logDebug ( getClass ( ) , "Comparator changed" ) ; } } else { getLogger ( ) . logDebug ( getClass ( ) , "Comparator set to null" ) ; } } | Sets the comparator which allows to determine the order which should be used to add views to the parent . When setting a comparator which is different from the current one the currently attached views are reordered . |
7,750 | public < T > T httpRequest ( HttpMethod method , Class < T > cls , Map < String , Object > params , Object data , String ... segments ) { HttpHeaders requestHeaders = new HttpHeaders ( ) ; requestHeaders . setAccept ( Collections . singletonList ( MediaType . APPLICATION_JSON ) ) ; if ( accessToken != null ) { String auth = "Bearer " + accessToken ; requestHeaders . set ( "Authorization" , auth ) ; log . info ( "Authorization: " + auth ) ; } String url = path ( apiUrl , segments ) ; MediaType contentType = MediaType . APPLICATION_JSON ; if ( method . equals ( HttpMethod . POST ) && isEmpty ( data ) && ! isEmpty ( params ) ) { data = encodeParams ( params ) ; contentType = MediaType . APPLICATION_FORM_URLENCODED ; } else { url = addQueryParams ( url , params ) ; } requestHeaders . setContentType ( contentType ) ; HttpEntity < ? > requestEntity = null ; if ( method . equals ( HttpMethod . POST ) || method . equals ( HttpMethod . PUT ) ) { if ( isEmpty ( data ) ) { data = JsonNodeFactory . instance . objectNode ( ) ; } requestEntity = new HttpEntity < Object > ( data , requestHeaders ) ; } else { requestEntity = new HttpEntity < Object > ( requestHeaders ) ; } log . info ( "Client.httpRequest(): url: " + url ) ; ResponseEntity < T > responseEntity = restTemplate . exchange ( url , method , requestEntity , cls ) ; log . info ( "Client.httpRequest(): reponse body: " + responseEntity . getBody ( ) . toString ( ) ) ; return responseEntity . getBody ( ) ; } | Low - level HTTP request method . Synchronous blocks till response or timeout . |
7,751 | public ApiResponse apiRequest ( HttpMethod method , Map < String , Object > params , Object data , String ... segments ) { ApiResponse response = null ; try { response = httpRequest ( method , ApiResponse . class , params , data , segments ) ; log . info ( "Client.apiRequest(): Response: " + response ) ; } catch ( HttpClientErrorException e ) { log . error ( "Client.apiRequest(): HTTP error: " + e . getLocalizedMessage ( ) ) ; response = parse ( e . getResponseBodyAsString ( ) , ApiResponse . class ) ; if ( ( response != null ) && ! isEmpty ( response . getError ( ) ) ) { log . error ( "Client.apiRequest(): Response error: " + response . getError ( ) ) ; if ( ! isEmpty ( response . getException ( ) ) ) { log . error ( "Client.apiRequest(): Response exception: " + response . getException ( ) ) ; } } } return response ; } | High - level Usergrid API request . |
7,752 | public ApiResponse authorizeAppUser ( String email , String password ) { validateNonEmptyParam ( email , "email" ) ; validateNonEmptyParam ( password , "password" ) ; assertValidApplicationId ( ) ; loggedInUser = null ; accessToken = null ; currentOrganization = null ; Map < String , Object > formData = new HashMap < String , Object > ( ) ; formData . put ( "grant_type" , "password" ) ; formData . put ( "username" , email ) ; formData . put ( "password" , password ) ; ApiResponse response = apiRequest ( HttpMethod . POST , formData , null , organizationId , applicationId , "token" ) ; if ( response == null ) { return response ; } if ( ! isEmpty ( response . getAccessToken ( ) ) && ( response . getUser ( ) != null ) ) { loggedInUser = response . getUser ( ) ; accessToken = response . getAccessToken ( ) ; currentOrganization = null ; log . info ( "Client.authorizeAppUser(): Access token: " + accessToken ) ; } else { log . info ( "Client.authorizeAppUser(): Response: " + response ) ; } return response ; } | Log the user in and get a valid access token . |
7,753 | public ApiResponse changePassword ( String username , String oldPassword , String newPassword ) { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( "newpassword" , newPassword ) ; data . put ( "oldpassword" , oldPassword ) ; return apiRequest ( HttpMethod . POST , null , data , organizationId , applicationId , "users" , username , "password" ) ; } | Change the password for the currently logged in user . You must supply the old password and the new password . |
7,754 | public ApiResponse authorizeAppClient ( String clientId , String clientSecret ) { validateNonEmptyParam ( clientId , "client identifier" ) ; validateNonEmptyParam ( clientSecret , "client secret" ) ; assertValidApplicationId ( ) ; loggedInUser = null ; accessToken = null ; currentOrganization = null ; Map < String , Object > formData = new HashMap < String , Object > ( ) ; formData . put ( "grant_type" , "client_credentials" ) ; formData . put ( "client_id" , clientId ) ; formData . put ( "client_secret" , clientSecret ) ; ApiResponse response = apiRequest ( HttpMethod . POST , formData , null , organizationId , applicationId , "token" ) ; if ( response == null ) { return response ; } if ( ! isEmpty ( response . getAccessToken ( ) ) ) { loggedInUser = null ; accessToken = response . getAccessToken ( ) ; currentOrganization = null ; log . info ( "Client.authorizeAppClient(): Access token: " + accessToken ) ; } else { log . info ( "Client.authorizeAppClient(): Response: " + response ) ; } return response ; } | Log the app in with it s client id and client secret key . Not recommended for production apps . |
7,755 | public ApiResponse createEntity ( Entity entity ) { assertValidApplicationId ( ) ; if ( isEmpty ( entity . getType ( ) ) ) { throw new IllegalArgumentException ( "Missing entity type" ) ; } ApiResponse response = apiRequest ( HttpMethod . POST , null , entity , organizationId , applicationId , entity . getType ( ) ) ; return response ; } | Create a new entity on the server . |
7,756 | public ApiResponse createEntity ( Map < String , Object > properties ) { assertValidApplicationId ( ) ; if ( isEmpty ( properties . get ( "type" ) ) ) { throw new IllegalArgumentException ( "Missing entity type" ) ; } ApiResponse response = apiRequest ( HttpMethod . POST , null , properties , organizationId , applicationId , properties . get ( "type" ) . toString ( ) ) ; return response ; } | Create a new entity on the server from a set of properties . Properties must include a type property . |
7,757 | public Map < String , Group > getGroupsForUser ( String userId ) { ApiResponse response = apiRequest ( HttpMethod . GET , null , null , organizationId , applicationId , "users" , userId , "groups" ) ; Map < String , Group > groupMap = new HashMap < String , Group > ( ) ; if ( response != null ) { List < Group > groups = response . getEntities ( Group . class ) ; for ( Group group : groups ) { groupMap . put ( group . getPath ( ) , group ) ; } } return groupMap ; } | Get the groups for the user . |
7,758 | public Query queryActivityFeedForUser ( String userId ) { Query q = queryEntitiesRequest ( HttpMethod . GET , null , null , organizationId , applicationId , "users" , userId , "feed" ) ; return q ; } | Get a user s activity feed . Returned as a query to ease paging . |
7,759 | public ApiResponse postUserActivity ( String userId , Activity activity ) { return apiRequest ( HttpMethod . POST , null , activity , organizationId , applicationId , "users" , userId , "activities" ) ; } | Posts an activity to a user . Activity must already be created . |
7,760 | public ApiResponse postUserActivity ( String verb , String title , String content , String category , User user , Entity object , String objectType , String objectName , String objectContent ) { Activity activity = Activity . newActivity ( verb , title , content , category , user , object , objectType , objectName , objectContent ) ; return postUserActivity ( user . getUuid ( ) . toString ( ) , activity ) ; } | Creates and posts an activity to a user . |
7,761 | public ApiResponse postGroupActivity ( String groupId , Activity activity ) { return apiRequest ( HttpMethod . POST , null , activity , organizationId , applicationId , "groups" , groupId , "activities" ) ; } | Posts an activity to a group . Activity must already be created . |
7,762 | public ApiResponse postGroupActivity ( String groupId , String verb , String title , String content , String category , User user , Entity object , String objectType , String objectName , String objectContent ) { Activity activity = Activity . newActivity ( verb , title , content , category , user , object , objectType , objectName , objectContent ) ; return postGroupActivity ( groupId , activity ) ; } | Creates and posts an activity to a group . |
7,763 | public Query queryActivity ( ) { Query q = queryEntitiesRequest ( HttpMethod . GET , null , null , organizationId , applicationId , "activities" ) ; return q ; } | Get a group s activity feed . Returned as a query to ease paging . |
7,764 | public Query queryEntitiesRequest ( HttpMethod method , Map < String , Object > params , Object data , String ... segments ) { ApiResponse response = apiRequest ( method , params , data , segments ) ; return new EntityQuery ( response , method , params , data , segments ) ; } | Perform a query request and return a query object . The Query object provides a simple way of dealing with result sets that need to be iterated or paged through . |
7,765 | public Query queryUsersForGroup ( String groupId ) { Query q = queryEntitiesRequest ( HttpMethod . GET , null , null , organizationId , applicationId , "groups" , groupId , "users" ) ; return q ; } | Queries the users for the specified group . |
7,766 | public ApiResponse addUserToGroup ( String userId , String groupId ) { return apiRequest ( HttpMethod . POST , null , null , organizationId , applicationId , "groups" , groupId , "users" , userId ) ; } | Adds a user to the specified groups . |
7,767 | public ApiResponse createGroup ( String groupPath , String groupTitle , String groupName ) { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( "type" , "group" ) ; data . put ( "path" , groupPath ) ; if ( groupTitle != null ) { data . put ( "title" , groupTitle ) ; } if ( groupName != null ) { data . put ( "name" , groupName ) ; } return apiRequest ( HttpMethod . POST , null , data , organizationId , applicationId , "groups" ) ; } | Create a group with a path title and name |
7,768 | public ApiResponse connectEntities ( String connectingEntityType , String connectingEntityId , String connectionType , String connectedEntityId ) { return apiRequest ( HttpMethod . POST , null , null , organizationId , applicationId , connectingEntityType , connectingEntityId , connectionType , connectedEntityId ) ; } | Connect two entities together . |
7,769 | public ApiResponse disconnectEntities ( String connectingEntityType , String connectingEntityId , String connectionType , String connectedEntityId ) { return apiRequest ( HttpMethod . DELETE , null , null , organizationId , applicationId , connectingEntityType , connectingEntityId , connectionType , connectedEntityId ) ; } | Disconnect two entities . |
7,770 | public Query queryEntityConnections ( String connectingEntityType , String connectingEntityId , String connectionType , String ql ) { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "ql" , ql ) ; Query q = queryEntitiesRequest ( HttpMethod . GET , params , null , organizationId , applicationId , connectingEntityType , connectingEntityId , connectionType ) ; return q ; } | Query the connected entities . |
7,771 | public Query queryEntityConnectionsWithinLocation ( String connectingEntityType , String connectingEntityId , String connectionType , float distance , float lattitude , float longitude , String ql ) { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "ql" , makeLocationQL ( distance , lattitude , longitude , ql ) ) ; Query q = queryEntitiesRequest ( HttpMethod . GET , params , null , organizationId , applicationId , connectingEntityType , connectingEntityId , connectionType ) ; return q ; } | Query the connected entities within distance of a specific point . |
7,772 | public static Object toData ( Literal lit ) { if ( lit == null ) throw new IllegalArgumentException ( "Can't convert null literal" ) ; if ( lit instanceof TypedLiteral ) return toData ( ( TypedLiteral ) lit ) ; return lit . getLexical ( ) ; } | Convert from RDF literal to native Java object . |
7,773 | public static Object toData ( TypedLiteral lit ) { if ( lit == null ) throw new IllegalArgumentException ( "Can't convert null literal" ) ; Conversion < ? > c = uriConversions . get ( lit . getDataType ( ) ) ; if ( c == null ) throw new IllegalArgumentException ( "Don't know how to convert literal of type " + lit . getDataType ( ) ) ; return c . data ( lit . getLexical ( ) ) ; } | Convert from RDF typed literal to native Java object . |
7,774 | public static TypedLiteral toLiteral ( Object value ) { if ( value == null ) throw new IllegalArgumentException ( "Can't convert null value" ) ; Conversion < ? > c = classConversions . get ( value . getClass ( ) ) ; if ( c != null ) return c . literal ( value ) ; return new TypedLiteralImpl ( value . toString ( ) , XsdTypes . ANY_SIMPLE_TYPE ) ; } | Convert from an arbitrary Java object to an RDF typed literal using an XSD datatype if possible . |
7,775 | protected Map < String , RDFNode > readNext ( ) throws SparqlException { try { int eventType = reader . nextTag ( ) ; if ( eventType == END_ELEMENT ) { if ( nameIs ( RESULTS ) ) { cleanup ( ) ; return null ; } else throw new SparqlException ( "Bad element closure with: " + reader . getLocalName ( ) ) ; } testOpen ( eventType , RESULT , "Expected a new result. Got :" + ( ( eventType == END_ELEMENT ) ? "/" : "" ) + reader . getLocalName ( ) ) ; Map < String , RDFNode > result = new HashMap < String , RDFNode > ( ) ; while ( ( eventType = reader . nextTag ( ) ) == START_ELEMENT && nameIs ( BINDING ) ) { String name = reader . getAttributeValue ( null , VAR_NAME ) ; result . put ( name , parseValue ( ) ) ; testClose ( reader . nextTag ( ) , BINDING , "Single Binding not closed correctly" ) ; } testClose ( eventType , RESULT , "Single Result not closed correctly" ) ; return result ; } catch ( XMLStreamException e ) { throw new SparqlException ( "Error reading from XML stream" , e ) ; } } | Parse the input stream to look for a result . |
7,776 | private static void append ( StringBuilder sb , int val , int width ) { String s = Integer . toString ( val ) ; for ( int i = s . length ( ) ; i < width ; i ++ ) sb . append ( '0' ) ; sb . append ( s ) ; } | Append the given value to the string builder with leading zeros to result in the given minimum width . |
7,777 | private static long elapsedDays ( int year ) { int y = year - 1 ; return DAYS_IN_YEAR * ( long ) y + div ( y , 400 ) - div ( y , 100 ) + div ( y , 4 ) ; } | Find the number of elapsed days from the epoch to the beginning of the given year . |
7,778 | private static int daysInMonth ( int year , int month ) { assert month >= FIRST_MONTH && month <= LAST_MONTH ; int d = DAYS_IN_MONTH [ month - 1 ] ; if ( month == FEBRUARY && isLeapYear ( year ) ) d ++ ; return d ; } | Find the number of days in the given month given the year . |
7,779 | private static int parseMillis ( Input s ) { if ( s . index < s . len && s . getChar ( ) == '.' ) { int startIndex = ++ s . index ; int ms = parseInt ( s ) ; int len = s . index - startIndex ; for ( ; len < 3 ; len ++ ) ms *= 10 ; for ( ; len > 3 ; len -- ) ms /= 10 ; return ms ; } return 0 ; } | Parse the fractional seconds field from the input returning the number of milliseconds and truncating extra places . |
7,780 | private static Integer parseTzOffsetMs ( Input s , boolean strict ) { if ( s . index < s . len ) { char c = s . getChar ( ) ; s . index ++ ; int sign ; if ( c == 'Z' ) { return 0 ; } else if ( c == '+' ) { sign = 1 ; } else if ( c == '-' ) { sign = - 1 ; } else { throw new DateFormatException ( "unexpected character, expected one of [Z+-]" , s . str , s . index - 1 ) ; } int tzHours = parseField ( "timezone hours" , s , TIME_SEP , 2 , 2 , strict ) ; if ( strict && tzHours > 14 ) throw new DateFormatException ( "timezone offset hours out of range [0..14]" , s . str , s . index - 2 ) ; int tzMin = parseField ( "timezone minutes" , s , null , 2 , 2 , strict ) ; if ( strict && tzMin > 59 ) throw new DateFormatException ( "timezone offset hours out of range [0..59]" , s . str , s . index - 1 ) ; if ( strict && tzHours == 14 && tzMin > 0 ) throw new DateFormatException ( "timezone offset may not be greater than 14 hours" , s . str , s . index - 1 ) ; return sign * ( tzHours * MINS_IN_HOUR + tzMin ) * MS_IN_MIN ; } return null ; } | Parse the timezone offset from the input returning its millisecond value . |
7,781 | private static int parseField ( String field , Input s , Character delim , int minLen , int maxLen , boolean strict ) { int startIndex = s . index ; int result = parseInt ( s ) ; if ( startIndex == s . index ) throw new DateFormatException ( "missing value for field '" + field + "'" , s . str , startIndex ) ; if ( strict ) { int len = s . index - startIndex ; if ( len < minLen ) throw new DateFormatException ( "field '" + field + "' must be at least " + minLen + " digits wide" , s . str , startIndex ) ; if ( maxLen > 0 && len > maxLen ) throw new DateFormatException ( "field '" + field + "' must be no more than " + minLen + " digits wide" , s . str , startIndex ) ; } if ( delim != null ) { if ( s . index >= s . len ) throw new DateFormatException ( "unexpected end of input" , s . str , s . index ) ; if ( strict && s . getChar ( ) != delim . charValue ( ) ) throw new DateFormatException ( "unexpected character, expected '" + delim + "'" , s . str , s . index ) ; s . index ++ ; } return result ; } | Parse a field from input validating its delimiter and length if requested . |
7,782 | private static int parseInt ( Input s ) { if ( s . index >= s . len ) throw new DateFormatException ( "unexpected end of input" , s . str , s . index ) ; int result = 0 ; while ( s . index < s . len ) { char c = s . getChar ( ) ; if ( c >= '0' && c <= '9' ) { if ( result >= Integer . MAX_VALUE / 10 ) throw new ArithmeticException ( "Field too large." ) ; result = result * 10 + ( ( int ) c - ( int ) '0' ) ; s . index ++ ; } else { break ; } } return result ; } | Parse an integer from the input reading up to the first non - numeric character . |
7,783 | public static void showAppInfo ( final Context context , final String packageName ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureNotNull ( packageName , "The package name may not be null" ) ; Condition . INSTANCE . ensureNotEmpty ( packageName , "The package name may not be empty" ) ; Intent intent = new Intent ( ) ; intent . setAction ( Settings . ACTION_APPLICATION_DETAILS_SETTINGS ) ; Uri uri = Uri . fromParts ( "package" , packageName , null ) ; intent . setData ( uri ) ; if ( intent . resolveActivity ( context . getPackageManager ( ) ) == null ) { throw new ActivityNotFoundException ( "App info for package " + packageName + " not available" ) ; } context . startActivity ( intent ) ; } | Starts the settings app in order to show the information about a specific app . |
7,784 | public ApiResponse < Void > postPermissionsWithHttpInfo ( String objectType , PostPermissionsData body ) throws ApiException { com . squareup . okhttp . Call call = postPermissionsValidateBeforeCall ( objectType , body , null , null ) ; return apiClient . execute ( call ) ; } | Post permissions for a list of objects . Post permissions from Configuration Server for objects identified by their type and DBIDs . |
7,785 | Optional < PlayerKilled > move ( Player player ) { Move move = player . getMoves ( ) . poll ( ) ; if ( move != null ) { Tile from = tiles [ move . getFrom ( ) ] ; boolean armyBigEnough = from . getArmySize ( ) > 1 ; boolean tileAndPlayerMatching = from . isOwnedBy ( player . getPlayerIndex ( ) ) ; boolean oneStepAway = Stream . of ( getTileAbove ( from ) , getTileBelow ( from ) , getTileLeftOf ( from ) , getTileRightOf ( from ) ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( Tile :: getTileIndex ) . anyMatch ( neighbourIndex -> neighbourIndex == move . getTo ( ) ) ; if ( armyBigEnough && tileAndPlayerMatching && oneStepAway ) { int armySize = from . moveFrom ( move . half ( ) ) ; return tiles [ move . getTo ( ) ] . moveTo ( armySize , from . getOwnerPlayerIndex ( ) . get ( ) , tiles ) . map ( this :: transfer ) ; } else { return move ( player ) ; } } return Optional . empty ( ) ; } | Polls move recursively until it finds a valid move . |
7,786 | public List < String > getPlayerNames ( ) { return lastGameState . getPlayers ( ) . stream ( ) . map ( Player :: getUsername ) . collect ( Collectors . toList ( ) ) ; } | Names of all players that played in the game . |
7,787 | public static Field getField ( Class < ? > clazz , String fieldName ) throws NoSuchFieldException { if ( clazz == Object . class ) { return null ; } try { Field field = clazz . getDeclaredField ( fieldName ) ; return field ; } catch ( NoSuchFieldException e ) { return getField ( clazz . getSuperclass ( ) , fieldName ) ; } } | Recursively find the field by name up to the top of class hierarchy . |
7,788 | public com . squareup . okhttp . Call connectCall ( final ProgressResponseBody . ProgressListener progressListener , final ProgressRequestBody . ProgressRequestListener progressRequestListener ) throws ApiException { Object localVarPostBody = null ; String localVarPath = "/notifications/connect" ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; List < Pair > localVarCollectionQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; if ( localVarAccept != null ) localVarHeaderParams . put ( "Accept" , localVarAccept ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; localVarHeaderParams . put ( "Content-Type" , localVarContentType ) ; if ( progressListener != null ) { apiClient . getHttpClient ( ) . networkInterceptors ( ) . add ( new com . squareup . okhttp . Interceptor ( ) { public com . squareup . okhttp . Response intercept ( com . squareup . okhttp . Interceptor . Chain chain ) throws IOException { com . squareup . okhttp . Response originalResponse = chain . proceed ( chain . request ( ) ) ; return originalResponse . newBuilder ( ) . body ( new ProgressResponseBody ( originalResponse . body ( ) , progressListener ) ) . build ( ) ; } } ) ; } String [ ] localVarAuthNames = new String [ ] { } ; return apiClient . buildCall ( localVarPath , "POST" , localVarQueryParams , localVarCollectionQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAuthNames , progressRequestListener ) ; } | Build call for connect |
7,789 | protected void invokeDelegate ( ActionFilter delegate , ActionRequest request , ActionResponse response , FilterChain filterChain ) throws PortletException , IOException { delegate . doFilter ( request , response , filterChain ) ; } | Actually invoke the delegate ActionFilter with the given request and response . |
7,790 | protected void invokeDelegate ( EventFilter delegate , EventRequest request , EventResponse response , FilterChain filterChain ) throws PortletException , IOException { delegate . doFilter ( request , response , filterChain ) ; } | Actually invoke the delegate EventFilter with the given request and response . |
7,791 | protected void invokeDelegate ( RenderFilter delegate , RenderRequest request , RenderResponse response , FilterChain filterChain ) throws PortletException , IOException { delegate . doFilter ( request , response , filterChain ) ; } | Actually invoke the delegate RenderFilter with the given request and response . |
7,792 | protected void invokeDelegate ( ResourceFilter delegate , ResourceRequest request , ResourceResponse response , FilterChain filterChain ) throws PortletException , IOException { delegate . doFilter ( request , response , filterChain ) ; } | Actually invoke the delegate ResourceFilter with the given request and response . |
7,793 | public PreAuthenticatedGrantedAuthoritiesPortletAuthenticationDetails buildDetails ( PortletRequest context ) { Collection < ? extends GrantedAuthority > userGas = buildGrantedAuthorities ( context ) ; PreAuthenticatedGrantedAuthoritiesPortletAuthenticationDetails result = new PreAuthenticatedGrantedAuthoritiesPortletAuthenticationDetails ( context , userGas ) ; return result ; } | Builds the authentication details object . |
7,794 | private boolean _runDML ( DataManupulationStatement q , boolean isDDL ) { boolean readOnly = ConnectionManager . instance ( ) . isPoolReadOnly ( getPool ( ) ) ; Transaction txn = Database . getInstance ( ) . getCurrentTransaction ( ) ; if ( ! readOnly ) { q . executeUpdate ( ) ; if ( Database . getJdbcTypeHelper ( getPool ( ) ) . isAutoCommitOnDDL ( ) ) { txn . registerCommit ( ) ; } else { txn . commit ( ) ; } } else { cat . fine ( "Pool " + getPool ( ) + " Skipped running" + q . getRealSQL ( ) ) ; } return ! readOnly ; } | RReturn true if modification was done .. |
7,795 | private List < PortletFilter > getFilters ( PortletRequest request ) { for ( PortletSecurityFilterChain chain : filterChains ) { if ( chain . matches ( request ) ) { return chain . getFilters ( ) ; } } return null ; } | Returns the first filter chain matching the supplied URL . |
7,796 | public void setFilterChainMap ( Map < RequestMatcher , List < PortletFilter > > filterChainMap ) { filterChains = new ArrayList < PortletSecurityFilterChain > ( filterChainMap . size ( ) ) ; for ( Map . Entry < RequestMatcher , List < PortletFilter > > entry : filterChainMap . entrySet ( ) ) { filterChains . add ( new DefaultPortletSecurityFilterChain ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } } | Sets the mapping of URL patterns to filter chains . |
7,797 | public Map < RequestMatcher , List < PortletFilter > > getFilterChainMap ( ) { LinkedHashMap < RequestMatcher , List < PortletFilter > > map = new LinkedHashMap < RequestMatcher , List < PortletFilter > > ( ) ; for ( PortletSecurityFilterChain chain : filterChains ) { map . put ( ( ( DefaultPortletSecurityFilterChain ) chain ) . getRequestMatcher ( ) , chain . getFilters ( ) ) ; } return map ; } | Returns a copy of the underlying filter chain map . Modifications to the map contents will not affect the PortletFilterChainProxy state . |
7,798 | private void displaySearchLine ( String line , String searchWord ) throws IOException { int start = line . indexOf ( searchWord ) ; connection . write ( line . substring ( 0 , start ) ) ; connection . write ( ANSI . INVERT_BACKGROUND ) ; connection . write ( searchWord ) ; connection . write ( ANSI . RESET ) ; connection . write ( line . substring ( start + searchWord . length ( ) , line . length ( ) ) ) ; } | highlight the specific word thats found in the search |
7,799 | public static PortletApplicationContext getPortletApplicationContext ( PortletContext pc , String attrName ) { Assert . notNull ( pc , "PortletContext must not be null" ) ; Object attr = pc . getAttribute ( attrName ) ; if ( attr == null ) { return null ; } if ( attr instanceof RuntimeException ) { throw ( RuntimeException ) attr ; } if ( attr instanceof Error ) { throw ( Error ) attr ; } if ( attr instanceof Exception ) { throw new IllegalStateException ( ( Exception ) attr ) ; } if ( ! ( attr instanceof PortletApplicationContext ) ) { throw new IllegalStateException ( "Context attribute is not of type PortletApplicationContext: " + attr . getClass ( ) + " - " + attr ) ; } return ( PortletApplicationContext ) attr ; } | Find a custom PortletApplicationContext for this web application . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.