idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,200
private static void createCurrencies ( TypeSpec . Builder type , List < String > currencies ) { TypeSpec . Builder currencyType = TypeSpec . enumBuilder ( "Currency" ) . addModifiers ( PUBLIC , STATIC ) ; List < String > codes = new ArrayList < > ( ) ; codes . addAll ( currencies ) ; Collections . sort ( codes ) ; Stri...
Create top - level container to hold currency constants .
5,201
protected static Unit selectExactUnit ( String compact , UnitConverter converter ) { if ( compact != null ) { switch ( compact ) { case "consumption" : return converter . consumptionUnit ( ) ; case "light" : return Unit . LUX ; case "speed" : return converter . speedUnit ( ) ; case "temp" : case "temperature" : return ...
Some categories only have a single possible unit depending the locale .
5,202
protected static Unit inputFromExactUnit ( Unit exact , UnitConverter converter ) { switch ( exact ) { case TERABIT : case GIGABIT : case MEGABIT : case KILOBIT : case BIT : return Unit . BIT ; case TERABYTE : case GIGABYTE : case MEGABYTE : case KILOBYTE : case BYTE : return Unit . BYTE ; default : break ; } UnitCateg...
Based on the unit we re converting to guess the input unit . For example if we re converting to MEGABIT and no input unit was specified assume BIT .
5,203
protected static UnitFactorSet getDefaultFactorSet ( UnitCategory category , UnitConverter converter ) { switch ( category ) { case ANGLE : return UnitFactorSets . ANGLE ; case AREA : return converter . areaFactors ( ) ; case DURATION : return UnitFactorSets . DURATION ; case ELECTRIC : return UnitFactorSets . ELECTRIC...
Default conversion factors for each category . Some of these differ based on the locale of the converter .
5,204
public String render ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Node node : parsed ) { if ( node instanceof Symbol ) { switch ( ( Symbol ) node ) { case MINUS : buf . append ( '-' ) ; break ; case CURRENCY : buf . append ( CURRENCY_SYM ) ; break ; case PERCENT : buf . append ( '%' ) ; break ; } } else if (...
Render a parseable representation of this pattern .
5,205
public String dump ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( " LOCALE MATCHED BUNDLE\n" ) ; buf . append ( " ====== ==============\n" ) ; List < MetaLocale > keys = availableBundlesMap . keySet ( ) . stream ( ) . map ( k -> ( MetaLocale ) k ) . collect ( Collec...
Inspect the mapping between permutations of locale fields and bundle identifiers .
5,206
private void buildMap ( List < CLDR . Locale > availableBundles ) { List < MetaLocale > maxBundleIds = new ArrayList < > ( ) ; for ( CLDR . Locale locale : availableBundles ) { MetaLocale source = ( MetaLocale ) locale ; if ( source . isRoot ( ) ) { continue ; } MetaLocale maxBundleId = languageResolver . addLikelySubt...
Iterate over the available bundle identifiers expand them and index all permutations to enable a fast direct lookup .
5,207
private void indexPermutations ( MetaLocale bundleId ) { MetaLocale key = bundleId . copy ( ) ; for ( int flags : LanguageResolver . MATCH_ORDER ) { LanguageResolver . set ( bundleId , key , flags ) ; MetaLocale maxBundleId = languageResolver . addLikelySubtags ( key ) ; MetaLocale source = availableBundlesMap . get ( ...
Index permutations of the given bundle identifier . We iterate over the field permutations and expand each to the maximum bundle identifier then query to see if that max bundle identifier matches a bundle . Then we index the permutation to that bundle . This creates a static mapping mimicking a dynamic lookup .
5,208
public Map < LocaleID , ClassName > generate ( Path outputDir , DataReader reader ) throws IOException { Map < LocaleID , ClassName > dateClasses = new TreeMap < > ( ) ; List < DateTimeData > dateTimeDataList = new ArrayList < > ( ) ; for ( Map . Entry < LocaleID , DateTimeData > entry : reader . calendars ( ) . entryS...
Generates the date - time classes into the given output directory .
5,209
private void addSkeletonClassifierMethod ( TypeSpec . Builder type , List < DateTimeData > dataList ) { Set < String > dates = new LinkedHashSet < > ( ) ; Set < String > times = new LinkedHashSet < > ( ) ; for ( DateTimeData data : dataList ) { for ( Skeleton skeleton : data . dateTimeSkeletons ) { if ( isDateSkeleton ...
Create a helper class to classify skeletons as either DATE or TIME .
5,210
private void addMetaZones ( TypeSpec . Builder type , Map < String , MetaZone > metazones ) { ClassName metazoneType = ClassName . get ( Types . PACKAGE_CLDR_DATES , "MetaZone" ) ; TypeName mapType = ParameterizedTypeName . get ( MAP , STRING , metazoneType ) ; FieldSpec . Builder field = FieldSpec . builder ( mapType ...
Populate the metaZone mapping .
5,211
private void buildTimeZoneAliases ( TypeSpec . Builder type , Map < String , String > map ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "getTimeZoneAlias" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( String . class , "zoneId" ) . returns ( String . class ) ; method . beginControlFlow ( "switch...
Creates a switch table to resolve a retired time zone to a valid one .
5,212
private TypeSpec createFormatter ( DateTimeData dateTimeData , TimeZoneData timeZoneData , String className ) { LocaleID id = dateTimeData . id ; MethodSpec . Builder constructor = MethodSpec . constructorBuilder ( ) . addModifiers ( PUBLIC ) ; constructor . addStatement ( "this.bundleId = $T.$L" , CLDR_LOCALE_IF , id ...
Create a Java class that captures all data formats for a given locale .
5,213
private void addTypedPattern ( MethodSpec . Builder method , String formatType , String pattern ) { method . beginControlFlow ( "case $L:" , formatType ) ; method . addComment ( "$S" , pattern ) ; addPattern ( method , pattern ) ; method . addStatement ( "break" ) ; method . endControlFlow ( ) ; }
Adds the pattern builder statements for a typed pattern .
5,214
private void addPattern ( MethodSpec . Builder method , String pattern ) { for ( Node node : DATETIME_PARSER . parse ( pattern ) ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; method . addSt...
Add a named date - time pattern adding statements to the formatting and indexing methods . Returns true if the pattern corresponds to a date ; false if a time .
5,215
private MethodSpec buildSkeletonFormatter ( List < Skeleton > skeletons ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "formatSkeleton" ) . addAnnotation ( Override . class ) . addModifiers ( PUBLIC ) . addParameter ( String . class , "skeleton" ) . addParameter ( ZonedDateTime . class , "d" ) . addPara...
Implements the formatSkeleton method .
5,216
private MethodSpec buildIntervalMethod ( Map < String , Map < String , String > > intervalFormats , String fallback ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "formatInterval" ) . addAnnotation ( Override . class ) . addModifiers ( PUBLIC ) . addParameter ( ZonedDateTime . class , "s" ) . addParamet...
Build methods to format date time intervals using the field of greatest difference .
5,217
private void addIntervalPattern ( MethodSpec . Builder method , List < Node > pattern , String which ) { for ( Node node : pattern ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; method . add...
Adds code to format a date time interval pattern which may be the start or end date time signified by the which parameter .
5,218
private void addIntervalFallback ( MethodSpec . Builder method , String pattern ) { method . addComment ( "$S" , pattern ) ; for ( Node node : WRAPPER_PARSER . parseWrapper ( pattern ) ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof...
Adds code to render the fallback pattern .
5,219
private boolean isDateSkeleton ( String skeleton ) { List < String > parts = Splitter . on ( '-' ) . splitToList ( skeleton ) ; if ( parts . size ( ) > 1 ) { skeleton = parts . get ( 0 ) ; } for ( Node node : DATETIME_PARSER . parse ( skeleton ) ) { if ( node instanceof Field ) { Field field = ( Field ) node ; switch (...
Indicates a skeleton represents a date based on the fields it contains . Any time - related field will cause this to return false .
5,220
private MethodSpec . Builder buildSkeletonType ( Set < String > dateSkeletons , Set < String > timeSkeletons ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "skeletonType" ) . addJavadoc ( "Indicates whether a given skeleton pattern is a DATE or TIME.\n" ) . addModifiers ( PUBLIC , STATIC ) . addParamete...
Constructs a method to indicate if the skeleton is a DATE or TIME or null if unsupported .
5,221
private void variantsFieldInit ( MethodSpec . Builder method , String fieldName , Variants v ) { Stmt b = new Stmt ( ) ; b . append ( "$L = new $T(" , fieldName , FIELD_VARIANTS ) ; b . append ( "\n " ) . append ( v . abbreviated ) . comma ( ) ; b . append ( "\n " ) . append ( v . narrow ) . comma ( ) ; b . append ( ...
Appends a statement that initializes a FieldVariants field in the superclass .
5,222
private void buildTimeZoneExemplarCities ( MethodSpec . Builder method , TimeZoneData data ) { CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "this.exemplarCities = new $T<$T, $T>() {" , HashMap . class , String . class , String . class ) ; for ( TimeZoneInfo info : data . timeZoneInfo )...
Mapping locale identifiers to their localized exemplar cities .
5,223
private void buildMetaZoneNames ( MethodSpec . Builder method , TimeZoneData data ) { CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "\nthis.$L = new $T<$T, $T>() {" , "metazoneNames" , HASHMAP , STRING , TIMEZONE_NAMES ) ; for ( MetaZoneInfo info : data . metaZoneInfo ) { if ( info . na...
Builds localized metazone name mapping .
5,224
private MethodSpec buildWrapTimeZoneGMTMethod ( TimeZoneData data ) { String [ ] hourFormat = data . hourFormat . split ( ";" ) ; List < Node > positive = DATETIME_PARSER . parse ( hourFormat [ 0 ] ) ; List < Node > negative = DATETIME_PARSER . parse ( hourFormat [ 1 ] ) ; List < Node > format = WRAPPER_PARSER . parseW...
Builds a method to format the timezone as hourFormat with a GMT wrapper .
5,225
private MethodSpec buildWrapTimeZoneRegionMethod ( TimeZoneData data ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "wrapTimeZoneRegion" ) . addModifiers ( PROTECTED ) . addParameter ( StringBuilder . class , "b" ) . addParameter ( String . class , "region" ) ; List < Node > format = WRAPPER_PARSER . pa...
Build a method to wrap a region in the regionFormat .
5,226
private void appendHourFormat ( MethodSpec . Builder method , List < Node > fmt ) { for ( Node n : fmt ) { if ( n instanceof Text ) { String t = ( ( Text ) n ) . text ( ) ; boolean minute = t . equals ( ":" ) || t . equals ( "." ) ; if ( minute ) { method . beginControlFlow ( "if (emitMins)" ) ; } method . addStatement...
Appends code to emit the hourFormat for positive or negative .
5,227
public static Map < String , List < String > > deduplicateFormats ( Format format ) { Map < String , List < String > > res = new LinkedHashMap < > ( ) ; mapAdd ( res , format . short_ , "SHORT" ) ; mapAdd ( res , format . medium , "MEDIUM" ) ; mapAdd ( res , format . long_ , "LONG" ) ; mapAdd ( res , format . full , "F...
De - duplication of formats .
5,228
public static List < Path > listResources ( String ... prefixes ) throws IOException { List < Path > result = new ArrayList < > ( ) ; ClassPath classPath = ClassPath . from ( Utils . class . getClassLoader ( ) ) ; for ( ResourceInfo info : classPath . getResources ( ) ) { String path = info . getResourceName ( ) ; for ...
Recursively list all resources under the given path prefixes .
5,229
public static Node < PluralType > findChild ( Struct < PluralType > parent , PluralType type ) { for ( Node < PluralType > n : parent . nodes ( ) ) { if ( n . type ( ) == type ) { return n ; } } return null ; }
Find a child node of a given type in a parent struct or return null .
5,230
public static Maybe < Pair < Node < PluralType > , CharSequence > > parse ( String input ) { return P_RULE . parse ( input ) ; }
Parse a plural rule into an abstract syntax tree .
5,231
public static UnitConverter get ( CLDR . Locale locale ) { MeasurementSystem system = MeasurementSystem . fromLocale ( locale ) ; return SYSTEMS . getOrDefault ( system , METRIC_SYSTEM ) ; }
Retrieves the correct measurement system for a given locale .
5,232
public void reset ( ) { this . formatMode = null ; this . roundMode = NumberRoundMode . ROUND ; this . grouping = null ; this . minimumIntegerDigits = null ; this . maximumFractionDigits = null ; this . minimumFractionDigits = null ; this . maximumSignificantDigits = null ; this . minimumSignificantDigits = null ; }
Reset the options to their defaults .
5,233
public void setFormat ( String format ) { this . format = format ; Scanner scanner = new Scanner ( format ) ; this . streams [ 0 ] = scanner . stream ( ) ; this . streams [ 1 ] = scanner . stream ( ) ; for ( int i = 2 ; i < this . streams . length ; i ++ ) { this . streams [ i ] = null ; } this . tag = scanner . stream...
Sets the message format .
5,234
public void format ( MessageArgs args , StringBuilder buf ) { this . args = args ; this . buf = buf ; this . reset ( ) ; format ( streams [ 0 ] , null ) ; }
Formats the message using the given arguments and writing the output to the buffer .
5,235
private void recurse ( Stream bounds , String arg ) { streamIndex ++ ; if ( streamIndex == streams . length ) { return ; } bounds . pos ++ ; bounds . end -- ; if ( streams [ streamIndex ] == null ) { streams [ streamIndex ] = bounds . copy ( ) ; } else { streams [ streamIndex ] . setFrom ( bounds ) ; } format ( streams...
Push a stream onto the stack and format it .
5,236
private void evaluateTag ( StringBuilder buf ) { tag . pos ++ ; tag . end -- ; if ( tag . peek ( ) == Chars . MINUS_SIGN ) { tag . pos ++ ; buf . append ( '{' ) ; buf . append ( tag . token ( ) ) ; buf . append ( '}' ) ; return ; } List < MessageArg > args = getArgs ( ) ; if ( args == null || args . size ( ) == 0 ) { r...
Parse and evaluate a tag .
5,237
private void evalPlural ( MessageArg arg , boolean cardinal ) { tag . skip ( COMMA_WS ) ; if ( ! arg . resolve ( ) ) { return ; } String value = arg . asString ( ) ; String offsetValue = value ; long offset = 0 ; if ( tag . seek ( PLURAL_OFFSET , choice ) ) { tag . jump ( choice ) ; tag . skip ( COMMA_WS ) ; offset = t...
PLURAL - Evaluate the argument as a plural either cardinal or ordinal .
5,238
private void evalSelect ( MessageArg arg ) { tag . skip ( COMMA_WS ) ; int pos = - 1 ; int end = - 1 ; String value = arg . asString ( ) ; while ( tag . peek ( ) != Chars . EOF ) { if ( ! tag . seek ( NON_WS , choice ) ) { break ; } String token = choice . token ( ) . toString ( ) ; tag . jump ( choice ) ; tag . skip (...
SELECT - Evaluate the tag that matches the argument s value .
5,239
private void evalNumber ( MessageArg arg ) { initDecimalArgsParser ( ) ; parseArgs ( decimalArgsParser ) ; BigDecimal number = arg . asBigDecimal ( ) ; NumberFormatter formatter = CLDR_INSTANCE . getNumberFormatter ( locale ) ; formatter . formatDecimal ( number , buf , decimalArgsParser . options ( ) ) ; }
NUMBER - Evaluate the argument as a number with options specified as key = value .
5,240
private void evalCurrency ( MessageArg arg ) { String currencyCode = arg . currency ( ) ; if ( currencyCode == null ) { return ; } CLDR . Currency currency = CLDR . Currency . fromString ( currencyCode ) ; if ( currency == null ) { return ; } initCurrencyArgsParser ( ) ; parseArgs ( currencyArgsParser ) ; BigDecimal nu...
CURRENCY - Evaluate the argument as a currency with options specified as key = value .
5,241
private void evalDateTime ( MessageArg arg ) { if ( ! arg . resolve ( ) ) { return ; } initCalendarArgsParser ( ) ; parseArgs ( calendarArgsParser ) ; ZonedDateTime datetime = parseDateTime ( arg ) ; CalendarFormatter formatter = CLDR_INSTANCE . getCalendarFormatter ( locale ) ; formatter . format ( datetime , calendar...
DATETIME - Evaluate the argument as a datetime with options specified as key = value .
5,242
private void evalDateTimeInterval ( List < MessageArg > args ) { int size = args . size ( ) ; if ( size != 2 ) { return ; } for ( int i = 0 ; i < size ; i ++ ) { if ( ! args . get ( i ) . resolve ( ) ) { return ; } } ZonedDateTime start = parseDateTime ( args . get ( 0 ) ) ; ZonedDateTime end = parseDateTime ( args . g...
DATETIME - INTERVAL - Evaluate the argument as a date - time interval with an optional skeleton argument .
5,243
private ZonedDateTime parseDateTime ( MessageArg arg ) { long instant = arg . asLong ( ) ; ZoneId timeZone = arg . timeZone ( ) != null ? arg . timeZone ( ) : this . timeZone ; return ZonedDateTime . ofInstant ( Instant . ofEpochMilli ( instant ) , timeZone ) ; }
Parse the argument as a date - time with the format - wide time zone .
5,244
private void emit ( int pos , int end , String arg ) { while ( pos < end ) { char ch = format . charAt ( pos ) ; if ( ch == '#' ) { buf . append ( arg == null ? ch : arg ) ; } else { buf . append ( ch ) ; } pos ++ ; } }
Append characters from raw in the range [ pos end ) to the output buffer .
5,245
public V get ( K key ) { Entry < V > entry = classMap . get ( key ) ; return entry == null ? null : entry . get ( ) ; }
Gets a new instance of the class corresponding to the key .
5,246
public void put ( K key , Class < ? extends V > cls ) { classMap . put ( key , new Entry < > ( cls ) ) ; }
Puts a class into the map .
5,247
protected MetaLocale addLikelySubtags ( MetaLocale src ) { MetaLocale dst = src . copy ( ) ; if ( src . hasAll ( ) ) { return dst ; } MetaLocale temp = src . copy ( ) ; temp . setVariant ( null ) ; for ( int flags : MATCH_ORDER ) { set ( src , temp , flags ) ; MetaLocale match = likelySubtagsMap . get ( temp ) ; if ( m...
Add likely subtags producing the max bundle ID .
5,248
protected MetaLocale removeLikelySubtags ( MetaLocale src ) { MetaLocale temp = new MetaLocale ( ) ; temp . setLanguage ( src . _language ( ) ) ; MetaLocale match = addLikelySubtags ( temp ) ; if ( match . equals ( src ) ) { return temp ; } temp . setTerritory ( src . _territory ( ) ) ; match = addLikelySubtags ( temp ...
Removes all subtags that would be added by addLikelySubtags . This produces the min bundle ID .
5,249
protected static void set ( MetaLocale src , MetaLocale dst , int flags ) { dst . setLanguage ( ( flags & LANGUAGE ) == 0 ? null : src . _language ( ) ) ; dst . setScript ( ( flags & SCRIPT ) == 0 ? null : src . _script ( ) ) ; dst . setTerritory ( ( flags & TERRITORY ) == 0 ? null : src . _territory ( ) ) ; }
Set or clear fields on the destination locale according to the flags .
5,250
private String getPartition ( Set < String > variables ) { String key = buildKey ( variables ) ; return partitionIds . computeIfAbsent ( key , k -> Character . toString ( ( char ) ( BASE_ID + idSequence ++ ) ) ) ; }
Retrieve the partition identifier for this set of matching variables .
5,251
private static String buildKey ( Set < String > variables ) { return variables . stream ( ) . sorted ( ) . collect ( Collectors . joining ( ", " ) ) ; }
Sort the set of variables and join to a comma - delimited string .
5,252
private static < K , V > void makeSetsImmutable ( Map < K , Set < V > > map ) { Set < K > keys = map . keySet ( ) ; for ( K key : keys ) { Set < V > value = map . get ( key ) ; map . put ( key , Collections . unmodifiableSet ( value ) ) ; } }
Convert values to immutable sets .
5,253
public UnitValue convert ( UnitValue value ) { Unit src = value . unit ( ) ; switch ( src . category ( ) ) { case CONCENTR : case LIGHT : break ; case ACCELERATION : return convert ( value , Unit . METER_PER_SECOND_SQUARED , UnitFactors . ACCELERATION ) ; case ANGLE : return convert ( value , UnitFactorSets . ANGLE ) ;...
Convert the given unit value into the best unit for its category relative to the current measurement system .
5,254
public UnitValue convert ( UnitValue value , Unit target ) { Unit src = value . unit ( ) ; UnitCategory category = src . category ( ) ; if ( src == target || category != target . category ( ) ) { return value ; } switch ( category ) { case CONCENTR : case LIGHT : break ; case CONSUMPTION : return consumption ( value , ...
Convert the given unit value into the target unit relative to the current measurement system .
5,255
public UnitValue convert ( UnitValue value , UnitFactorSet factorSet ) { value = convert ( value , factorSet . base ( ) ) ; BigDecimal n = value . amount ( ) ; boolean negative = false ; if ( n . signum ( ) == - 1 ) { negative = true ; n = n . abs ( ) ; } List < UnitValue > factors = factorSet . factors ( ) ; int size ...
Convert to the best display unit among the available factors . By best we mean the most compact representation .
5,256
public List < UnitValue > sequence ( UnitValue value , UnitFactorSet factorSet ) { value = convert ( value , factorSet . base ( ) ) ; boolean negative = false ; BigDecimal n = value . amount ( ) ; if ( n . signum ( ) == - 1 ) { negative = true ; n = n . abs ( ) ; } List < UnitValue > result = new ArrayList < > ( ) ; Li...
Breaks down the unit value into a sequence of units using the given divisors and allowed units .
5,257
private static UnitValue temperature ( UnitValue value , Unit target ) { BigDecimal n = value . amount ( ) ; if ( target == Unit . TEMPERATURE_GENERIC ) { return new UnitValue ( n , Unit . TEMPERATURE_GENERIC ) ; } switch ( value . unit ( ) ) { case FAHRENHEIT : if ( target == Unit . CELSIUS ) { n = n . subtract ( THIR...
Temperature conversions .
5,258
public MessageArg get ( int index ) { return index < args . size ( ) ? args . get ( index ) : null ; }
Return a positional argument using a zero - based index or null if not enough arguments exist .
5,259
public MessageArg get ( String name ) { return map == null ? null : map . get ( name ) ; }
Return a named argument or null if does not exist .
5,260
public void add ( String name , MessageArg arg ) { args . add ( arg ) ; if ( map == null ) { map = new HashMap < > ( ) ; } map . put ( name , arg ) ; }
Add a named argument . Also accessible by index .
5,261
public Map < LocaleID , ClassName > generate ( Path outputDir , DataReader reader ) throws IOException { Map < LocaleID , ClassName > numberClasses = new TreeMap < > ( ) ; Map < LocaleID , UnitData > unitMap = reader . units ( ) ; for ( Map . Entry < LocaleID , NumberData > entry : reader . numbers ( ) . entrySet ( ) )...
Generate all number formatting classes .
5,262
private TypeSpec create ( NumberData data , UnitData unitData , String className ) { LocaleID id = data . id ( ) ; TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . superclass ( NUMBER_FORMATTER_BASE ) . addModifiers ( Modifier . PUBLIC ) ; String fmt = "super(\n" ; List < Object > args = new ArrayList ...
Creates a number formatter class .
5,263
public TypeSpec createCurrencyUtil ( String className , Map < String , CurrencyData > currencies ) { TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . addModifiers ( Modifier . PUBLIC ) ; CurrencyData defaultData = currencies . get ( "DEFAULT" ) ; currencies . remove ( "DEFAULT" ) ; MethodSpec . Builder...
Create class to hold global currency information .
5,264
private List < String > getPatterns ( List < NumberPattern > patterns ) { return patterns . stream ( ) . map ( p -> p . render ( ) ) . collect ( Collectors . toList ( ) ) ; }
Return a list of the string patterns embedded in the NumberPattern instances .
5,265
private void addParams ( TypeSpec . Builder parent , LocaleID id , NumberData data ) { MethodSpec . Builder code = MethodSpec . constructorBuilder ( ) ; code . addStatement ( "this.decimal = $S" , data . decimal ) ; code . addStatement ( "this.group = $S" , data . group ) ; code . addStatement ( "this.percent = $S" , d...
Construct s the locale s number formatter params .
5,266
private void addCurrencyInfo ( TypeSpec . Builder type , NumberData data ) { addCurrencyInfoMethod ( type , "getCurrencySymbol" , data . currencySymbols ) ; addCurrencyInfoMethod ( type , "getNarrowCurrencySymbol" , data . narrowCurrencySymbols ) ; addCurrencyInfoMethod ( type , "getCurrencyDisplayName" , data . curren...
Adds methods to return information about a currency .
5,267
private void addCurrencyInfoMethod ( TypeSpec . Builder type , String name , Map < String , String > mapping ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( name ) . addModifiers ( PUBLIC ) . addParameter ( Types . CLDR_CURRENCY_ENUM , "code" ) . returns ( String . class ) ; method . beginControlFlow ( "...
Adds a method to return the symbol or display name for a currency .
5,268
private static void buildMatchVariables ( TypeSpec . Builder type , Map < String , Set < String > > territoryData , LanguageMatchingData data ) { Map < String , Set < String > > territories = flatten ( territoryData ) ; CodeBlock . Builder code = CodeBlock . builder ( ) ; code . add ( "new $T<$T, $T<$T>>() {{\n" , HASH...
Build table containing language matching variables .
5,269
private static Map < String , Set < String > > flatten ( Map < String , Set < String > > data ) { Map < String , Set < String > > territories = new TreeMap < > ( ) ; Set < String > keys = data . keySet ( ) ; for ( String key : keys ) { Set < String > values = flatten ( key , territories , data ) ; territories . put ( k...
Flatten the territory containment hierarchy .
5,270
private static Set < String > flatten ( String parent , Map < String , Set < String > > flat , Map < String , Set < String > > data ) { Set < String > countries = new LinkedHashSet < > ( ) ; Set < String > keys = data . get ( parent ) ; if ( keys == null ) { return countries ; } for ( String region : keys ) { if ( data...
Flatten one level of the territory containment hierarchy .
5,271
private static void addStringList ( CodeBlock . Builder code , List < String > list , String indent ) { int size = list . size ( ) ; code . add ( "$T.asList(\n$L" , Arrays . class , indent ) ; int width = indent . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i != 0 ) { code . add ( ", " ) ; width += 2 ; } if...
Helper to add a list of strings to a code block .
5,272
public NumberPattern parse ( String raw ) { this . buf . setLength ( 0 ) ; this . nodes = new ArrayList < > ( ) ; this . attached = false ; this . format = new Format ( ) ; int length = raw . length ( ) ; int i = 0 ; boolean inGroup = false ; boolean inDecimal = false ; while ( i < length ) { char ch = raw . charAt ( i...
Parse a number formatting pattern .
5,273
private void pushText ( ) { if ( buf . length ( ) > 0 ) { nodes . add ( new NumberPattern . Text ( buf . toString ( ) ) ) ; buf . setLength ( 0 ) ; } }
If the buffer is not empty push it onto the node list and reset it .
5,274
public CLDR . Locale fromJavaLocale ( java . util . Locale javaLocale ) { return MetaLocale . fromJavaLocale ( javaLocale ) ; }
Convert the Java locale to a CLDR locale object .
5,275
public CLDR . Locale minimize ( CLDR . Locale locale ) { return languageResolver . removeLikelySubtags ( ( MetaLocale ) locale ) ; }
Produce the minimal representation of this locale by removing likely subtags .
5,276
public CalendarFormatter getCalendarFormatter ( CLDR . Locale locale ) { locale = bundleMatch ( locale ) ; CalendarFormatter formatter = CALENDAR_FORMATTERS . get ( locale ) ; return formatter == null ? CALENDAR_FORMATTERS . get ( CLDR . Locale . en_US ) : formatter ; }
Returns a calendar formatter for the given locale translating it before lookup .
5,277
public NumberFormatter getNumberFormatter ( CLDR . Locale locale ) { locale = bundleMatch ( locale ) ; NumberFormatter formatter = NUMBER_FORMATTERS . get ( locale ) ; return formatter == null ? NUMBER_FORMATTERS . get ( CLDR . Locale . en_US ) : formatter ; }
Returns a number formatter for the given locale translating it before lookup .
5,278
protected static void addLanguageAlias ( String rawType , String rawReplacement ) { LanguageAlias type = LanguageAlias . parse ( rawType ) ; LanguageAlias replacement = LanguageAlias . parse ( rawReplacement ) ; String language = type . language ( ) ; List < Pair < LanguageAlias , LanguageAlias > > aliases = LANGUAGE_A...
Add a language alias entry .
5,279
protected CLDR . Locale bundleMatch ( CLDR . Locale locale ) { locale = DEFAULT_CONTENT . getOrDefault ( locale , locale ) ; return bundleMatcher . match ( ( MetaLocale ) locale ) ; }
Locate the correct bundle identifier for the given resolved locale . Note that the bundle identifier is not terribly useful outside of the CLDR library since it may in many cases carry incomplete information for the intended public locale . For example the bundle used for en - Latn - US is en which is missing critical ...
5,280
public DigitBuffer append ( String s ) { int len = s . length ( ) ; check ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { this . buf [ size ] = s . charAt ( i ) ; size ++ ; } return this ; }
Append a string to the buffer expanding it if necessary .
5,281
public void append ( DigitBuffer other ) { check ( other . size ) ; System . arraycopy ( other . buf , 0 , buf , size , other . size ) ; size += other . size ; }
Append the contents of the other buffer to this one .
5,282
public void reverse ( int start ) { int end = size - 1 ; int num = end - start >> 1 ; for ( int i = 0 ; i <= num ; i ++ ) { int j = start + i ; int k = end - i ; char c = buf [ k ] ; buf [ k ] = buf [ j ] ; buf [ j ] = c ; } }
Reverse all characters from start to end of buffer .
5,283
private void check ( int length ) { if ( size + length >= buf . length ) { buf = Arrays . copyOf ( buf , buf . length + length + 16 ) ; } }
Ensure the buffer is large enough for the next append .
5,284
public static DataReader get ( ) throws IOException { if ( ! instance . initialized ) { long start = System . currentTimeMillis ( ) ; instance . init ( ) ; long elapsed = System . currentTimeMillis ( ) - start ; System . out . printf ( "Loaded CLDR data in %d ms.\n" , elapsed ) ; } return instance ; }
Returns the global DataReader instance populating it if necessary .
5,285
private void loadPatches ( ) throws IOException { List < Path > paths = Utils . listResources ( PATCHES ) ; for ( Path path : paths ) { String fileName = path . getFileName ( ) . toString ( ) ; if ( fileName . endsWith ( ".json" ) ) { JsonObject root = load ( path ) ; patches . put ( fileName , root ) ; } } }
Load patches which override values in the CLDR data . Use this to restore certain cases to our preferred form .
5,286
private JsonObject patch ( String fileName , String code , JsonObject root ) { for ( Map . Entry < String , JsonObject > entry : patches . entrySet ( ) ) { JsonObject patch = entry . getValue ( ) ; if ( ! patch . get ( "filename" ) . getAsString ( ) . equals ( fileName ) ) { continue ; } JsonArray locales = patch . get...
Apply a patch to the given filename if applicable .
5,287
private void patchObject ( JsonObject src , JsonObject dst ) { for ( String key : objectKeys ( src ) ) { JsonElement se = src . get ( key ) ; JsonElement de = dst . get ( key ) ; if ( de == null ) { continue ; } if ( se . isJsonObject ( ) && de . isJsonObject ( ) ) { patchObject ( se . getAsJsonObject ( ) , de . getAsJ...
Overlay nested values from src on top of dst .
5,288
private void sanityCheck ( List < Path > resources ) { Set < String > fileNames = resources . stream ( ) . map ( p -> p . getFileName ( ) . toString ( ) ) . collect ( Collectors . toSet ( ) ) ; for ( String name : FILENAMES_MUST_EXIST ) { if ( ! fileNames . contains ( name ) ) { String msg = String . format ( "CLDR DAT...
Blow up if required paths do not exist .
5,289
private JsonObject load ( Path path ) throws IOException { try ( InputStream stream = Resources . getResource ( path . toString ( ) ) . openStream ( ) ) { return ( JsonObject ) JSON_PARSER . parse ( new InputStreamReader ( stream ) ) ; } }
Loads and parses a JSON file returning a reference to its root object node .
5,290
private LocaleID parseIdentity ( String code , JsonObject root ) throws IOException { JsonObject node = resolve ( root , "main" , code , "identity" ) ; return new LocaleID ( string ( node , "language" ) , string ( node , "script" ) , string ( node , "territory" ) , string ( node , "variant" ) ) ; }
Parse the locale identity header from a calendar JSON tree .
5,291
private void parseLikelySubtags ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "likelySubtags" ) ; for ( Map . Entry < String , JsonElement > entry : node . entrySet ( ) ) { likelySubtags . put ( entry . getKey ( ) , entry . getValue ( ) . getAsString ( ) ) ; } }
Parse likely subtags tree .
5,292
private void parseLanguageMatchingFix ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "languageMatching" , "written_new" ) ; JsonArray matches = node . getAsJsonArray ( "languageMatch" ) ; for ( JsonElement element : matches ) { JsonObject value = ( JsonObject ) element ; String desired = stri...
Parse enhanced language matching fix tree .
5,293
private void parseTerritoryContainment ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "territoryContainment" ) ; for ( Map . Entry < String , JsonElement > entry : node . entrySet ( ) ) { String parentCode = entry . getKey ( ) ; if ( parentCode . contains ( "-" ) ) { if ( ! parentCode . endsW...
Parse territory containment tree .
5,294
private DateTimeData parseCalendar ( JsonObject root ) throws IOException { DateTimeData data = new DateTimeData ( ) ; JsonObject node = resolve ( root , "dates" , "calendars" , "gregorian" ) ; data . eras = parseEras ( node ) ; data . dayPeriodsFormat = parseDayPeriods ( node , "format" ) ; data . dayPeriodsStandalone...
Parse calendar date - time attributes .
5,295
private Format parseDateFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard date formats of varying sizes .
5,296
private Format parseTimeFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "timeFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard time formats of varying sizes .
5,297
private Format parseDateTimeFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateTimeFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard date - time wrapper formats of varying sizes .
5,298
private List < Skeleton > parseDateTimeSkeletons ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateTimeFormats" , "availableFormats" ) ; List < Skeleton > value = new ArrayList < > ( ) ; for ( String key : objectKeys ( node ) ) { value . add ( new Skeleton ( key , string ( node , key ) ) ) ; } retur...
Parse date - time skeletons .
5,299
private Map < String , Integer > parseMinDays ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "weekData" , "minDays" ) ; Map < String , Integer > m = new HashMap < > ( ) ; for ( String key : objectKeys ( node ) ) { m . put ( key , Integer . valueOf ( string ( node , key ) ) ) ; } return m ; }
Parse the min days values . This indicates the minimum number of days a week must include for it to be counted as the first week of the year ; otherwise it s the last week of the previous year .