idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,100
public String getGroupedValue ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( getRegisternummer ( ) ) . append ( Constants . DOT ) ; sb . append ( getAccountType ( ) ) . append ( Constants . DOT ) ; sb . append ( getPartAfterAccountType ( ) ) ; return sb . toString ( ) ; }
Returns the Kontonummer as a String formatted with . s separating the Registernummer AccountType and end part .
5,101
public static List < Fodselsnummer > getFodselsnummerForDateAndGender ( Date date , KJONN kjonn ) { List < Fodselsnummer > result = getManyFodselsnummerForDate ( date ) ; splitByGender ( kjonn , result ) ; return result ; }
Returns a List with valid Fodselsnummer instances for a given Date and gender .
5,102
public static Fodselsnummer getFodselsnummerForDate ( Date date ) { List < Fodselsnummer > fodselsnummerList = getManyFodselsnummerForDate ( date ) ; Collections . shuffle ( fodselsnummerList ) ; return fodselsnummerList . get ( 0 ) ; }
Return one random valid fodselsnummer on a given date
5,103
public static List < Fodselsnummer > getManyDNumberFodselsnummerForDate ( Date date ) { if ( date == null ) { throw new IllegalArgumentException ( ) ; } DateFormat df = new SimpleDateFormat ( "ddMMyy" ) ; String centuryString = getCentury ( date ) ; String dateString = df . format ( date ) ; dateString = new StringBuil...
Returns a List with with VALID DNumber Fodselsnummer instances for a given Date .
5,104
public static List < Fodselsnummer > getManyFodselsnummerForDate ( Date date ) { if ( date == null ) { throw new IllegalArgumentException ( ) ; } DateFormat df = new SimpleDateFormat ( "ddMMyy" ) ; String centuryString = getCentury ( date ) ; String dateString = df . format ( date ) ; return generateFodselsnummerForDat...
Returns a List with with VALID Fodselsnummer instances for a given Date .
5,105
public static GeoParser getDefault ( String pathToLuceneIndex , int maxHitDepth , int maxContentWindow ) throws ClavinException { return getDefault ( pathToLuceneIndex , maxHitDepth , maxContentWindow , false ) ; }
Get a GeoParser with defined values for maxHitDepth and maxContentWindow .
5,106
public static GeoParser getDefault ( String pathToLuceneIndex , int maxHitDepth , int maxContentWindow , boolean fuzzy ) throws ClavinException { try { LocationExtractor extractor = new ApacheExtractor ( ) ; return getDefault ( pathToLuceneIndex , extractor , maxHitDepth , maxContentWindow , fuzzy ) ; } catch ( IOExcep...
Get a GeoParser with defined values for maxHitDepth and maxContentWindow and fuzzy matching explicitly turned on or off .
5,107
public static GeoParser getDefault ( String pathToLuceneIndex , LocationExtractor extractor , int maxHitDepth , int maxContentWindow , boolean fuzzy ) throws ClavinException { Gazetteer gazetteer = new LuceneGazetteer ( new File ( pathToLuceneIndex ) ) ; return new GeoParser ( extractor , gazetteer , maxHitDepth , maxC...
Get a GeoParser with defined values for maxHitDepth and maxContentWindow fuzzy matching explicitly turned on or off and a specific LocationExtractor to use .
5,108
public static Kidnummer mod10Kid ( String baseNumber , int targetLength ) { if ( baseNumber . length ( ) >= targetLength ) throw new IllegalArgumentException ( "baseNumber too long" ) ; String padded = String . format ( "%0" + ( targetLength - 1 ) + "d" , new BigInteger ( baseNumber ) ) ; Kidnummer k = new Kidnummer ( ...
Create a valid KID numer of the wanted length using MOD10 . Input is padded with leading zeros to reach wanted target length
5,109
public static Kidnummer mod11Kid ( String baseNumber , int targetLength ) { if ( baseNumber . length ( ) >= targetLength ) throw new IllegalArgumentException ( "baseNumber too long" ) ; String padded = String . format ( "%0" + ( targetLength - 1 ) + "d" , new BigInteger ( baseNumber ) ) ; Kidnummer k = new Kidnummer ( ...
Create a valid KID numer of the wanted length using MOD11 . Input is padded with leading zeros to reach wanted target length
5,110
private String sanitizeQueryText ( final GazetteerQuery query ) { String sanitized = "" ; if ( query != null && query . getOccurrence ( ) != null ) { String text = query . getOccurrence ( ) . getText ( ) ; if ( text != null ) { sanitized = escape ( text . trim ( ) . toLowerCase ( ) ) ; } } return sanitized ; }
Sanitizes the text of the LocationOccurrence in the query parameters for use in a Lucene query returning an empty string if no text is found .
5,111
private Filter buildFilter ( final GazetteerQuery params ) { List < Query > queryParts = new ArrayList < Query > ( ) ; if ( ! params . isIncludeHistorical ( ) ) { int val = IndexField . getBooleanIndexValue ( false ) ; queryParts . add ( NumericRangeQuery . newIntRange ( HISTORICAL . key ( ) , val , val , true , true )...
Builds a Lucene search filter based on the provided parameters .
5,112
private void resolveParents ( final Map < Integer , Set < GeoName > > childMap ) throws IOException { Map < Integer , GeoName > parentMap = new HashMap < Integer , GeoName > ( ) ; Map < Integer , Set < GeoName > > grandParentMap = new HashMap < Integer , Set < GeoName > > ( ) ; for ( Integer parentId : childMap . keySe...
Retrieves and sets the parents of the provided children .
5,113
protected TokenStreamComponents createComponents ( final String fieldName , final Reader reader ) { return new TokenStreamComponents ( new WhitespaceLowerCaseTokenizer ( matchVersion , reader ) ) ; }
Provides tokenizer access for the analyzer .
5,114
public static void main ( String [ ] args ) throws IOException { Options options = getOptions ( ) ; CommandLine cmd = null ; CommandLineParser parser = new GnuParser ( ) ; try { cmd = parser . parse ( options , args ) ; } catch ( ParseException pe ) { LOG . error ( pe . getMessage ( ) ) ; printHelp ( options ) ; System...
Turns a GeoNames gazetteer file into a Lucene index and adds some supplementary gazetteer records at the end .
5,115
public static boolean isValid ( String kontonummer ) { try { KontonummerValidator . getKontonummer ( kontonummer ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } }
Return true if the provided String is a valid Kontonummmer .
5,116
public static Kontonummer getKontonummer ( String kontonummer ) throws IllegalArgumentException { validateSyntax ( kontonummer ) ; validateChecksum ( kontonummer ) ; return new Kontonummer ( kontonummer ) ; }
Returns an object that represents a Kontonummer .
5,117
public static Kontonummer getAndForceValidKontonummer ( String kontonummer ) { validateSyntax ( kontonummer ) ; try { validateChecksum ( kontonummer ) ; } catch ( IllegalArgumentException iae ) { Kontonummer k = new Kontonummer ( kontonummer ) ; int checksum = calculateMod11CheckSum ( getMod11Weights ( k ) , k ) ; kont...
Returns an object that represents a Kontonummer . The checksum of the supplied kontonummer is changed to a valid checksum if the original kontonummer has an invalid checksum .
5,118
private List < ResolvedLocation > pickBestCandidates ( final List < List < ResolvedLocation > > allCandidates ) { List < ResolvedLocation > bestCandidates = new ArrayList < ResolvedLocation > ( ) ; Set < CountryCode > countries ; Set < String > states ; float score ; float newMaxScore = 0 ; float oldMaxScore ; int cand...
Uses heuristics to select the best match for each location name extracted from a document choosing from among a list of lists of candidate matches .
5,119
public GazetteerQuery build ( ) { return new GazetteerQuery ( location , maxResults , fuzzyMode , ancestryMode , includeHistorical , filterDupes , parentIds , featureCodes ) ; }
Constructs a query from the current configuration of this Builder .
5,120
public static boolean isEditDistance1 ( String str1 , String str2 ) { if ( ( str1 == null ) || str1 . isEmpty ( ) ) { if ( ( str2 == null ) || str2 . isEmpty ( ) ) { return true ; } else { return ( str2 . length ( ) <= 1 ) ; } } else if ( ( str2 == null ) || str2 . isEmpty ( ) ) { return ( str1 . length ( ) <= 1 ) ; } ...
Fast method for determining whether the Damerau - Levenshtein edit distance between two strings is less than 2 .
5,121
protected String remainder ( int index ) { if ( index > this . array . length ) return "" ; else return new String ( Arrays . copyOfRange ( this . array , index , this . array . length ) ) ; }
Get the contents of the char array to the right of the given index and return it as a String .
5,122
public static < T > Iterable < PSArray < T > > create ( Iterable < T > items , final Comparator < T > comparator ) { MutableArray < T > initial = MutableArrayFromIterable . create ( items ) ; GoodSortingAlgorithm . getInstance ( ) . sort ( initial , comparator ) ; return IterableUsingStatusUpdater . create ( initial , ...
SRM464 - 1 - 250 is a good problem to solve using this .
5,123
public static < V , E extends DirectedEdge < V > > void traverse ( Graph < V , E > graph , DFSVisitor < V , E > visitor ) { MultiSourceDFS . traverse ( graph , graph . getVertices ( ) , visitor ) ; }
Remember that visiting order is not ordered .
5,124
private static < T > IntPair findBridgeIndexes ( PSArray < Point2D < T > > earlyHull , PSArray < Point2D < T > > laterHull , int earlyStart , int laterStart , MultipliableNumberSystem < T > ns ) { int early = earlyStart ; int later = laterStart ; while ( true ) { int nextEarly = getPreIndex ( early , earlyHull . size (...
early later are ordered by ccw order .
5,125
public static TrieNodeFactory < Boolean > getInstance ( ) { return new TrieNodeFactory < Boolean > ( ) { public TrieNode < Boolean > create ( ) { return new BooleanTrieNode ( ) ; } } ; }
specialized in speed for boolean keyed nodes .
5,126
public static void renderTemplateAsExcel ( String templateName , Object ... args ) { Scope . RenderArgs templateBinding = Scope . RenderArgs . current ( ) ; for ( Object o : args ) { List < String > names = LocalvariablesNamesEnhancer . LocalVariablesNamesTracer . getAllLocalVariableNames ( o ) ; for ( String name : na...
Render a specific template
5,127
public static void renderExcel ( Object ... args ) { String templateName = null ; final Http . Request request = Http . Request . current ( ) ; if ( args . length > 0 && args [ 0 ] instanceof String && LocalvariablesNamesEnhancer . LocalVariablesNamesTracer . getAllLocalVariableNames ( args [ 0 ] ) . isEmpty ( ) ) { te...
Render the corresponding template
5,128
public static BigDecimal setup ( BigDecimal n , NumberRoundMode roundMode , NumberFormatMode formatMode , int minIntDigits , int maxFracDigits , int minFracDigits , int maxSigDigits , int minSigDigits ) { RoundingMode mode = roundMode . toRoundingMode ( ) ; boolean useSignificant = formatMode == SIGNIFICANT || formatMo...
Calculates the number of integer and fractional digits to emit returning them in a 2 - element array and updates the operands .
5,129
public static void format ( BigDecimal n , DigitBuffer buf , NumberFormatterParams params , boolean currencyMode , boolean grouping , int minIntDigits , int primaryGroupingSize , int secondaryGroupingSize ) { if ( secondaryGroupingSize <= 0 ) { secondaryGroupingSize = primaryGroupingSize ; } int groupSize = primaryGrou...
Formats the number into the digit buffer .
5,130
public int distance ( CLDR . Locale desired , CLDR . Locale supported ) { return distance ( desired , supported , DEFAULT_THRESHOLD ) ; }
Returns the distance between the desired and supported locale using the default distance threshold .
5,131
public int distance ( CLDR . Locale desired , CLDR . Locale supported , int threshold ) { boolean langEquals = desired . language ( ) . equals ( supported . language ( ) ) ; Node node = distanceMap . get ( desired . language ( ) , supported . language ( ) ) ; if ( node == null ) { node = distanceMap . get ( ANY , ANY )...
Returns the distance between the desired and supported locale using the given distance threshold . Any distance equal to or greater than the threshold will return the maximum distance .
5,132
private Node scanTerritory ( DistanceMap map , String desired , String supported ) { Node node ; for ( String partition : PARTITION_TABLE . getRegionPartition ( desired ) ) { node = map . get ( partition , supported ) ; if ( node != null ) { return node ; } } for ( String partition : PARTITION_TABLE . getRegionPartitio...
Scan the desired region against the supported partitions and vice versa . Return the first matching node .
5,133
public String applies ( ZonedDateTime d ) { long epoch = d . toEpochSecond ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Entry entry = entries [ i ] ; if ( entry . from == - 1 ) { if ( entry . to == - 1 || epoch < entry . to ) { return entry . metazoneId ; } } else if ( entry . to == - 1 ) { if ( entry . from <= epoch ) ...
Find the metazone that applies for a given timestamp .
5,134
public Match match ( List < String > desired , int threshold ) { return matchImpl ( parse ( desired ) , threshold ) ; }
Return the best match that exceeds the threshold . If the default is returned its distance is set to MAX_DISTANCE .
5,135
public List < Match > matches ( List < String > desired ) { return matchesImpl ( parse ( desired ) , DEFAULT_THRESHOLD ) ; }
Return all matches and their distances if they exceed the default threshold . If no match exceeds the threshold this returns an empty list .
5,136
private Match matchImpl ( List < Entry > desiredLocales , int threshold ) { int bestDistance = MAX_DISTANCE ; Entry bestMatch = null ; for ( Entry desired : desiredLocales ) { List < String > exact = exactMatch . get ( desired . locale ) ; if ( exact != null ) { return new Match ( exact . get ( 0 ) , 0 ) ; } for ( Entr...
Return the best match that exceeds the threshold or the default . If the default is returned its distance is set to MAX_DISTANCE . An exact match has distance of 0 .
5,137
public void generate ( Path outputDir , DataReader reader ) throws IOException { String className = "_PluralRules" ; TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . addModifiers ( PUBLIC ) . superclass ( TYPE_BASE ) ; Map < String , FieldSpec > fieldMap = buildConditionFields ( reader . cardinals ( ) ...
Generate a class for plural rule evaluation .
5,138
private MethodSpec buildRuleMethod ( String methodName , PluralData data , Map < String , FieldSpec > fieldMap ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( methodName ) . addModifiers ( PRIVATE , STATIC ) . addParameter ( NUMBER_OPERANDS , "o" ) . returns ( PLURAL_CATEGORY ) ; for ( Map . Entry < Stri...
Builds a method that when called evaluates the rule and returns a PluralCategory .
5,139
private final Map < String , FieldSpec > buildConditionFields ( Map < String , PluralData > ... pluralMaps ) { Map < String , FieldSpec > index = new LinkedHashMap < > ( ) ; int seq = 0 ; for ( Map < String , PluralData > pluralMap : pluralMaps ) { for ( Map . Entry < String , PluralData > entry : pluralMap . entrySet ...
Maps an integer to each AND condition s canonical representation .
5,140
public FieldSpec buildConditionField ( int index , Struct < PluralType > branch ) { String fieldDoc = PluralRulePrinter . print ( branch ) ; String name = String . format ( "COND_%d" , index ) ; FieldSpec . Builder field = FieldSpec . builder ( PLURAL_CONDITION , name , PRIVATE , STATIC , FINAL ) . addJavadoc ( fieldDo...
Constructs a lambda Condition field that represents a chain of AND conditions that together is a single branch in an OR condition .
5,141
private static void renderExpr ( boolean first , CodeBlock . Builder code , Node < PluralType > expr ) { Iterator < Node < PluralType > > iter = expr . asStruct ( ) . nodes ( ) . iterator ( ) ; Atom < PluralType > operand = iter . next ( ) . asAtom ( ) ; Atom < PluralType > modop = null ; Atom < PluralType > relop = it...
Render the header of a branch method .
5,142
private static void renderExpr ( CodeBlock . Builder code , List < Node < PluralType > > rangeList , boolean equal , boolean decimalsZero ) { int size = rangeList . size ( ) ; String r = "" ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { r += " || " ; } r += renderRange ( "zz" , rangeList . get ( i ) ) ; } Strin...
Render the expression body of a branch method .
5,143
private static String renderRange ( String name , Node < PluralType > node ) { if ( node . type ( ) == PluralType . RANGE ) { Struct < PluralType > range = node . asStruct ( ) ; int start = ( Integer ) range . nodes ( ) . get ( 0 ) . asAtom ( ) . value ( ) ; int end = ( Integer ) range . nodes ( ) . get ( 1 ) . asAtom ...
Render a the range segment of an expression .
5,144
public static String print ( Node < PluralType > node ) { StringBuilder buf = new StringBuilder ( ) ; print ( buf , node ) ; return buf . toString ( ) ; }
Return a recursive representation of the given pluralization node or tree .
5,145
private static void print ( StringBuilder buf , Node < PluralType > node ) { switch ( node . type ( ) ) { case RULE : join ( buf , node , " " ) ; break ; case AND_CONDITION : join ( buf , node , " and " ) ; break ; case OR_CONDITION : join ( buf , node , " or " ) ; break ; case RANGELIST : join ( buf , node , "," ) ; b...
Recursively visit the structs and atoms in the pluralization node or tree appending the representations to a string buffer .
5,146
private static void join ( StringBuilder buf , Node < PluralType > parent , String delimiter ) { List < Node < PluralType > > nodes = parent . asStruct ( ) . nodes ( ) ; int size = nodes . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { buf . append ( delimiter ) ; } print ( buf , nodes . get ( i ) ) ; ...
Print each child node of a struct joining them together with a delimiter string .
5,147
public void format ( ZonedDateTime datetime , CalendarFormatOptions options , StringBuilder buffer ) { String dateSkeleton = options . dateSkeleton ( ) == null ? null : options . dateSkeleton ( ) . skeleton ( ) ; String timeSkeleton = options . timeSkeleton ( ) == null ? null : options . timeSkeleton ( ) . skeleton ( )...
Main entry point for date time formatting .
5,148
public void format ( ZonedDateTime start , ZonedDateTime end , DateTimeIntervalSkeleton skeleton , StringBuilder buffer ) { DateTimeField field = CalendarFormattingUtils . greatestDifference ( start , end ) ; if ( skeleton == null ) { switch ( field ) { case YEAR : case MONTH : case DAY : skeleton = DateTimeIntervalSke...
Format a date time interval guessing at the best skeleton to use based on the field of greatest difference between the start and end date - time . If the end date - time has a different time zone than the start this is corrected for comparison . If the skeleton is null one is selected automatically using the field of g...
5,149
public String resolveTimeZoneId ( String zoneId ) { String alias = _CalendarUtils . getTimeZoneAlias ( zoneId ) ; if ( alias != null ) { zoneId = alias ; } alias = TimeZoneAliases . getAlias ( zoneId ) ; if ( alias != null ) { zoneId = alias ; } return zoneId ; }
Check if the zoneId has an alias in the CLDR data .
5,150
public void formatField ( ZonedDateTime datetime , String pattern , StringBuilder buffer ) { int length = pattern . length ( ) ; if ( length == 0 ) { return ; } int i = 0 ; if ( pattern . charAt ( i ) == '+' ) { if ( length == 1 ) { return ; } i ++ ; } int width = 0 ; char field = pattern . charAt ( i ) ; while ( i < l...
Formats a single field based on the first character in the pattern string with repeated characters indicating the field width .
5,151
public void formatField ( ZonedDateTime datetime , char field , int width , StringBuilder buffer ) { switch ( field ) { case 'G' : formatEra ( buffer , datetime , width , eras ) ; break ; case 'y' : formatYear ( buffer , datetime , width ) ; break ; case 'Y' : formatISOYearWeekOfYear ( buffer , datetime , width ) ; bre...
Format a single field of a given width .
5,152
void formatEra ( StringBuilder b , ZonedDateTime d , int width , FieldVariants eras ) { int year = d . getYear ( ) ; int index = year < 0 ? 0 : 1 ; switch ( width ) { case 5 : b . append ( eras . narrow [ index ] ) ; break ; case 4 : b . append ( eras . wide [ index ] ) ; break ; case 3 : case 2 : case 1 : b . append (...
Format the era based on the year .
5,153
void formatYear ( StringBuilder b , ZonedDateTime d , int width ) { int year = d . getYear ( ) ; _formatYearValue ( b , year , width ) ; }
Format the numeric year zero padding as necessary .
5,154
void formatISOYearWeekOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int year = d . get ( IsoFields . WEEK_BASED_YEAR ) ; _formatYearValue ( b , year , width ) ; }
Formats the year according to ISO week - year .
5,155
void formatQuarter ( StringBuilder b , ZonedDateTime d , int width , FieldVariants quarters ) { int quarter = ( d . getMonth ( ) . getValue ( ) - 1 ) / 3 ; switch ( width ) { case 5 : b . append ( quarters . narrow [ quarter ] ) ; break ; case 4 : b . append ( quarters . wide [ quarter ] ) ; break ; case 3 : b . append...
Format the quarter based on the month .
5,156
void formatMonth ( StringBuilder b , ZonedDateTime d , int width , FieldVariants months ) { int month = d . getMonth ( ) . getValue ( ) ; switch ( width ) { case 5 : b . append ( months . narrow [ month - 1 ] ) ; break ; case 4 : b . append ( months . wide [ month - 1 ] ) ; break ; case 3 : b . append ( months . abbrev...
Format the month numeric or a string name variant .
5,157
void formatWeekOfMonth ( StringBuilder b , ZonedDateTime d , int width ) { int w = d . get ( ChronoField . ALIGNED_WEEK_OF_MONTH ) ; if ( width == 1 ) { b . append ( w ) ; } }
Format the week number of the month .
5,158
void formatISOWeekOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int w = d . get ( IsoFields . WEEK_OF_WEEK_BASED_YEAR ) ; switch ( width ) { case 2 : zeroPad2 ( b , w , 2 ) ; break ; case 1 : b . append ( w ) ; break ; } }
Format the week number of the year .
5,159
void formatWeekday ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays ) { int weekday = d . getDayOfWeek ( ) . getValue ( ) % 7 ; switch ( width ) { case 6 : b . append ( weekdays . short_ [ weekday ] ) ; break ; case 5 : b . append ( weekdays . narrow [ weekday ] ) ; break ; case 4 : b . append (...
Format the weekday name .
5,160
void formatLocalWeekday ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays , int firstDay ) { if ( width > 2 ) { formatWeekday ( b , d , width , weekdays ) ; return ; } if ( width == 2 ) { b . append ( '0' ) ; } formatWeekdayNumeric ( b , d , firstDay ) ; }
Format the numeric weekday or the format name variant .
5,161
void formatLocalWeekdayStandalone ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays , int firstDay ) { if ( width > 2 ) { formatWeekday ( b , d , width , weekdays ) ; return ; } formatWeekdayNumeric ( b , d , firstDay ) ; }
Format the numeric weekday or the stand - alone name variant .
5,162
private void formatWeekdayNumeric ( StringBuilder b , ZonedDateTime d , int firstDay ) { int weekday = d . getDayOfWeek ( ) . getValue ( ) ; int w = ( 7 - firstDay + weekday ) % 7 + 1 ; b . append ( w ) ; }
Convert from Java s ISO - 8601 week number where Monday = 1 and Sunday = 7 . We need to adjust this according to the locale s first day of the week which in the US is Sunday = 0 .
5,163
void formatDayOfMonth ( StringBuilder b , ZonedDateTime d , int width ) { int day = d . getDayOfMonth ( ) ; zeroPad2 ( b , day , width ) ; }
Format the day of the month optionally zero - padded .
5,164
void formatDayOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int day = d . getDayOfYear ( ) ; int digits = day < 10 ? 1 : day < 100 ? 2 : 3 ; switch ( digits ) { case 1 : if ( width > 1 ) { b . append ( '0' ) ; } case 2 : if ( width > 2 ) { b . append ( '0' ) ; } case 3 : b . append ( day ) ; break ; } }
Format the 3 - digit day of the year zero padded .
5,165
void formatDayOfWeekInMonth ( StringBuilder b , ZonedDateTime d , int width ) { int day = ( ( d . getDayOfMonth ( ) - 1 ) / 7 ) + 1 ; b . append ( day ) ; }
Numeric day of week in month as in 2nd Wednesday in July .
5,166
void formatDayPeriod ( StringBuilder b , ZonedDateTime d , int width , FieldVariants dayPeriods ) { int hours = d . getHour ( ) ; int index = hours < 12 ? 0 : 1 ; switch ( width ) { case 5 : b . append ( dayPeriods . narrow [ index ] ) ; break ; case 4 : b . append ( dayPeriods . wide [ index ] ) ; break ; case 3 : cas...
Format the day period variant .
5,167
void formatHours ( StringBuilder b , ZonedDateTime d , int width , boolean twelveHour ) { int hours = d . getHour ( ) ; if ( twelveHour && hours > 12 ) { hours = hours - 12 ; } if ( twelveHour && hours == 0 ) { hours = 12 ; } zeroPad2 ( b , hours , width ) ; }
Format the hours in 12 - or 24 - hour format optionally zero - padded .
5,168
void formatMinutes ( StringBuilder b , ZonedDateTime d , int width ) { zeroPad2 ( b , d . getMinute ( ) , width ) ; }
Format the minutes optionally zero - padded .
5,169
void formatSeconds ( StringBuilder b , ZonedDateTime d , int width ) { zeroPad2 ( b , d . getSecond ( ) , width ) ; }
Format the seconds optionally zero - padded .
5,170
void formatFractionalSeconds ( StringBuilder b , ZonedDateTime d , int width ) { int nano = d . getNano ( ) ; int f = 100000000 ; while ( width > 0 && f > 0 ) { int digit = nano / f ; nano -= ( digit * f ) ; f /= 10 ; b . append ( digit ) ; width -- ; } while ( width > 0 ) { b . append ( '0' ) ; width -- ; } }
Format fractional seconds up to N digits .
5,171
void formatTimeZone_O ( StringBuilder b , ZonedDateTime d , int width ) { int [ ] tz = getTzComponents ( d ) ; switch ( width ) { case 1 : wrapTimeZoneGMT ( b , tz [ TZNEG ] == - 1 , tz [ TZHOURS ] , tz [ TZMINS ] , true ) ; break ; case 4 : wrapTimeZoneGMT ( b , tz [ TZNEG ] == - 1 , tz [ TZHOURS ] , tz [ TZMINS ] , f...
Format timezone in localized GMT format for field O .
5,172
void formatTimeZone_z ( StringBuilder b , ZonedDateTime d , int width ) { if ( width > 4 ) { return ; } ZoneId zone = d . getZone ( ) ; ZoneRules zoneRules = null ; try { zoneRules = zone . getRules ( ) ; } catch ( ZoneRulesException e ) { return ; } boolean daylight = zoneRules . isDaylightSavings ( d . toInstant ( ) ...
Format a time zone using a non - location format .
5,173
private int [ ] getTzComponents ( ZonedDateTime d ) { ZoneOffset offset = d . getOffset ( ) ; int secs = offset . getTotalSeconds ( ) ; boolean negative = secs < 0 ; if ( negative ) { secs = - secs ; } int hours = secs / 3600 ; int mins = ( secs % 3600 ) / 60 ; return new int [ ] { negative ? - 1 : 1 , secs , hours , m...
Decode some fields about a time zone .
5,174
void zeroPad2 ( StringBuilder b , int value , int width ) { switch ( width ) { case 2 : if ( value < 10 ) { b . append ( '0' ) ; } case 1 : b . append ( value ) ; break ; } }
Format 2 - digit number with 0 - padding .
5,175
private static void decimal ( CLDR . Locale locale , String [ ] numbers , DecimalFormatOptions opts ) { for ( String num : numbers ) { BigDecimal n = new BigDecimal ( num ) ; StringBuilder buf = new StringBuilder ( " " ) ; NumberFormatter fmt = CLDR . get ( ) . getNumberFormatter ( locale ) ; fmt . formatDecimal ( n ,...
Format decimal numbers in this locale .
5,176
private static void money ( CLDR . Locale locale , CLDR . Currency [ ] currencies , String [ ] numbers , CurrencyFormatOptions opts ) { for ( CLDR . Currency currency : currencies ) { System . out . println ( "Currency " + currency ) ; for ( String num : numbers ) { BigDecimal n = new BigDecimal ( num ) ; NumberFormatt...
Format numbers in this locale for several currencies .
5,177
public List < UnitValue > getFactors ( Unit base , RoundingMode mode , Unit ... units ) { List < UnitValue > result = new ArrayList < > ( ) ; for ( int i = 0 ; i < units . length ; i ++ ) { UnitFactor factor = resolve ( units [ i ] , base ) ; if ( factor != null ) { BigDecimal n = factor . rational ( ) . compute ( mode...
Return an array of factors to convert the array of units to the given base .
5,178
protected UnitFactorMap add ( Unit unit , String n , Unit base ) { check ( unit ) ; check ( base ) ; if ( unit == base ) { throw new IllegalArgumentException ( "Attempt to define a unit " + unit + " in terms of itself." ) ; } Rational rational = new Rational ( n ) ; set ( unit , rational , base , true ) ; return this ;...
Set a factor to convert the unit into a given base .
5,179
protected UnitFactorMap complete ( ) { Set < Unit > units = new LinkedHashSet < > ( ) ; for ( Unit from : factors . keySet ( ) ) { units . add ( from ) ; for ( Map . Entry < Unit , UnitFactor > entry : factors . get ( from ) . entrySet ( ) ) { Unit to = entry . getKey ( ) ; units . add ( to ) ; UnitFactor factor = entr...
Creates direct conversion factors between all units by resolving the best conversion path and setting an explicit mapping if one does not already exist .
5,180
protected UnitFactor resolve ( Unit from , Unit to ) { if ( from == to ) { return new UnitFactor ( Rational . ONE , to ) ; } List < UnitFactor > path = getPath ( from , to ) ; if ( path . isEmpty ( ) ) { throw new IllegalStateException ( "Can't find a path to convert " + from + " units into " + to ) ; } UnitFactor fact...
Find the best conversion factor path between the FROM and TO units multiply them together and return the resulting factor .
5,181
private int precisionSum ( List < UnitFactor > factors ) { return factors . stream ( ) . map ( f -> totalPrecision ( f . rational ( ) ) ) . reduce ( 0 , Math :: addExact ) ; }
Reduces the list of factors by adding together the precision for all numerators and denominators .
5,182
public UnitFactor get ( Unit from , Unit to ) { Map < Unit , UnitFactor > map = factors . get ( from ) ; if ( map != null ) { UnitFactor factor = map . get ( to ) ; if ( factor != null ) { return factor ; } } return null ; }
Find an exact conversion factor between the from and to units or return null if none exists .
5,183
public String dump ( Unit unit ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( unit ) . append ( ":\n" ) ; Map < Unit , UnitFactor > map = factors . get ( unit ) ; for ( Unit base : map . keySet ( ) ) { UnitFactor factor = map . get ( base ) ; buf . append ( " " ) . append ( factor ) . append ( " " ) ;...
Debugging conversion factors .
5,184
private void set ( Unit unit , Rational rational , Unit base , boolean replace ) { Map < Unit , UnitFactor > map = factors . get ( unit ) ; if ( map == null ) { map = new EnumMap < > ( Unit . class ) ; factors . put ( unit , map ) ; } if ( replace || ! map . containsKey ( base ) ) { map . put ( base , new UnitFactor ( ...
Set a conversion factor that converts UNIT to BASE . If the replace flag is true we always overwrite the mapping .
5,185
private List < UnitFactor > list ( UnitFactor factor ) { List < UnitFactor > list = new ArrayList < > ( ) ; list . add ( factor ) ; return list ; }
Construct a list containing just this factor .
5,186
private List < Unit > getBases ( Unit unit ) { Map < Unit , UnitFactor > map = factors . get ( unit ) ; if ( map != null ) { return map . values ( ) . stream ( ) . map ( u -> u . unit ( ) ) . collect ( Collectors . toList ( ) ) ; } return Collections . emptyList ( ) ; }
Fetch all of the existing bases for the given unit . A base is a conversion factor that was directly added or the inverse of one that was directly added .
5,187
private static int hash ( String k1 , String k2 ) { int h = ( k1 . hashCode ( ) * 33 ) + k2 . hashCode ( ) ; return h ^ ( h >>> 16 ) ; }
Combine the hash codes for the two keys then mix .
5,188
public void setPattern ( NumberPattern pattern , int _maxSigDigits , int _minSigDigits ) { Format format = pattern . format ( ) ; minIntDigits = orDefault ( options . minimumIntegerDigits ( ) , format . minimumIntegerDigits ( ) ) ; maxFracDigits = currencyDigits == - 1 ? format . maximumFractionDigits ( ) : currencyDig...
Set the pattern and initialize parameters based on the arguments pattern and options settings .
5,189
public BigDecimal adjust ( BigDecimal n ) { return NumberFormattingUtils . setup ( n , options . roundMode ( ) , formatMode , minIntDigits , maxFracDigits , minFracDigits , maxSigDigits , minSigDigits ) ; }
Adjust the number using all of the options .
5,190
public Pair < List < Node > , List < Node > > splitIntervalPattern ( String raw ) { List < Node > pattern = parse ( raw ) ; Set < Character > seen = new HashSet < > ( ) ; List < Node > fst = new ArrayList < > ( ) ; List < Node > snd = new ArrayList < > ( ) ; boolean boundary = false ; for ( Node node : pattern ) { if (...
Looks for the first repeated field in the pattern splitting it into two parts on that boundary .
5,191
public static String render ( List < Node > nodes ) { StringBuilder buf = new StringBuilder ( ) ; for ( Node node : nodes ) { if ( node instanceof Text ) { String text = ( ( Text ) node ) . text ; boolean inquote = false ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char ch = text . charAt ( i ) ; switch ( ch ) ...
Render the compiled pattern back into string form .
5,192
public List < Node > parse ( String raw ) { StringBuilder buf = new StringBuilder ( ) ; char field = '\0' ; int width = 0 ; boolean inquote = false ; int length = raw . length ( ) ; int i = 0 ; List < Node > nodes = new ArrayList < > ( ) ; while ( i < length ) { char ch = raw . charAt ( i ) ; if ( inquote ) { if ( ch =...
Parses a CLDR date - time pattern into a series of Text and Field nodes .
5,193
public static void generate ( Path outputDir ) throws IOException { DataReader reader = DataReader . get ( ) ; CalendarCodeGenerator datetimeGenerator = new CalendarCodeGenerator ( ) ; Map < LocaleID , ClassName > dateClasses = datetimeGenerator . generate ( outputDir , reader ) ; PluralCodeGenerator pluralGenerator = ...
Loads all CLDR data and invokes the code generators for each data type . Output is a series of Java classes under the outputDir .
5,194
public static void saveClass ( Path rootDir , String packageName , String className , TypeSpec type ) throws IOException { List < String > packagePath = Splitter . on ( '.' ) . splitToList ( packageName ) ; Path classPath = Paths . get ( rootDir . toString ( ) , packagePath . toArray ( EMPTY ) ) ; Path outputFile = cla...
Saves a Java class file to a path for the given package rooted in rootDir .
5,195
private static void addPluralRules ( TypeSpec . Builder type ) { FieldSpec field = FieldSpec . builder ( PLURAL_RULES , "pluralRules" , PRIVATE , STATIC , FINAL ) . initializer ( "new $T()" , PLURAL_RULES ) . build ( ) ; MethodSpec method = MethodSpec . methodBuilder ( "getPluralRules" ) . addModifiers ( PUBLIC ) . ret...
Add static instance of plural rules and accessor method .
5,196
private static MethodSpec indexFormatters ( String methodName , String registerMethodName , Map < LocaleID , ClassName > dateClasses ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( methodName ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < LocaleID , ClassName > entry : dateClasses . entrySet...
Generates a static code block that populates the formatter map .
5,197
private static void addLocaleField ( TypeSpec . Builder type , String name , LocaleID locale ) { FieldSpec . Builder field = FieldSpec . builder ( CLDR_LOCALE_IF , name , PUBLIC , STATIC , FINAL ) . initializer ( "new $T($S, $S, $S, $S)" , META_LOCALE , strOrNull ( locale . language ) , strOrNull ( locale . script ) , ...
Create a public locale field .
5,198
private static void createLanguageAliases ( TypeSpec . Builder type , Map < String , String > languageAliases ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "registerLanguageAliases" ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < String , String > entry : languageAliases . entrySet ( ) ) { ...
Create language alias mapping .
5,199
private static void createLikelySubtags ( TypeSpec . Builder type , Map < String , String > likelySubtags ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "registerLikelySubtags" ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < String , String > entry : likelySubtags . entrySet ( ) ) { method ....
Create likely subtags mapping .