idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
300
public Collection < SerialMessage > initialize ( ) { ArrayList < SerialMessage > result = new ArrayList < SerialMessage > ( ) ; if ( this . getNode ( ) . getManufacturer ( ) == 0x010F && this . getNode ( ) . getDeviceType ( ) == 0x0501 ) { logger . warn ( "Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET." ) ; return result ; } result . add ( this . getSupportedMessage ( ) ) ; return result ; }
Initializes the alarm sensor command class . Requests the supported alarm types .
133
15
301
public static java . util . Date newDateTime ( ) { return new java . util . Date ( ( System . currentTimeMillis ( ) / SECOND_MILLIS ) * SECOND_MILLIS ) ; }
Create a new DateTime . To the last second . This will not create any extra - millis - seconds which may cause bugs when writing to stores such as databases that round milli - seconds up and down .
48
43
302
public static java . sql . Date newDate ( ) { return new java . sql . Date ( ( System . currentTimeMillis ( ) / DAY_MILLIS ) * DAY_MILLIS ) ; }
Create a new Date . To the last day .
45
10
303
public static java . sql . Time newTime ( ) { return new java . sql . Time ( System . currentTimeMillis ( ) % DAY_MILLIS ) ; }
Create a new Time with no date component .
37
9
304
public static int secondsDiff ( Date earlierDate , Date laterDate ) { if ( earlierDate == null || laterDate == null ) { return 0 ; } return ( int ) ( ( laterDate . getTime ( ) / SECOND_MILLIS ) - ( earlierDate . getTime ( ) / SECOND_MILLIS ) ) ; }
Get the seconds difference
73
4
305
public static int minutesDiff ( Date earlierDate , Date laterDate ) { if ( earlierDate == null || laterDate == null ) { return 0 ; } return ( int ) ( ( laterDate . getTime ( ) / MINUTE_MILLIS ) - ( earlierDate . getTime ( ) / MINUTE_MILLIS ) ) ; }
Get the minutes difference
73
4
306
public static int hoursDiff ( Date earlierDate , Date laterDate ) { if ( earlierDate == null || laterDate == null ) { return 0 ; } return ( int ) ( ( laterDate . getTime ( ) / HOUR_MILLIS ) - ( earlierDate . getTime ( ) / HOUR_MILLIS ) ) ; }
Get the hours difference
73
4
307
public static int daysDiff ( Date earlierDate , Date laterDate ) { if ( earlierDate == null || laterDate == null ) { return 0 ; } return ( int ) ( ( laterDate . getTime ( ) / DAY_MILLIS ) - ( earlierDate . getTime ( ) / DAY_MILLIS ) ) ; }
Get the days difference
71
4
308
public static java . sql . Time rollTime ( java . util . Date startDate , int period , int amount ) { GregorianCalendar gc = new GregorianCalendar ( ) ; gc . setTime ( startDate ) ; gc . add ( period , amount ) ; return new java . sql . Time ( gc . getTime ( ) . getTime ( ) ) ; }
Roll the java . util . Time forward or backward .
83
11
309
public static java . util . Date rollDateTime ( java . util . Date startDate , int period , int amount ) { GregorianCalendar gc = new GregorianCalendar ( ) ; gc . setTime ( startDate ) ; gc . add ( period , amount ) ; return new java . util . Date ( gc . getTime ( ) . getTime ( ) ) ; }
Roll the java . util . Date forward or backward .
84
11
310
public static java . sql . Date rollYears ( java . util . Date startDate , int years ) { return rollDate ( startDate , Calendar . YEAR , years ) ; }
Roll the years forward or backward .
37
7
311
@ SuppressWarnings ( "deprecation" ) public static boolean dateEquals ( java . util . Date d1 , java . util . Date d2 ) { if ( d1 == null || d2 == null ) { return false ; } return d1 . getDate ( ) == d2 . getDate ( ) && d1 . getMonth ( ) == d2 . getMonth ( ) && d1 . getYear ( ) == d2 . getYear ( ) ; }
Checks the day month and year are equal .
104
10
312
@ SuppressWarnings ( "deprecation" ) public static boolean timeEquals ( java . util . Date d1 , java . util . Date d2 ) { if ( d1 == null || d2 == null ) { return false ; } return d1 . getHours ( ) == d2 . getHours ( ) && d1 . getMinutes ( ) == d2 . getMinutes ( ) && d1 . getSeconds ( ) == d2 . getSeconds ( ) ; }
Checks the hour minute and second are equal .
108
10
313
@ SuppressWarnings ( "deprecation" ) public static boolean dateTimeEquals ( java . util . Date d1 , java . util . Date d2 ) { if ( d1 == null || d2 == null ) { return false ; } return d1 . getDate ( ) == d2 . getDate ( ) && d1 . getMonth ( ) == d2 . getMonth ( ) && d1 . getYear ( ) == d2 . getYear ( ) && d1 . getHours ( ) == d2 . getHours ( ) && d1 . getMinutes ( ) == d2 . getMinutes ( ) && d1 . getSeconds ( ) == d2 . getSeconds ( ) ; }
Checks the second hour month day month and year are equal .
157
13
314
public static Object toObject ( Class < ? > clazz , Object value ) throws ParseException { if ( value == null ) { return null ; } if ( clazz == null ) { return value ; } if ( java . sql . Date . class . isAssignableFrom ( clazz ) ) { return toDate ( value ) ; } if ( java . sql . Time . class . isAssignableFrom ( clazz ) ) { return toTime ( value ) ; } if ( java . sql . Timestamp . class . isAssignableFrom ( clazz ) ) { return toTimestamp ( value ) ; } if ( java . util . Date . class . isAssignableFrom ( clazz ) ) { return toDateTime ( value ) ; } return value ; }
Convert an Object of type Class to an Object .
167
11
315
public static java . util . Date getDateTime ( Object value ) { try { return toDateTime ( value ) ; } catch ( ParseException pe ) { pe . printStackTrace ( ) ; return null ; } }
Convert an Object to a DateTime without an Exception
48
11
316
public static java . util . Date toDateTime ( Object value ) throws ParseException { if ( value == null ) { return null ; } if ( value instanceof java . util . Date ) { return ( java . util . Date ) value ; } if ( value instanceof String ) { if ( "" . equals ( ( String ) value ) ) { return null ; } return IN_DATETIME_FORMAT . parse ( ( String ) value ) ; } return IN_DATETIME_FORMAT . parse ( value . toString ( ) ) ; }
Convert an Object to a DateTime .
120
9
317
public static java . sql . Date getDate ( Object value ) { try { return toDate ( value ) ; } catch ( ParseException pe ) { pe . printStackTrace ( ) ; return null ; } }
Convert an Object to a Date without an Exception
46
10
318
public static java . sql . Date toDate ( Object value ) throws ParseException { if ( value == null ) { return null ; } if ( value instanceof java . sql . Date ) { return ( java . sql . Date ) value ; } if ( value instanceof String ) { if ( "" . equals ( ( String ) value ) ) { return null ; } return new java . sql . Date ( IN_DATE_FORMAT . parse ( ( String ) value ) . getTime ( ) ) ; } return new java . sql . Date ( IN_DATE_FORMAT . parse ( value . toString ( ) ) . getTime ( ) ) ; }
Convert an Object to a Date .
141
8
319
public static java . sql . Time getTime ( Object value ) { try { return toTime ( value ) ; } catch ( ParseException pe ) { pe . printStackTrace ( ) ; return null ; } }
Convert an Object to a Time without an Exception
46
10
320
public static java . sql . Time toTime ( Object value ) throws ParseException { if ( value == null ) { return null ; } if ( value instanceof java . sql . Time ) { return ( java . sql . Time ) value ; } if ( value instanceof String ) { if ( "" . equals ( ( String ) value ) ) { return null ; } return new java . sql . Time ( IN_TIME_FORMAT . parse ( ( String ) value ) . getTime ( ) ) ; } return new java . sql . Time ( IN_TIME_FORMAT . parse ( value . toString ( ) ) . getTime ( ) ) ; }
Convert an Object to a Time .
139
8
321
public static java . sql . Timestamp getTimestamp ( Object value ) { try { return toTimestamp ( value ) ; } catch ( ParseException pe ) { pe . printStackTrace ( ) ; return null ; } }
Convert an Object to a Timestamp without an Exception
49
11
322
public static java . sql . Timestamp toTimestamp ( Object value ) throws ParseException { if ( value == null ) { return null ; } if ( value instanceof java . sql . Timestamp ) { return ( java . sql . Timestamp ) value ; } if ( value instanceof String ) { if ( "" . equals ( ( String ) value ) ) { return null ; } return new java . sql . Timestamp ( IN_TIMESTAMP_FORMAT . parse ( ( String ) value ) . getTime ( ) ) ; } return new java . sql . Timestamp ( IN_TIMESTAMP_FORMAT . parse ( value . toString ( ) ) . getTime ( ) ) ; }
Convert an Object to a Timestamp .
151
9
323
@ SuppressWarnings ( "deprecation" ) public static boolean isTimeInRange ( java . sql . Time start , java . sql . Time end , java . util . Date d ) { d = new java . sql . Time ( d . getHours ( ) , d . getMinutes ( ) , d . getSeconds ( ) ) ; if ( start == null || end == null ) { return false ; } if ( start . before ( end ) && ( ! ( d . after ( start ) && d . before ( end ) ) ) ) { return false ; } if ( end . before ( start ) && ( ! ( d . after ( end ) || d . before ( start ) ) ) ) { return false ; } return true ; }
Tells you if the date part of a datetime is in a certain time range .
161
18
324
public static Trajectory combineTrajectory ( Trajectory a , Trajectory b ) { if ( a . getDimension ( ) != b . getDimension ( ) ) { throw new IllegalArgumentException ( "Combination not possible: The trajectorys does not have the same dimension" ) ; } if ( a . size ( ) != b . size ( ) ) { throw new IllegalArgumentException ( "Combination not possible: The trajectorys does not " + "have the same number of steps a=" + a . size ( ) + " b=" + b . size ( ) ) ; } Trajectory c = new Trajectory ( a . getDimension ( ) ) ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { Point3d pos = new Point3d ( a . get ( i ) . x + b . get ( i ) . x , a . get ( i ) . y + b . get ( i ) . y , a . get ( i ) . z + b . get ( i ) . z ) ; c . add ( pos ) ; } return c ; }
Combines two trajectories by adding the corresponding positions . The trajectories have to have the same length .
244
21
325
public static Trajectory concactTrajectorie ( Trajectory a , Trajectory b ) { if ( a . getDimension ( ) != b . getDimension ( ) ) { throw new IllegalArgumentException ( "Combination not possible: The trajectorys does not have the same dimension" ) ; } Trajectory c = new Trajectory ( a . getDimension ( ) ) ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { Point3d pos = new Point3d ( a . get ( i ) . x , a . get ( i ) . y , a . get ( i ) . z ) ; c . add ( pos ) ; } double dx = a . get ( a . size ( ) - 1 ) . x - b . get ( 0 ) . x ; double dy = a . get ( a . size ( ) - 1 ) . y - b . get ( 0 ) . y ; double dz = a . get ( a . size ( ) - 1 ) . z - b . get ( 0 ) . z ; for ( int i = 1 ; i < b . size ( ) ; i ++ ) { Point3d pos = new Point3d ( b . get ( i ) . x + dx , b . get ( i ) . y + dy , b . get ( i ) . z + dz ) ; c . add ( pos ) ; } return c ; }
Concatenates the trajectory a and b
309
9
326
public static Trajectory resample ( Trajectory t , int n ) { Trajectory t1 = new Trajectory ( 2 ) ; for ( int i = 0 ; i < t . size ( ) ; i = i + n ) { t1 . add ( t . get ( i ) ) ; } return t1 ; }
Resamples a trajectory
72
4
327
public static Trajectory getTrajectoryByID ( List < ? extends Trajectory > t , int id ) { Trajectory track = null ; for ( int i = 0 ; i < t . size ( ) ; i ++ ) { if ( t . get ( i ) . getID ( ) == id ) { track = t . get ( i ) ; break ; } } return track ; }
Finds trajectory by ID
86
5
328
public void setPropertyDestinationType ( Class < ? > clazz , String propertyName , TypeReference < ? > destinationType ) { propertiesDestinationTypes . put ( new ClassProperty ( clazz , propertyName ) , destinationType ) ; }
set the property destination type for given property
51
8
329
public void addConverter ( int index , IConverter converter ) { converterList . add ( index , converter ) ; if ( converter instanceof IContainerConverter ) { IContainerConverter containerConverter = ( IContainerConverter ) converter ; if ( containerConverter . getElementConverter ( ) == null ) { containerConverter . setElementConverter ( elementConverter ) ; } } }
add converter at given index . The index can be changed during conversion if canReorder is true
96
19
330
public static SPIProviderResolver getInstance ( ClassLoader cl ) { SPIProviderResolver resolver = ( SPIProviderResolver ) ServiceLoader . loadService ( SPIProviderResolver . class . getName ( ) , DEFAULT_SPI_PROVIDER_RESOLVER , cl ) ; return resolver ; }
Get the SPIProviderResolver instance using the provided classloader for lookup
66
14
331
static Parameter createParameter ( final String name , final String value ) { if ( value != null && isQuoted ( value ) ) { return new QuotedParameter ( name , value ) ; } return new Parameter ( name , value ) ; }
Creates a Parameter
52
5
332
public static < T , A extends Annotation > String getClassAnnotationValue ( Class < T > classType , Class < A > annotationType , String attributeName ) { String value = null ; Annotation annotation = classType . getAnnotation ( annotationType ) ; if ( annotation != null ) { try { value = ( String ) annotation . annotationType ( ) . getMethod ( attributeName ) . invoke ( annotation ) ; } catch ( Exception ex ) { } } return value ; }
Get the value of a Annotation in a class declaration .
102
12
333
private Long string2long ( String text , DateTimeFormat fmt ) { // null or "" returns null if ( text == null ) return null ; text = text . trim ( ) ; if ( text . length ( ) == 0 ) return null ; Date date = fmt . parse ( text ) ; return date != null ? UTCDateBox . date2utc ( date ) : null ; }
Parses the supplied text and converts it to a Long corresponding to that midnight in UTC on the specified date .
81
23
334
private String long2string ( Long value , DateTimeFormat fmt ) { // for html5 inputs, use "" for no value if ( value == null ) return "" ; Date date = UTCDateBox . utc2date ( value ) ; return date != null ? fmt . format ( date ) : null ; }
Formats the supplied value using the specified DateTimeFormat .
65
12
335
public static RgbaColor from ( String color ) { if ( color . startsWith ( "#" ) ) { return fromHex ( color ) ; } else if ( color . startsWith ( "rgba" ) ) { return fromRgba ( color ) ; } else if ( color . startsWith ( "rgb" ) ) { return fromRgb ( color ) ; } else if ( color . startsWith ( "hsla" ) ) { return fromHsla ( color ) ; } else if ( color . startsWith ( "hsl" ) ) { return fromHsl ( color ) ; } else { return getDefaultColor ( ) ; } }
Parses an RgbaColor from a hexadecimal rgb rgba hsl or hsla value .
142
25
336
public static RgbaColor fromHex ( String hex ) { if ( hex . length ( ) == 0 || hex . charAt ( 0 ) != ' ' ) return getDefaultColor ( ) ; // #rgb if ( hex . length ( ) == 4 ) { return new RgbaColor ( parseHex ( hex , 1 , 2 ) , parseHex ( hex , 2 , 3 ) , parseHex ( hex , 3 , 4 ) ) ; } // #rrggbb else if ( hex . length ( ) == 7 ) { return new RgbaColor ( parseHex ( hex , 1 , 3 ) , parseHex ( hex , 3 , 5 ) , parseHex ( hex , 5 , 7 ) ) ; } else { return getDefaultColor ( ) ; } }
Parses an RgbaColor from a hexadecimal value .
169
16
337
public static RgbaColor fromRgb ( String rgb ) { if ( rgb . length ( ) == 0 ) return getDefaultColor ( ) ; String [ ] parts = getRgbParts ( rgb ) . split ( "," ) ; if ( parts . length == 3 ) { return new RgbaColor ( parseInt ( parts [ 0 ] ) , parseInt ( parts [ 1 ] ) , parseInt ( parts [ 2 ] ) ) ; } else { return getDefaultColor ( ) ; } }
Parses an RgbaColor from an rgb value .
106
13
338
public static RgbaColor fromRgba ( String rgba ) { if ( rgba . length ( ) == 0 ) return getDefaultColor ( ) ; String [ ] parts = getRgbaParts ( rgba ) . split ( "," ) ; if ( parts . length == 4 ) { return new RgbaColor ( parseInt ( parts [ 0 ] ) , parseInt ( parts [ 1 ] ) , parseInt ( parts [ 2 ] ) , parseFloat ( parts [ 3 ] ) ) ; } else { return getDefaultColor ( ) ; } }
Parses an RgbaColor from an rgba value .
120
14
339
private RgbaColor withHsl ( int index , float value ) { float [ ] HSL = convertToHsl ( ) ; HSL [ index ] = value ; return RgbaColor . fromHsl ( HSL ) ; }
Returns a new color with a new value of the specified HSL component .
52
15
340
public RgbaColor adjustHue ( float degrees ) { float [ ] HSL = convertToHsl ( ) ; HSL [ 0 ] = hueCheck ( HSL [ 0 ] + degrees ) ; // ensure [0-360) return RgbaColor . fromHsl ( HSL ) ; }
Returns a new color that has the hue adjusted by the specified amount .
66
14
341
public RgbaColor opacify ( float amount ) { return new RgbaColor ( r , g , b , alphaCheck ( a + amount ) ) ; }
Returns a new color that has the alpha adjusted by the specified amount .
36
14
342
protected static final float [ ] getSpreadInRange ( float member , int count , int max , int offset ) { // to find the spread, we first find the min that is a // multiple of max/count away from the member int interval = max / count ; float min = ( member + offset ) % interval ; if ( min == 0 && member == max ) { min += interval ; } float [ ] range = new float [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { range [ i ] = min + interval * i + offset ; } return range ; }
Returns a spread of integers in a range [ 0 max ) that includes count . The spread is sorted from largest to smallest .
126
25
343
public static RgbaColor fromHsl ( float H , float S , float L ) { // convert to [0-1] H /= 360f ; S /= 100f ; L /= 100f ; float R , G , B ; if ( S == 0 ) { // grey R = G = B = L ; } else { float m2 = L <= 0.5 ? L * ( S + 1f ) : L + S - L * S ; float m1 = 2f * L - m2 ; R = hue2rgb ( m1 , m2 , H + 1 / 3f ) ; G = hue2rgb ( m1 , m2 , H ) ; B = hue2rgb ( m1 , m2 , H - 1 / 3f ) ; } // convert [0-1] to [0-255] int r = Math . round ( R * 255f ) ; int g = Math . round ( G * 255f ) ; int b = Math . round ( B * 255f ) ; return new RgbaColor ( r , g , b , 1 ) ; }
Creates a new RgbaColor from the specified HSL components .
240
15
344
private float max ( float x , float y , float z ) { if ( x > y ) { // not y if ( x > z ) { return x ; } else { return z ; } } else { // not x if ( y > z ) { return y ; } else { return z ; } } }
misc utility methods
66
3
345
public Constructor < ? > getCompatibleConstructor ( Class < ? > type , Class < ? > argumentType ) { try { return type . getConstructor ( new Class [ ] { argumentType } ) ; } catch ( Exception e ) { // get public classes and interfaces Class < ? > [ ] types = type . getClasses ( ) ; for ( int i = 0 ; i < types . length ; i ++ ) { try { return type . getConstructor ( new Class [ ] { types [ i ] } ) ; } catch ( Exception e1 ) { } } } return null ; }
Get a compatible constructor
127
4
346
public < T > T convert ( Object source , TypeReference < T > typeReference ) throws ConverterException { return ( T ) convert ( new ConversionContext ( ) , source , typeReference ) ; }
Convert an object to another object with given type
42
10
347
public < T > T convert ( ConversionContext context , Object source , TypeReference < T > destinationType ) throws ConverterException { try { return ( T ) multiConverter . convert ( context , source , destinationType ) ; } catch ( ConverterException e ) { throw e ; } catch ( Exception e ) { // There is a problem with one converter. This should not happen. // Either there is a bug in this converter or it is not properly // configured throw new ConverterException ( MessageFormat . format ( "Could not convert given object with class ''{0}'' to object with type signature ''{1}''" , source == null ? "null" : source . getClass ( ) . getName ( ) , destinationType ) , e ) ; } }
Convert an object to another object given a parameterized type signature
162
13
348
public static int compare ( double a , double b , double delta ) { if ( equals ( a , b , delta ) ) { return 0 ; } return Double . compare ( a , b ) ; }
Compares two double values up to some delta .
42
10
349
public double getValue ( int [ ] batch ) { double value = 0.0 ; for ( int i = 0 ; i < batch . length ; i ++ ) { value += getValue ( i ) ; } return value ; }
Gets value of this function at the current point computed on the given batch of examples .
48
18
350
public void getGradient ( int [ ] batch , double [ ] gradient ) { for ( int i = 0 ; i < batch . length ; i ++ ) { addGradient ( i , gradient ) ; } }
Gets the gradient at the current point computed on the given batch of examples .
45
16
351
public synchronized static SQLiteDatabase getConnection ( Context context ) { if ( database == null ) { // Construct the single helper and open the unique(!) db connection for the app database = new CupboardDbHelper ( context . getApplicationContext ( ) ) . getWritableDatabase ( ) ; } return database ; }
Returns a raw handle to the SQLite database connection . Do not close!
65
15
352
@ SuppressWarnings ( "unchecked" ) public static Type getSuperclassTypeParameter ( Class < ? > subclass ) { Type superclass = subclass . getGenericSuperclass ( ) ; if ( superclass instanceof Class ) { throw new RuntimeException ( "Missing type parameter." ) ; } return ( ( ParameterizedType ) superclass ) . getActualTypeArguments ( ) [ 0 ] ; }
Gets type from super class s type parameter .
88
10
353
@ Override protected void onLoad ( ) { super . onLoad ( ) ; // these styles need to be the same for the box and shadow so // that we can measure properly matchStyles ( "display" ) ; matchStyles ( "fontSize" ) ; matchStyles ( "fontFamily" ) ; matchStyles ( "fontWeight" ) ; matchStyles ( "lineHeight" ) ; matchStyles ( "paddingTop" ) ; matchStyles ( "paddingRight" ) ; matchStyles ( "paddingBottom" ) ; matchStyles ( "paddingLeft" ) ; adjustSize ( ) ; }
Matches the styles and adjusts the size . This needs to be called after the input is added to the DOM so we do it in onLoad .
132
30
354
@ Override public void onKeyDown ( KeyDownEvent event ) { char c = MiscUtils . getCharCode ( event . getNativeEvent ( ) ) ; onKeyCodeEvent ( event , box . getValue ( ) + c ) ; }
On key down we assume the key will go at the end . It s the most common case and not that distracting if that s not true .
53
29
355
public static void setEnabled ( Element element , boolean enabled ) { element . setPropertyBoolean ( "disabled" , ! enabled ) ; setStyleName ( element , "disabled" , ! enabled ) ; }
It s enough to just set the disabled attribute on the element but we want to also add a disabled class so that we can style it .
43
28
356
private Method getPropertySourceMethod ( Object sourceObject , Object destinationObject , String destinationProperty ) { BeanToBeanMapping beanToBeanMapping = beanToBeanMappings . get ( ClassPair . get ( sourceObject . getClass ( ) , destinationObject . getClass ( ) ) ) ; String sourceProperty = null ; if ( beanToBeanMapping != null ) { sourceProperty = beanToBeanMapping . getSourceProperty ( destinationProperty ) ; } if ( sourceProperty == null ) { sourceProperty = destinationProperty ; } return BeanUtils . getGetterPropertyMethod ( sourceObject . getClass ( ) , sourceProperty ) ; }
get the property source method corresponding to given destination property
142
10
357
protected TypeReference < ? > getBeanPropertyType ( Class < ? > clazz , String propertyName , TypeReference < ? > originalType ) { TypeReference < ? > propertyDestinationType = null ; if ( beanDestinationPropertyTypeProvider != null ) { propertyDestinationType = beanDestinationPropertyTypeProvider . getPropertyType ( clazz , propertyName , originalType ) ; } if ( propertyDestinationType == null ) { propertyDestinationType = originalType ; } return propertyDestinationType ; }
get the bean property type
109
5
358
public void addBeanToBeanMapping ( BeanToBeanMapping beanToBeanMapping ) { beanToBeanMappings . put ( ClassPair . get ( beanToBeanMapping . getSourceClass ( ) , beanToBeanMapping . getDestinationClass ( ) ) , beanToBeanMapping ) ; }
Add a mapping of properties between two beans
77
8
359
public static SPIProvider getInstance ( ) { if ( me == null ) { final ClassLoader cl = ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ; me = SPIProviderResolver . getInstance ( cl ) . getProvider ( ) ; } return me ; }
Gets the a singleton reference to the SPIProvider returned by the SPIProviderResolver retrieved using the default server integration classloader .
63
27
360
public < T > T getSPI ( Class < T > spiType ) { return getSPI ( spiType , SecurityActions . getContextClassLoader ( ) ) ; }
Gets the specified SPI using the current thread context classloader
40
12
361
public Optional < SoyMsgBundle > resolve ( final Optional < Locale > locale ) throws IOException { if ( ! locale . isPresent ( ) ) { return Optional . absent ( ) ; } synchronized ( msgBundles ) { SoyMsgBundle soyMsgBundle = null ; if ( isHotReloadModeOff ( ) ) { soyMsgBundle = msgBundles . get ( locale . get ( ) ) ; } if ( soyMsgBundle == null ) { soyMsgBundle = createSoyMsgBundle ( locale . get ( ) ) ; if ( soyMsgBundle == null ) { soyMsgBundle = createSoyMsgBundle ( new Locale ( locale . get ( ) . getLanguage ( ) ) ) ; } if ( soyMsgBundle == null && fallbackToEnglish ) { soyMsgBundle = createSoyMsgBundle ( Locale . ENGLISH ) ; } if ( soyMsgBundle == null ) { return Optional . absent ( ) ; } if ( isHotReloadModeOff ( ) ) { msgBundles . put ( locale . get ( ) , soyMsgBundle ) ; } } return Optional . fromNullable ( soyMsgBundle ) ; } }
Based on a provided locale return a SoyMsgBundle file .
263
13
362
private Optional < ? extends SoyMsgBundle > mergeMsgBundles ( final Locale locale , final List < SoyMsgBundle > soyMsgBundles ) { if ( soyMsgBundles . isEmpty ( ) ) { return Optional . absent ( ) ; } final List < SoyMsg > msgs = Lists . newArrayList ( ) ; for ( final SoyMsgBundle smb : soyMsgBundles ) { for ( final Iterator < SoyMsg > it = smb . iterator ( ) ; it . hasNext ( ) ; ) { msgs . add ( it . next ( ) ) ; } } return Optional . of ( new SoyMsgBundleImpl ( locale . toString ( ) , msgs ) ) ; }
Merge msg bundles together creating new MsgBundle with merges msg bundles passed in as a method argument
158
22
363
@ Override public Optional < String > hash ( final Optional < URL > url ) throws IOException { if ( ! url . isPresent ( ) ) { return Optional . absent ( ) ; } logger . debug ( "Calculating md5 hash, url:{}" , url ) ; if ( isHotReloadModeOff ( ) ) { final String md5 = cache . getIfPresent ( url . get ( ) ) ; logger . debug ( "md5 hash:{}" , md5 ) ; if ( md5 != null ) { return Optional . of ( md5 ) ; } } final InputStream is = url . get ( ) . openStream ( ) ; final String md5 = getMD5Checksum ( is ) ; if ( isHotReloadModeOff ( ) ) { logger . debug ( "caching url:{} with hash:{}" , url , md5 ) ; cache . put ( url . get ( ) , md5 ) ; } return Optional . fromNullable ( md5 ) ; }
Calculates a md5 hash for an url
214
10
364
public static String [ ] allUpperCase ( String ... strings ) { String [ ] tmp = new String [ strings . length ] ; for ( int idx = 0 ; idx < strings . length ; idx ++ ) { if ( strings [ idx ] != null ) { tmp [ idx ] = strings [ idx ] . toUpperCase ( ) ; } } return tmp ; }
Make all elements of a String array upper case .
84
10
365
public static String [ ] allLowerCase ( String ... strings ) { String [ ] tmp = new String [ strings . length ] ; for ( int idx = 0 ; idx < strings . length ; idx ++ ) { if ( strings [ idx ] != null ) { tmp [ idx ] = strings [ idx ] . toLowerCase ( ) ; } } return tmp ; }
Make all elements of a String array lower case .
82
10
366
public FullTypeSignature getTypeErasureSignature ( ) { if ( typeErasureSignature == null ) { typeErasureSignature = new ClassTypeSignature ( binaryName , new TypeArgSignature [ 0 ] , ownerTypeSignature == null ? null : ( ClassTypeSignature ) ownerTypeSignature . getTypeErasureSignature ( ) ) ; } return typeErasureSignature ; }
get the type erasure signature
88
6
367
public MIMEType addParameter ( String name , String value ) { Map < String , String > copy = new LinkedHashMap <> ( this . parameters ) ; copy . put ( name , value ) ; return new MIMEType ( type , subType , copy ) ; }
Adds a parameter to the MIMEType .
61
10
368
@ Override public List < String > contentTypes ( ) { List < String > contentTypes = null ; final HttpServletRequest request = getHttpRequest ( ) ; if ( favorParameterOverAcceptHeader ) { contentTypes = getFavoredParameterValueAsList ( request ) ; } else { contentTypes = getAcceptHeaderValues ( request ) ; } if ( isEmpty ( contentTypes ) ) { logger . debug ( "Setting content types to default: {}." , DEFAULT_SUPPORTED_CONTENT_TYPES ) ; contentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES ; } return unmodifiableList ( contentTypes ) ; }
Returns requested content types or default content type if none found .
142
12
369
public Headers getAllHeaders ( ) { Headers requestHeaders = getHeaders ( ) ; requestHeaders = hasPayload ( ) ? requestHeaders . withContentType ( getPayload ( ) . get ( ) . getMimeType ( ) ) : requestHeaders ; //We don't want to add headers more than once. return requestHeaders ; }
Returns all headers with the headers from the Payload
80
10
370
public static Optimizer < DifferentiableFunction > getRegularizedOptimizer ( final Optimizer < DifferentiableFunction > opt , final double l1Lambda , final double l2Lambda ) { if ( l1Lambda == 0 && l2Lambda == 0 ) { return opt ; } return new Optimizer < DifferentiableFunction > ( ) { @ Override public boolean minimize ( DifferentiableFunction objective , IntDoubleVector point ) { DifferentiableFunction fn = getRegularizedFn ( objective , false , l1Lambda , l2Lambda ) ; return opt . minimize ( fn , point ) ; } } ; }
Converts a standard optimizer to one which the given amount of l1 or l2 regularization .
138
21
371
public String toRomanNumeral ( ) { if ( this . romanString == null ) { this . romanString = "" ; int remainder = this . value ; for ( int i = 0 ; i < BASIC_VALUES . length ; i ++ ) { while ( remainder >= BASIC_VALUES [ i ] ) { this . romanString += BASIC_ROMAN_NUMERALS [ i ] ; remainder -= BASIC_VALUES [ i ] ; } } } return this . romanString ; }
Get the Roman Numeral of the current value
111
9
372
public void takeNoteOfGradient ( IntDoubleVector gradient ) { gradient . iterate ( new FnIntDoubleToVoid ( ) { @ Override public void call ( int index , double value ) { gradSumSquares [ index ] += value * value ; assert ! Double . isNaN ( gradSumSquares [ index ] ) ; } } ) ; }
A tie - in for subclasses such as AdaGrad .
77
12
373
private ArrayTypeSignature getArrayTypeSignature ( GenericArrayType genericArrayType ) { FullTypeSignature componentTypeSignature = getFullTypeSignature ( genericArrayType . getGenericComponentType ( ) ) ; ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature ( componentTypeSignature ) ; return arrayTypeSignature ; }
get the ArrayTypeSignature corresponding to given generic array type
74
12
374
private ClassTypeSignature getClassTypeSignature ( ParameterizedType parameterizedType ) { Class < ? > rawType = ( Class < ? > ) parameterizedType . getRawType ( ) ; Type [ ] typeArguments = parameterizedType . getActualTypeArguments ( ) ; TypeArgSignature [ ] typeArgSignatures = new TypeArgSignature [ typeArguments . length ] ; for ( int i = 0 ; i < typeArguments . length ; i ++ ) { typeArgSignatures [ i ] = getTypeArgSignature ( typeArguments [ i ] ) ; } String binaryName = rawType . isMemberClass ( ) ? rawType . getSimpleName ( ) : rawType . getName ( ) ; ClassTypeSignature ownerTypeSignature = parameterizedType . getOwnerType ( ) == null ? null : ( ClassTypeSignature ) getFullTypeSignature ( parameterizedType . getOwnerType ( ) ) ; ClassTypeSignature classTypeSignature = new ClassTypeSignature ( binaryName , typeArgSignatures , ownerTypeSignature ) ; return classTypeSignature ; }
get the ClassTypeSignature corresponding to given parameterized type
241
12
375
private FullTypeSignature getTypeSignature ( Class < ? > clazz ) { StringBuilder sb = new StringBuilder ( ) ; if ( clazz . isArray ( ) ) { sb . append ( clazz . getName ( ) ) ; } else if ( clazz . isPrimitive ( ) ) { sb . append ( primitiveTypesMap . get ( clazz ) . toString ( ) ) ; } else { sb . append ( ' ' ) . append ( clazz . getName ( ) ) . append ( ' ' ) ; } return TypeSignatureFactory . getTypeSignature ( sb . toString ( ) , false ) ; }
get the type signature corresponding to given class
142
8
376
private TypeArgSignature getTypeArgSignature ( Type type ) { if ( type instanceof WildcardType ) { WildcardType wildcardType = ( WildcardType ) type ; Type lowerBound = wildcardType . getLowerBounds ( ) . length == 0 ? null : wildcardType . getLowerBounds ( ) [ 0 ] ; Type upperBound = wildcardType . getUpperBounds ( ) . length == 0 ? null : wildcardType . getUpperBounds ( ) [ 0 ] ; if ( lowerBound == null && Object . class . equals ( upperBound ) ) { return new TypeArgSignature ( TypeArgSignature . UNBOUNDED_WILDCARD , ( FieldTypeSignature ) getFullTypeSignature ( upperBound ) ) ; } else if ( lowerBound == null && upperBound != null ) { return new TypeArgSignature ( TypeArgSignature . UPPERBOUND_WILDCARD , ( FieldTypeSignature ) getFullTypeSignature ( upperBound ) ) ; } else if ( lowerBound != null ) { return new TypeArgSignature ( TypeArgSignature . LOWERBOUND_WILDCARD , ( FieldTypeSignature ) getFullTypeSignature ( lowerBound ) ) ; } else { throw new RuntimeException ( "Invalid type" ) ; } } else { return new TypeArgSignature ( TypeArgSignature . NO_WILDCARD , ( FieldTypeSignature ) getFullTypeSignature ( type ) ) ; } }
get the TypeArgSignature corresponding to given type
327
10
377
public static boolean zipFolder ( File folder , String fileName ) { boolean success = false ; if ( ! folder . isDirectory ( ) ) { return false ; } if ( fileName == null ) { fileName = folder . getAbsolutePath ( ) + ZIP_EXT ; } ZipArchiveOutputStream zipOutput = null ; try { zipOutput = new ZipArchiveOutputStream ( new File ( fileName ) ) ; success = addFolderContentToZip ( folder , zipOutput , "" ) ; zipOutput . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } finally { try { if ( zipOutput != null ) { zipOutput . close ( ) ; } } catch ( IOException e ) { } } return success ; }
Utility function to zip the content of an entire folder but not the folder itself .
167
17
378
public static boolean unzipFileOrFolder ( File zipFile , String unzippedFolder ) { InputStream is ; ArchiveInputStream in = null ; OutputStream out = null ; if ( ! zipFile . isFile ( ) ) { return false ; } if ( unzippedFolder == null ) { unzippedFolder = FilenameUtils . removeExtension ( zipFile . getAbsolutePath ( ) ) ; } try { is = new FileInputStream ( zipFile ) ; new File ( unzippedFolder ) . mkdir ( ) ; in = new ArchiveStreamFactory ( ) . createArchiveInputStream ( ArchiveStreamFactory . ZIP , is ) ; ZipArchiveEntry entry = ( ZipArchiveEntry ) in . getNextEntry ( ) ; while ( entry != null ) { if ( entry . isDirectory ( ) ) { new File ( unzippedFolder , entry . getName ( ) ) . mkdir ( ) ; } else { out = new FileOutputStream ( new File ( unzippedFolder , entry . getName ( ) ) ) ; IOUtils . copy ( in , out ) ; out . close ( ) ; out = null ; } entry = ( ZipArchiveEntry ) in . getNextEntry ( ) ; } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } catch ( ArchiveException e ) { e . printStackTrace ( ) ; return false ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { } } if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { } } } return true ; }
Unzip a file or a folder
385
7
379
protected static final String formatUsingFormat ( Long value , DateTimeFormat fmt ) { if ( value == null ) { return "" ; } else { // midnight GMT Date date = new Date ( 0 ) ; // offset by timezone and value date . setTime ( UTCDateBox . timezoneOffsetMillis ( date ) + value . longValue ( ) ) ; // format it return fmt . format ( date ) ; } }
Formats the value provided with the specified DateTimeFormat
88
11
380
protected static final Long parseUsingFallbacksWithColon ( String text , DateTimeFormat timeFormat ) { if ( text . indexOf ( ' ' ) == - 1 ) { text = text . replace ( " " , "" ) ; int numdigits = 0 ; int lastdigit = 0 ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; if ( Character . isDigit ( c ) ) { numdigits ++ ; lastdigit = i ; } } if ( numdigits == 1 || numdigits == 2 ) { // insert :00 int colon = lastdigit + 1 ; text = text . substring ( 0 , colon ) + ":00" + text . substring ( colon ) ; } else if ( numdigits > 2 ) { // insert : int colon = lastdigit - 1 ; text = text . substring ( 0 , colon ) + ":" + text . substring ( colon ) ; } return parseUsingFallbacks ( text , timeFormat ) ; } else { return null ; } }
Attempts to insert a colon so that a value without a colon can be parsed .
234
16
381
public static Class < ? > getRawType ( Type type ) { if ( type instanceof Class ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType actualType = ( ParameterizedType ) type ; return getRawType ( actualType . getRawType ( ) ) ; } else if ( type instanceof GenericArrayType ) { GenericArrayType genericArrayType = ( GenericArrayType ) type ; Object rawArrayType = Array . newInstance ( getRawType ( genericArrayType . getGenericComponentType ( ) ) , 0 ) ; return rawArrayType . getClass ( ) ; } else if ( type instanceof WildcardType ) { WildcardType castedType = ( WildcardType ) type ; return getRawType ( castedType . getUpperBounds ( ) [ 0 ] ) ; } else { throw new IllegalArgumentException ( "Type \'" + type + "\' is not a Class, " + "ParameterizedType, or GenericArrayType. Can't extract class." ) ; } }
This method returns the actual raw class associated with the specified type .
231
13
382
public static boolean isAssignableFrom ( TypeReference < ? > from , TypeReference < ? > to ) { if ( from == null ) { return false ; } if ( to . equals ( from ) ) { return true ; } if ( to . getType ( ) instanceof Class ) { return to . getRawType ( ) . isAssignableFrom ( from . getRawType ( ) ) ; } else if ( to . getType ( ) instanceof ParameterizedType ) { return isAssignableFrom ( from . getType ( ) , ( ParameterizedType ) to . getType ( ) , new HashMap < String , Type > ( ) ) ; } else if ( to . getType ( ) instanceof GenericArrayType ) { return to . getRawType ( ) . isAssignableFrom ( from . getRawType ( ) ) && isAssignableFrom ( from . getType ( ) , ( GenericArrayType ) to . getType ( ) ) ; } else { throw new AssertionError ( "Unexpected Type : " + to ) ; } }
Check if this type is assignable from the given Type .
232
12
383
private static boolean isAssignableFrom ( Type from , ParameterizedType to , Map < String , Type > typeVarMap ) { if ( from == null ) { return false ; } if ( to . equals ( from ) ) { return true ; } // First figure out the class and any type information. Class < ? > clazz = getRawType ( from ) ; ParameterizedType ptype = null ; if ( from instanceof ParameterizedType ) { ptype = ( ParameterizedType ) from ; } // Load up parameterized variable info if it was parameterized. if ( ptype != null ) { Type [ ] tArgs = ptype . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] tParams = clazz . getTypeParameters ( ) ; for ( int i = 0 ; i < tArgs . length ; i ++ ) { Type arg = tArgs [ i ] ; TypeVariable < ? > var = tParams [ i ] ; while ( arg instanceof TypeVariable ) { TypeVariable < ? > v = ( TypeVariable < ? > ) arg ; arg = typeVarMap . get ( v . getName ( ) ) ; } typeVarMap . put ( var . getName ( ) , arg ) ; } // check if they are equivalent under our current mapping. if ( typeEquals ( ptype , to , typeVarMap ) ) { return true ; } } for ( Type itype : clazz . getGenericInterfaces ( ) ) { if ( isAssignableFrom ( itype , to , new HashMap < String , Type > ( typeVarMap ) ) ) { return true ; } } // Interfaces didn't work, try the superclass. Type sType = clazz . getGenericSuperclass ( ) ; if ( isAssignableFrom ( sType , to , new HashMap < String , Type > ( typeVarMap ) ) ) { return true ; } return false ; }
Private recursive helper function to actually do the type - safe checking of assignability .
417
16
384
private static boolean typeEquals ( ParameterizedType from , ParameterizedType to , Map < String , Type > typeVarMap ) { if ( from . getRawType ( ) . equals ( to . getRawType ( ) ) ) { Type [ ] fromArgs = from . getActualTypeArguments ( ) ; Type [ ] toArgs = to . getActualTypeArguments ( ) ; for ( int i = 0 ; i < fromArgs . length ; i ++ ) { if ( ! matches ( fromArgs [ i ] , toArgs [ i ] , typeVarMap ) ) { return false ; } } return true ; } return false ; }
Checks if two parameterized types are exactly equal under the variable replacement described in the typeVarMap .
140
21
385
private static boolean matches ( Type from , Type to , Map < String , Type > typeMap ) { if ( to . equals ( from ) ) return true ; if ( from instanceof TypeVariable ) { return to . equals ( typeMap . get ( ( ( TypeVariable < ? > ) from ) . getName ( ) ) ) ; } return false ; }
Checks if two types are the same or are equivalent under a variable mapping given in the type map that was provided .
75
24
386
private static boolean isAssignableFrom ( Type from , GenericArrayType to ) { Type toGenericComponentType = to . getGenericComponentType ( ) ; if ( toGenericComponentType instanceof ParameterizedType ) { Type t = from ; if ( from instanceof GenericArrayType ) { t = ( ( GenericArrayType ) from ) . getGenericComponentType ( ) ; } else if ( from instanceof Class ) { Class < ? > classType = ( Class < ? > ) from ; while ( classType . isArray ( ) ) { classType = classType . getComponentType ( ) ; } t = classType ; } return isAssignableFrom ( t , ( ParameterizedType ) toGenericComponentType , new HashMap < String , Type > ( ) ) ; } // No generic defined on "to"; therefore, return true and let other // checks determine assignability return true ; }
Private helper function that performs some assignability checks for the provided GenericArrayType .
192
16
387
@ Override public void setValue ( String value , boolean fireEvents ) { boolean added = setSelectedValue ( this , value , addMissingValue ) ; if ( added && fireEvents ) { ValueChangeEvent . fire ( this , getValue ( ) ) ; } }
Selects the specified value in the list .
57
9
388
public static final String getSelectedValue ( ListBox list ) { int index = list . getSelectedIndex ( ) ; return ( index >= 0 ) ? list . getValue ( index ) : null ; }
Utility function to get the current value .
44
9
389
public static final String getSelectedText ( ListBox list ) { int index = list . getSelectedIndex ( ) ; return ( index >= 0 ) ? list . getItemText ( index ) : null ; }
Utility function to get the current text .
45
9
390
public static final int findValueInListBox ( ListBox list , String value ) { for ( int i = 0 ; i < list . getItemCount ( ) ; i ++ ) { if ( value . equals ( list . getValue ( i ) ) ) { return i ; } } return - 1 ; }
Utility function to find the first index of a value in a ListBox .
65
16
391
public static final boolean setSelectedValue ( ListBox list , String value , boolean addMissingValues ) { if ( value == null ) { list . setSelectedIndex ( 0 ) ; return false ; } else { int index = findValueInListBox ( list , value ) ; if ( index >= 0 ) { list . setSelectedIndex ( index ) ; return true ; } if ( addMissingValues ) { list . addItem ( value , value ) ; // now that it's there, search again index = findValueInListBox ( list , value ) ; list . setSelectedIndex ( index ) ; return true ; } return false ; } }
Utility function to set the current value in a ListBox .
138
13
392
public static String capitalizePropertyName ( String s ) { if ( s . length ( ) == 0 ) { return s ; } char [ ] chars = s . toCharArray ( ) ; chars [ 0 ] = Character . toUpperCase ( chars [ 0 ] ) ; return new String ( chars ) ; }
Return a capitalized version of the specified property name .
65
11
393
public static Method getGetterPropertyMethod ( Class < ? > type , String propertyName ) { String sourceMethodName = "get" + BeanUtils . capitalizePropertyName ( propertyName ) ; Method sourceMethod = BeanUtils . getMethod ( type , sourceMethodName ) ; if ( sourceMethod == null ) { sourceMethodName = "is" + BeanUtils . capitalizePropertyName ( propertyName ) ; sourceMethod = BeanUtils . getMethod ( type , sourceMethodName ) ; if ( sourceMethod != null && sourceMethod . getReturnType ( ) != Boolean . TYPE ) { sourceMethod = null ; } } return sourceMethod ; }
get the getter method corresponding to given property
137
9
394
public static Method getSetterPropertyMethod ( Class < ? > type , String propertyName ) { String sourceMethodName = "set" + BeanUtils . capitalizePropertyName ( propertyName ) ; Method sourceMethod = BeanUtils . getMethod ( type , sourceMethodName ) ; return sourceMethod ; }
get the setter method corresponding to given property
64
9
395
@ Override public Optional < SoyMapData > toSoyMap ( @ Nullable final Object model ) throws Exception { if ( model instanceof SoyMapData ) { return Optional . of ( ( SoyMapData ) model ) ; } if ( model instanceof Map ) { return Optional . of ( new SoyMapData ( model ) ) ; } return Optional . of ( new SoyMapData ( ) ) ; }
Pass a model object and return a SoyMapData if a model object happens to be a SoyMapData .
86
22
396
@ Override public int getShadowSize ( ) { Element shadowElement = shadow . getElement ( ) ; shadowElement . setScrollTop ( 10000 ) ; return shadowElement . getScrollTop ( ) ; }
Returns the size of the shadow element
43
7
397
public Object get ( IConverter converter , Object sourceObject , TypeReference < ? > destinationType ) { return convertedObjects . get ( new ConvertedObjectsKey ( converter , sourceObject , destinationType ) ) ; }
get the converted object corresponding to sourceObject as converted to destination type by converter
47
15
398
public void add ( IConverter converter , Object sourceObject , TypeReference < ? > destinationType , Object convertedObject ) { convertedObjects . put ( new ConvertedObjectsKey ( converter , sourceObject , destinationType ) , convertedObject ) ; }
add a converted object to the pool
53
7
399
public void remove ( IConverter converter , Object sourceObject , TypeReference < ? > destinationType ) { convertedObjects . remove ( new ConvertedObjectsKey ( converter , sourceObject , destinationType ) ) ; }
remove a converted object from the pool
46
7