repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addMetaZones
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, "metazones", PROTECTED, STATIC, FINAL); CodeBlock.Builder code = CodeBlock.builder(); code.beginControlFlow("new $T<$T, $T>() {", HashMap.class, String.class, metazoneType); for (Map.Entry<String, MetaZone> entry : metazones.entrySet()) { String zoneId = entry.getKey(); MetaZone zone = entry.getValue(); code.beginControlFlow("\nput($S, new $T($S,\n new $T.Entry[] ", zoneId, metazoneType, zoneId, metazoneType); int size = zone.metazones.size(); Collections.reverse(zone.metazones); for (int i = 0; i < size; i++) { MetaZoneEntry meta = zone.metazones.get(i); if (i > 0) { code.add(",\n"); } code.add(" new $T.Entry($S, ", metazoneType, meta.metazone); if (meta.from != null) { code.add("/* $L */ $L, ", meta.fromString, meta.from.toEpochSecond()); } else { code.add("-1, "); } if (meta.to != null) { code.add("/* $L */ $L)", meta.toString, meta.to.toEpochSecond()); } else { code.add("-1)"); } } code.endControlFlow("))"); } code.endControlFlow("\n}"); field.initializer(code.build()); type.addField(field.build()); MethodSpec.Builder method = MethodSpec.methodBuilder("getMetazone") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "zoneId") .addParameter(ZonedDateTime.class, "date") .returns(String.class); method.addStatement("$T zone = metazones.get(zoneId)", metazoneType); method.addStatement("return zone == null ? null : zone.applies(date)"); type.addMethod(method.build()); }
java
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, "metazones", PROTECTED, STATIC, FINAL); CodeBlock.Builder code = CodeBlock.builder(); code.beginControlFlow("new $T<$T, $T>() {", HashMap.class, String.class, metazoneType); for (Map.Entry<String, MetaZone> entry : metazones.entrySet()) { String zoneId = entry.getKey(); MetaZone zone = entry.getValue(); code.beginControlFlow("\nput($S, new $T($S,\n new $T.Entry[] ", zoneId, metazoneType, zoneId, metazoneType); int size = zone.metazones.size(); Collections.reverse(zone.metazones); for (int i = 0; i < size; i++) { MetaZoneEntry meta = zone.metazones.get(i); if (i > 0) { code.add(",\n"); } code.add(" new $T.Entry($S, ", metazoneType, meta.metazone); if (meta.from != null) { code.add("/* $L */ $L, ", meta.fromString, meta.from.toEpochSecond()); } else { code.add("-1, "); } if (meta.to != null) { code.add("/* $L */ $L)", meta.toString, meta.to.toEpochSecond()); } else { code.add("-1)"); } } code.endControlFlow("))"); } code.endControlFlow("\n}"); field.initializer(code.build()); type.addField(field.build()); MethodSpec.Builder method = MethodSpec.methodBuilder("getMetazone") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "zoneId") .addParameter(ZonedDateTime.class, "date") .returns(String.class); method.addStatement("$T zone = metazones.get(zoneId)", metazoneType); method.addStatement("return zone == null ? null : zone.applies(date)"); type.addMethod(method.build()); }
[ "private", "void", "addMetaZones", "(", "TypeSpec", ".", "Builder", "type", ",", "Map", "<", "String", ",", "MetaZone", ">", "metazones", ")", "{", "ClassName", "metazoneType", "=", "ClassName", ".", "get", "(", "Types", ".", "PACKAGE_CLDR_DATES", ",", "\"Me...
Populate the metaZone mapping.
[ "Populate", "the", "metaZone", "mapping", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L133-L181
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildTimeZoneAliases
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 (zoneId)"); for (Map.Entry<String, String> entry : map.entrySet()) { method.addStatement("case $S: return $S", entry.getKey(), entry.getValue()); } method.addStatement("default: return null"); method.endControlFlow(); type.addMethod(method.build()); }
java
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 (zoneId)"); for (Map.Entry<String, String> entry : map.entrySet()) { method.addStatement("case $S: return $S", entry.getKey(), entry.getValue()); } method.addStatement("default: return null"); method.endControlFlow(); type.addMethod(method.build()); }
[ "private", "void", "buildTimeZoneAliases", "(", "TypeSpec", ".", "Builder", "type", ",", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"getTimeZoneAlias\"", ")...
Creates a switch table to resolve a retired time zone to a valid one.
[ "Creates", "a", "switch", "table", "to", "resolve", "a", "retired", "time", "zone", "to", "a", "valid", "one", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L186-L199
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.createFormatter
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.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
java
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.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
[ "private", "TypeSpec", "createFormatter", "(", "DateTimeData", "dateTimeData", ",", "TimeZoneData", "timeZoneData", ",", "String", "className", ")", "{", "LocaleID", "id", "=", "dateTimeData", ".", "id", ";", "MethodSpec", ".", "Builder", "constructor", "=", "Meth...
Create a Java class that captures all data formats for a given locale.
[ "Create", "a", "Java", "class", "that", "captures", "all", "data", "formats", "for", "a", "given", "locale", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L204-L253
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addTypedPattern
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(); }
java
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(); }
[ "private", "void", "addTypedPattern", "(", "MethodSpec", ".", "Builder", "method", ",", "String", "formatType", ",", "String", "pattern", ")", "{", "method", ".", "beginControlFlow", "(", "\"case $L:\"", ",", "formatType", ")", ";", "method", ".", "addComment", ...
Adds the pattern builder statements for a typed pattern.
[ "Adds", "the", "pattern", "builder", "statements", "for", "a", "typed", "pattern", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L285-L291
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addPattern
private void addPattern(MethodSpec.Builder method, String pattern) { // Parse the pattern and populate the method body with instructions to format the date. 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.addStatement("formatField(d, '$L', $L, b)", field.ch(), field.width()); } } }
java
private void addPattern(MethodSpec.Builder method, String pattern) { // Parse the pattern and populate the method body with instructions to format the date. 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.addStatement("formatField(d, '$L', $L, b)", field.ch(), field.width()); } } }
[ "private", "void", "addPattern", "(", "MethodSpec", ".", "Builder", "method", ",", "String", "pattern", ")", "{", "// Parse the pattern and populate the method body with instructions to format the date.", "for", "(", "Node", "node", ":", "DATETIME_PARSER", ".", "parse", "...
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.
[ "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", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L297-L307
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildSkeletonFormatter
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") .addParameter(StringBuilder.class, "b") .returns(boolean.class); method.beginControlFlow("if (skeleton == null)"); method.addStatement("return false"); method.endControlFlow(); method.beginControlFlow("switch (skeleton)"); // Skeleton patterns. for (Skeleton skeleton : skeletons) { method.beginControlFlow("case $S:", skeleton.skeleton) .addComment("Pattern: $S", skeleton.pattern); addPattern(method, skeleton.pattern); method.addStatement("break"); method.endControlFlow(); } method.beginControlFlow("default:"); method.addStatement("return false"); method.endControlFlow(); method.endControlFlow(); method.addStatement("return true"); return method.build(); }
java
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") .addParameter(StringBuilder.class, "b") .returns(boolean.class); method.beginControlFlow("if (skeleton == null)"); method.addStatement("return false"); method.endControlFlow(); method.beginControlFlow("switch (skeleton)"); // Skeleton patterns. for (Skeleton skeleton : skeletons) { method.beginControlFlow("case $S:", skeleton.skeleton) .addComment("Pattern: $S", skeleton.pattern); addPattern(method, skeleton.pattern); method.addStatement("break"); method.endControlFlow(); } method.beginControlFlow("default:"); method.addStatement("return false"); method.endControlFlow(); method.endControlFlow(); method.addStatement("return true"); return method.build(); }
[ "private", "MethodSpec", "buildSkeletonFormatter", "(", "List", "<", "Skeleton", ">", "skeletons", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"formatSkeleton\"", ")", ".", "addAnnotation", "(", "Override", "."...
Implements the formatSkeleton method.
[ "Implements", "the", "formatSkeleton", "method", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L377-L411
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildIntervalMethod
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") .addParameter(ZonedDateTime.class, "e") .addParameter(String.class, "k") .addParameter(DateTimeField.class, "f") .addParameter(StringBuilder.class, "b"); // Only enter the switches if both params are non-null. method.beginControlFlow("if (k != null && f != null)"); // BEGIN switch (k) method.beginControlFlow("switch (k)"); for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) { String skeleton = format.getKey(); // BEGIN "case skeleton:" method.beginControlFlow("case $S:", skeleton); method.beginControlFlow("switch (f)"); for (Map.Entry<String, String> entry : format.getValue().entrySet()) { String field = entry.getKey(); // Split the interval pattern on the boundary. We end up with two patterns, one for // start and end respectively. Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue()); // BEGIN "case field:" // Render this pair of patterns when the given field matches. method.beginControlFlow("case $L:", DateTimeField.fromString(field)); method.addComment("$S", DateTimePatternParser.render(patterns._1)); addIntervalPattern(method, patterns._1, "s"); method.addComment("$S", DateTimePatternParser.render(patterns._2)); addIntervalPattern(method, patterns._2, "e"); method.addStatement("return"); method.endControlFlow(); // END "case field:" } method.addStatement("default: break"); method.endControlFlow(); // switch (f) method.addStatement("break"); method.endControlFlow(); // END "case skeleton:" } method.addStatement("default: break"); method.endControlFlow(); // END switch (k) // One of the parameters was null, or nothing matched, so render the // fallback, e.g. format the start / end separately as "{0} - {1}" addIntervalFallback(method, fallback); method.endControlFlow(); return method.build(); }
java
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") .addParameter(ZonedDateTime.class, "e") .addParameter(String.class, "k") .addParameter(DateTimeField.class, "f") .addParameter(StringBuilder.class, "b"); // Only enter the switches if both params are non-null. method.beginControlFlow("if (k != null && f != null)"); // BEGIN switch (k) method.beginControlFlow("switch (k)"); for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) { String skeleton = format.getKey(); // BEGIN "case skeleton:" method.beginControlFlow("case $S:", skeleton); method.beginControlFlow("switch (f)"); for (Map.Entry<String, String> entry : format.getValue().entrySet()) { String field = entry.getKey(); // Split the interval pattern on the boundary. We end up with two patterns, one for // start and end respectively. Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue()); // BEGIN "case field:" // Render this pair of patterns when the given field matches. method.beginControlFlow("case $L:", DateTimeField.fromString(field)); method.addComment("$S", DateTimePatternParser.render(patterns._1)); addIntervalPattern(method, patterns._1, "s"); method.addComment("$S", DateTimePatternParser.render(patterns._2)); addIntervalPattern(method, patterns._2, "e"); method.addStatement("return"); method.endControlFlow(); // END "case field:" } method.addStatement("default: break"); method.endControlFlow(); // switch (f) method.addStatement("break"); method.endControlFlow(); // END "case skeleton:" } method.addStatement("default: break"); method.endControlFlow(); // END switch (k) // One of the parameters was null, or nothing matched, so render the // fallback, e.g. format the start / end separately as "{0} - {1}" addIntervalFallback(method, fallback); method.endControlFlow(); return method.build(); }
[ "private", "MethodSpec", "buildIntervalMethod", "(", "Map", "<", "String", ",", "Map", "<", "String", ",", "String", ">", ">", "intervalFormats", ",", "String", "fallback", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilde...
Build methods to format date time intervals using the field of greatest difference.
[ "Build", "methods", "to", "format", "date", "time", "intervals", "using", "the", "field", "of", "greatest", "difference", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L416-L474
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addIntervalPattern
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.addStatement("formatField($L, '$L', $L, b)", which, field.ch(), field.width()); } } }
java
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.addStatement("formatField($L, '$L', $L, b)", which, field.ch(), field.width()); } } }
[ "private", "void", "addIntervalPattern", "(", "MethodSpec", ".", "Builder", "method", ",", "List", "<", "Node", ">", "pattern", ",", "String", "which", ")", "{", "for", "(", "Node", "node", ":", "pattern", ")", "{", "if", "(", "node", "instanceof", "Text...
Adds code to format a date time interval pattern, which may be the start or end date time, signified by the 'which' parameter.
[ "Adds", "code", "to", "format", "a", "date", "time", "interval", "pattern", "which", "may", "be", "the", "start", "or", "end", "date", "time", "signified", "by", "the", "which", "parameter", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L480-L489
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addIntervalFallback
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 Field) { Field field = (Field)node; String which = "s"; if (field.ch() == '1') { which = "e"; } method.addStatement("formatSkeleton(k, $L, b)", which); } } }
java
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 Field) { Field field = (Field)node; String which = "s"; if (field.ch() == '1') { which = "e"; } method.addStatement("formatSkeleton(k, $L, b)", which); } } }
[ "private", "void", "addIntervalFallback", "(", "MethodSpec", ".", "Builder", "method", ",", "String", "pattern", ")", "{", "method", ".", "addComment", "(", "\"$S\"", ",", "pattern", ")", ";", "for", "(", "Node", "node", ":", "WRAPPER_PARSER", ".", "parseWra...
Adds code to render the fallback pattern.
[ "Adds", "code", "to", "render", "the", "fallback", "pattern", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L494-L509
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.isDateSkeleton
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 (field.ch()) { case 'H': case 'h': case 'm': case 's': return false; } } } return true; }
java
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 (field.ch()) { case 'H': case 'h': case 'm': case 's': return false; } } } return true; }
[ "private", "boolean", "isDateSkeleton", "(", "String", "skeleton", ")", "{", "List", "<", "String", ">", "parts", "=", "Splitter", ".", "on", "(", "'", "'", ")", ".", "splitToList", "(", "skeleton", ")", ";", "if", "(", "parts", ".", "size", "(", ")"...
Indicates a skeleton represents a date based on the fields it contains. Any time-related field will cause this to return false.
[ "Indicates", "a", "skeleton", "represents", "a", "date", "based", "on", "the", "fields", "it", "contains", ".", "Any", "time", "-", "related", "field", "will", "cause", "this", "to", "return", "false", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L515-L533
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildSkeletonType
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) .addParameter(String.class, "skeleton") .returns(SKELETON); method.beginControlFlow("switch (skeleton)"); for (String skel : dateSkeletons) { method.addCode("case $S:\n", skel); } method.addStatement(" return $T.DATE", SKELETON); for (String skel : timeSkeletons) { method.addCode("case $S:\n", skel); } method.addStatement(" return $T.TIME", SKELETON); method.addCode("default:\n"); method.addStatement(" return null"); method.endControlFlow(); return method; }
java
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) .addParameter(String.class, "skeleton") .returns(SKELETON); method.beginControlFlow("switch (skeleton)"); for (String skel : dateSkeletons) { method.addCode("case $S:\n", skel); } method.addStatement(" return $T.DATE", SKELETON); for (String skel : timeSkeletons) { method.addCode("case $S:\n", skel); } method.addStatement(" return $T.TIME", SKELETON); method.addCode("default:\n"); method.addStatement(" return null"); method.endControlFlow(); return method; }
[ "private", "MethodSpec", ".", "Builder", "buildSkeletonType", "(", "Set", "<", "String", ">", "dateSkeletons", ",", "Set", "<", "String", ">", "timeSkeletons", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"s...
Constructs a method to indicate if the skeleton is a DATE or TIME, or null if unsupported.
[ "Constructs", "a", "method", "to", "indicate", "if", "the", "skeleton", "is", "a", "DATE", "or", "TIME", "or", "null", "if", "unsupported", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L538-L562
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.variantsFieldInit
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("\n ").append(v.short_).comma(); b.append("\n ").append(v.wide); b.append(")"); method.addStatement(b.format(), b.args()); }
java
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("\n ").append(v.short_).comma(); b.append("\n ").append(v.wide); b.append(")"); method.addStatement(b.format(), b.args()); }
[ "private", "void", "variantsFieldInit", "(", "MethodSpec", ".", "Builder", "method", ",", "String", "fieldName", ",", "Variants", "v", ")", "{", "Stmt", "b", "=", "new", "Stmt", "(", ")", ";", "b", ".", "append", "(", "\"$L = new $T(\"", ",", "fieldName", ...
Appends a statement that initializes a FieldVariants field in the superclass.
[ "Appends", "a", "statement", "that", "initializes", "a", "FieldVariants", "field", "in", "the", "superclass", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L567-L576
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildTimeZoneExemplarCities
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) { code.addStatement("put($S, $S)", info.zone, info.exemplarCity); } code.endControlFlow("}"); method.addCode(code.build()); }
java
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) { code.addStatement("put($S, $S)", info.zone, info.exemplarCity); } code.endControlFlow("}"); method.addCode(code.build()); }
[ "private", "void", "buildTimeZoneExemplarCities", "(", "MethodSpec", ".", "Builder", "method", ",", "TimeZoneData", "data", ")", "{", "CodeBlock", ".", "Builder", "code", "=", "CodeBlock", ".", "builder", "(", ")", ";", "code", ".", "beginControlFlow", "(", "\...
Mapping locale identifiers to their localized exemplar cities.
[ "Mapping", "locale", "identifiers", "to", "their", "localized", "exemplar", "cities", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L581-L589
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildMetaZoneNames
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.nameLong == null && info.nameShort == null) { continue; } code.add("\nput($S, new $T($S, ", info.zone, TIMEZONE_NAMES, info.zone); if (info.nameLong == null) { code.add("\n null,"); } else { code.add("\n new $T.Name($S, $S, $S),", TIMEZONE_NAMES, info.nameLong.generic, info.nameLong.standard, info.nameLong.daylight); } if (info.nameShort == null) { code.add("\n null"); } else { code.add("\n new $T.Name($S, $S, $S)", TIMEZONE_NAMES, info.nameShort.generic, info.nameShort.standard, info.nameShort.daylight); } code.add("));\n"); } code.endControlFlow("}"); method.addCode(code.build()); }
java
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.nameLong == null && info.nameShort == null) { continue; } code.add("\nput($S, new $T($S, ", info.zone, TIMEZONE_NAMES, info.zone); if (info.nameLong == null) { code.add("\n null,"); } else { code.add("\n new $T.Name($S, $S, $S),", TIMEZONE_NAMES, info.nameLong.generic, info.nameLong.standard, info.nameLong.daylight); } if (info.nameShort == null) { code.add("\n null"); } else { code.add("\n new $T.Name($S, $S, $S)", TIMEZONE_NAMES, info.nameShort.generic, info.nameShort.standard, info.nameShort.daylight); } code.add("));\n"); } code.endControlFlow("}"); method.addCode(code.build()); }
[ "private", "void", "buildMetaZoneNames", "(", "MethodSpec", ".", "Builder", "method", ",", "TimeZoneData", "data", ")", "{", "CodeBlock", ".", "Builder", "code", "=", "CodeBlock", ".", "builder", "(", ")", ";", "code", ".", "beginControlFlow", "(", "\"\\nthis....
Builds localized metazone name mapping.
[ "Builds", "localized", "metazone", "name", "mapping", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L625-L651
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildWrapTimeZoneGMTMethod
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.parseWrapper(data.gmtFormat); MethodSpec.Builder method = MethodSpec.methodBuilder("wrapTimeZoneGMT") .addModifiers(PROTECTED) .addParameter(StringBuilder.class, "b") .addParameter(boolean.class, "neg") .addParameter(int.class, "hours") .addParameter(int.class, "mins") .addParameter(boolean.class, "_short"); // Special format for zero method.beginControlFlow("if (hours == 0 && mins == 0)"); method.addStatement("b.append($S)", data.gmtZeroFormat); method.addStatement("return"); method.endControlFlow(); method.addStatement("boolean emitMins = !_short || mins > 0"); for (Node node : format) { if (node instanceof Text) { Text text = (Text) node; method.addStatement("b.append($S)", text.text()); } else { method.beginControlFlow("if (neg)"); appendHourFormat(method, negative); method.endControlFlow(); method.beginControlFlow("else"); appendHourFormat(method, positive); method.endControlFlow(); } } return method.build(); }
java
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.parseWrapper(data.gmtFormat); MethodSpec.Builder method = MethodSpec.methodBuilder("wrapTimeZoneGMT") .addModifiers(PROTECTED) .addParameter(StringBuilder.class, "b") .addParameter(boolean.class, "neg") .addParameter(int.class, "hours") .addParameter(int.class, "mins") .addParameter(boolean.class, "_short"); // Special format for zero method.beginControlFlow("if (hours == 0 && mins == 0)"); method.addStatement("b.append($S)", data.gmtZeroFormat); method.addStatement("return"); method.endControlFlow(); method.addStatement("boolean emitMins = !_short || mins > 0"); for (Node node : format) { if (node instanceof Text) { Text text = (Text) node; method.addStatement("b.append($S)", text.text()); } else { method.beginControlFlow("if (neg)"); appendHourFormat(method, negative); method.endControlFlow(); method.beginControlFlow("else"); appendHourFormat(method, positive); method.endControlFlow(); } } return method.build(); }
[ "private", "MethodSpec", "buildWrapTimeZoneGMTMethod", "(", "TimeZoneData", "data", ")", "{", "String", "[", "]", "hourFormat", "=", "data", ".", "hourFormat", ".", "split", "(", "\";\"", ")", ";", "List", "<", "Node", ">", "positive", "=", "DATETIME_PARSER", ...
Builds a method to format the timezone as hourFormat with a GMT wrapper.
[ "Builds", "a", "method", "to", "format", "the", "timezone", "as", "hourFormat", "with", "a", "GMT", "wrapper", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L656-L692
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildWrapTimeZoneRegionMethod
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.parseWrapper(data.regionFormat); for (Node node : format) { if (node instanceof Text) { Text text = (Text) node; method.addStatement("b.append($S)", text.text()); } else { method.addStatement("b.append(region)"); } } return method.build(); }
java
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.parseWrapper(data.regionFormat); for (Node node : format) { if (node instanceof Text) { Text text = (Text) node; method.addStatement("b.append($S)", text.text()); } else { method.addStatement("b.append(region)"); } } return method.build(); }
[ "private", "MethodSpec", "buildWrapTimeZoneRegionMethod", "(", "TimeZoneData", "data", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"wrapTimeZoneRegion\"", ")", ".", "addModifiers", "(", "PROTECTED", ")", ".", "ad...
Build a method to wrap a region in the regionFormat.
[ "Build", "a", "method", "to", "wrap", "a", "region", "in", "the", "regionFormat", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L697-L715
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.appendHourFormat
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("b.append($S)", t); if (minute) { method.endControlFlow(); } } else { Field f = (Field)n; if (f.ch() == 'H') { if (f.width() == 1) { method.addStatement("zeroPad2(b, hours, 1)"); } else { method.addStatement("zeroPad2(b, hours, _short ? 1 : $L)", f.width()); } } else { method.beginControlFlow("if (emitMins)"); method.addStatement("zeroPad2(b, mins, $L)", f.width()); method.endControlFlow(); } } } }
java
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("b.append($S)", t); if (minute) { method.endControlFlow(); } } else { Field f = (Field)n; if (f.ch() == 'H') { if (f.width() == 1) { method.addStatement("zeroPad2(b, hours, 1)"); } else { method.addStatement("zeroPad2(b, hours, _short ? 1 : $L)", f.width()); } } else { method.beginControlFlow("if (emitMins)"); method.addStatement("zeroPad2(b, mins, $L)", f.width()); method.endControlFlow(); } } } }
[ "private", "void", "appendHourFormat", "(", "MethodSpec", ".", "Builder", "method", ",", "List", "<", "Node", ">", "fmt", ")", "{", "for", "(", "Node", "n", ":", "fmt", ")", "{", "if", "(", "n", "instanceof", "Text", ")", "{", "String", "t", "=", "...
Appends code to emit the hourFormat for positive or negative.
[ "Appends", "code", "to", "emit", "the", "hourFormat", "for", "positive", "or", "negative", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L720-L747
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.deduplicateFormats
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, "FULL"); return res; }
java
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, "FULL"); return res; }
[ "public", "static", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "deduplicateFormats", "(", "Format", "format", ")", "{", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "res", "=", "new", "LinkedHashMap", "<>", "(", ")", "...
De-duplication of formats.
[ "De", "-", "duplication", "of", "formats", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L753-L760
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/Utils.java
Utils.listResources
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 (String prefix : prefixes) { if (path.startsWith(prefix)) { result.add(Paths.get(path)); } } } return result; }
java
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 (String prefix : prefixes) { if (path.startsWith(prefix)) { result.add(Paths.get(path)); } } } return result; }
[ "public", "static", "List", "<", "Path", ">", "listResources", "(", "String", "...", "prefixes", ")", "throws", "IOException", "{", "List", "<", "Path", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "ClassPath", "classPath", "=", "ClassPath"...
Recursively list all resources under the given path prefixes.
[ "Recursively", "list", "all", "resources", "under", "the", "given", "path", "prefixes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/Utils.java#L21-L33
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/Utils.java
Utils.findChild
public static Node<PluralType> findChild(Struct<PluralType> parent, PluralType type) { for (Node<PluralType> n : parent.nodes()) { if (n.type() == type) { return n; } } return null; }
java
public static Node<PluralType> findChild(Struct<PluralType> parent, PluralType type) { for (Node<PluralType> n : parent.nodes()) { if (n.type() == type) { return n; } } return null; }
[ "public", "static", "Node", "<", "PluralType", ">", "findChild", "(", "Struct", "<", "PluralType", ">", "parent", ",", "PluralType", "type", ")", "{", "for", "(", "Node", "<", "PluralType", ">", "n", ":", "parent", ".", "nodes", "(", ")", ")", "{", "...
Find a child node of a given type in a parent struct, or return null.
[ "Find", "a", "child", "node", "of", "a", "given", "type", "in", "a", "parent", "struct", "or", "return", "null", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/Utils.java#L38-L45
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRuleGrammar.java
PluralRuleGrammar.parse
public static Maybe<Pair<Node<PluralType>, CharSequence>> parse(String input) { return P_RULE.parse(input); }
java
public static Maybe<Pair<Node<PluralType>, CharSequence>> parse(String input) { return P_RULE.parse(input); }
[ "public", "static", "Maybe", "<", "Pair", "<", "Node", "<", "PluralType", ">", ",", "CharSequence", ">", ">", "parse", "(", "String", "input", ")", "{", "return", "P_RULE", ".", "parse", "(", "input", ")", ";", "}" ]
Parse a plural rule into an abstract syntax tree.
[ "Parse", "a", "plural", "rule", "into", "an", "abstract", "syntax", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRuleGrammar.java#L107-L109
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/UnitConverters.java
UnitConverters.get
public static UnitConverter get(CLDR.Locale locale) { MeasurementSystem system = MeasurementSystem.fromLocale(locale); return SYSTEMS.getOrDefault(system, METRIC_SYSTEM); }
java
public static UnitConverter get(CLDR.Locale locale) { MeasurementSystem system = MeasurementSystem.fromLocale(locale); return SYSTEMS.getOrDefault(system, METRIC_SYSTEM); }
[ "public", "static", "UnitConverter", "get", "(", "CLDR", ".", "Locale", "locale", ")", "{", "MeasurementSystem", "system", "=", "MeasurementSystem", ".", "fromLocale", "(", "locale", ")", ";", "return", "SYSTEMS", ".", "getOrDefault", "(", "system", ",", "METR...
Retrieves the correct measurement system for a given locale.
[ "Retrieves", "the", "correct", "measurement", "system", "for", "a", "given", "locale", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/UnitConverters.java#L20-L23
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/NumberFormatOptions.java
NumberFormatOptions.reset
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; }
java
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; }
[ "public", "void", "reset", "(", ")", "{", "this", ".", "formatMode", "=", "null", ";", "this", ".", "roundMode", "=", "NumberRoundMode", ".", "ROUND", ";", "this", ".", "grouping", "=", "null", ";", "this", ".", "minimumIntegerDigits", "=", "null", ";", ...
Reset the options to their defaults.
[ "Reset", "the", "options", "to", "their", "defaults", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberFormatOptions.java#L26-L35
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.setFormat
public void setFormat(String format) { this.format = format; // Track multiple streams over the format string. 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; } // Streams for temporary matching. this.tag = scanner.stream(); this.choice = scanner.stream(); }
java
public void setFormat(String format) { this.format = format; // Track multiple streams over the format string. 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; } // Streams for temporary matching. this.tag = scanner.stream(); this.choice = scanner.stream(); }
[ "public", "void", "setFormat", "(", "String", "format", ")", "{", "this", ".", "format", "=", "format", ";", "// Track multiple streams over the format string.", "Scanner", "scanner", "=", "new", "Scanner", "(", "format", ")", ";", "this", ".", "streams", "[", ...
Sets the message format.
[ "Sets", "the", "message", "format", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L218-L232
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.format
public void format(MessageArgs args, StringBuilder buf) { this.args = args; this.buf = buf; this.reset(); format(streams[0], null); }
java
public void format(MessageArgs args, StringBuilder buf) { this.args = args; this.buf = buf; this.reset(); format(streams[0], null); }
[ "public", "void", "format", "(", "MessageArgs", "args", ",", "StringBuilder", "buf", ")", "{", "this", ".", "args", "=", "args", ";", "this", ".", "buf", "=", "buf", ";", "this", ".", "reset", "(", ")", ";", "format", "(", "streams", "[", "0", "]",...
Formats the message using the given arguments, and writing the output to the buffer.
[ "Formats", "the", "message", "using", "the", "given", "arguments", "and", "writing", "the", "output", "to", "the", "buffer", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L237-L242
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.recurse
private void recurse(Stream bounds, String arg) { // Refuse if we've reached our recursion limit. streamIndex++; if (streamIndex == streams.length) { return; } // Trim the '{' and '}' bounding characters. bounds.pos++; bounds.end--; // Set the bounds of the tag, allocating a new stream on the stack if necessary. if (streams[streamIndex] == null) { streams[streamIndex] = bounds.copy(); } else { streams[streamIndex].setFrom(bounds); } // Execute the formatter recursively on the current bounds, then // pop the stack. format(streams[streamIndex], arg); streamIndex--; }
java
private void recurse(Stream bounds, String arg) { // Refuse if we've reached our recursion limit. streamIndex++; if (streamIndex == streams.length) { return; } // Trim the '{' and '}' bounding characters. bounds.pos++; bounds.end--; // Set the bounds of the tag, allocating a new stream on the stack if necessary. if (streams[streamIndex] == null) { streams[streamIndex] = bounds.copy(); } else { streams[streamIndex].setFrom(bounds); } // Execute the formatter recursively on the current bounds, then // pop the stack. format(streams[streamIndex], arg); streamIndex--; }
[ "private", "void", "recurse", "(", "Stream", "bounds", ",", "String", "arg", ")", "{", "// Refuse if we've reached our recursion limit.", "streamIndex", "++", ";", "if", "(", "streamIndex", "==", "streams", ".", "length", ")", "{", "return", ";", "}", "// Trim t...
Push a stream onto the stack and format it.
[ "Push", "a", "stream", "onto", "the", "stack", "and", "format", "it", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L292-L314
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evaluateTag
private void evaluateTag(StringBuilder buf) { // Trim the '{' and '}' bounding characters. tag.pos++; tag.end--; // If this tag has been hidden from the processor, skip over the '-' and // emit the tag body. 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) { return; } MessageArg arg = args.get(0); // Process a short tag like "{1}" by just appending the argument value. if (tag.peek() == Chars.EOF) { if (arg.resolve()) { buf.append(arg.asString()); } return; } // Parse the formatter name and execute the associated formatting method. if (tag.seek(FORMATTER, choice)) { String formatter = choice.token().toString(); tag.jump(choice); switch (formatter) { case PLURAL: evalPlural(arg, true); break; case SELECTORDINAL: evalPlural(arg, false); break; case SELECT: evalSelect(arg); break; case CURRENCY: case MONEY: evalCurrency(arg); break; case DATETIME: evalDateTime(arg); break; case DATETIME_INTERVAL: evalDateTimeInterval(args); break; case DECIMAL: case NUMBER: evalNumber(arg); break; case UNIT: evalUnit(arg); break; } } }
java
private void evaluateTag(StringBuilder buf) { // Trim the '{' and '}' bounding characters. tag.pos++; tag.end--; // If this tag has been hidden from the processor, skip over the '-' and // emit the tag body. 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) { return; } MessageArg arg = args.get(0); // Process a short tag like "{1}" by just appending the argument value. if (tag.peek() == Chars.EOF) { if (arg.resolve()) { buf.append(arg.asString()); } return; } // Parse the formatter name and execute the associated formatting method. if (tag.seek(FORMATTER, choice)) { String formatter = choice.token().toString(); tag.jump(choice); switch (formatter) { case PLURAL: evalPlural(arg, true); break; case SELECTORDINAL: evalPlural(arg, false); break; case SELECT: evalSelect(arg); break; case CURRENCY: case MONEY: evalCurrency(arg); break; case DATETIME: evalDateTime(arg); break; case DATETIME_INTERVAL: evalDateTimeInterval(args); break; case DECIMAL: case NUMBER: evalNumber(arg); break; case UNIT: evalUnit(arg); break; } } }
[ "private", "void", "evaluateTag", "(", "StringBuilder", "buf", ")", "{", "// Trim the '{' and '}' bounding characters.", "tag", ".", "pos", "++", ";", "tag", ".", "end", "--", ";", "// If this tag has been hidden from the processor, skip over the '-' and", "// emit the tag bo...
Parse and evaluate a tag.
[ "Parse", "and", "evaluate", "a", "tag", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L320-L390
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalPlural
private void evalPlural(MessageArg arg, boolean cardinal) { tag.skip(COMMA_WS); if (!arg.resolve()) { return; } String value = arg.asString(); String offsetValue = value; // Look for optional "offset:<number>" argument. This modifies the argument value, // changing the plural operands calculation. long offset = 0; if (tag.seek(PLURAL_OFFSET, choice)) { tag.jump(choice); tag.skip(COMMA_WS); // Parse the offset digits and the argument value. offset = toLong(format, choice.pos + 7, choice.end); long newValue = toLong(value, 0, value.length()) - offset; // Operands are evaluated based on the offset-adjusted value. offsetValue = Long.toString(newValue); operands.set(offsetValue); } else { operands.set(value); } // Evaluate the plural operands for the current argument. String language = locale.language(); PluralCategory category = cardinal ? PLURAL_RULES.evalCardinal(language, operands) : PLURAL_RULES.evalOrdinal(language, operands); Recognizer matcher = PLURAL_MATCHERS[category.ordinal()]; // Scan over the potential choices inside this tag. We will evaluate // the first choice that matches our plural category. char ch; while ((ch = tag.peek()) != Chars.EOF) { // First look for explicit match, falling back to a plural category. if (ch == '=' && tag.seek(PLURAL_EXPLICIT, choice)) { tag.jump(choice); // Skip the '=' character. choice.pos++; // If our argument matches the exact value, recurse and then return. String repr = choice.token().toString(); if (repr.equals(value) && tag.seekBounds(choice, '{', '}')) { recurse(choice, offsetValue); return; } } else if (tag.seek(matcher, choice)) { // Jump over the plural category. tag.jump(choice); tag.skipWs(); // If the choice format is valid, recurse and then return. if (tag.peek() == '{' && tag.seekBounds(choice, '{', '}')) { recurse(choice, offsetValue); } return; } // Skip over this choice and any trailing whitespace, or bail out if no match. if (!tag.seekBounds(choice, '{', '}')) { return; } tag.jump(choice); tag.skip(COMMA_WS); } }
java
private void evalPlural(MessageArg arg, boolean cardinal) { tag.skip(COMMA_WS); if (!arg.resolve()) { return; } String value = arg.asString(); String offsetValue = value; // Look for optional "offset:<number>" argument. This modifies the argument value, // changing the plural operands calculation. long offset = 0; if (tag.seek(PLURAL_OFFSET, choice)) { tag.jump(choice); tag.skip(COMMA_WS); // Parse the offset digits and the argument value. offset = toLong(format, choice.pos + 7, choice.end); long newValue = toLong(value, 0, value.length()) - offset; // Operands are evaluated based on the offset-adjusted value. offsetValue = Long.toString(newValue); operands.set(offsetValue); } else { operands.set(value); } // Evaluate the plural operands for the current argument. String language = locale.language(); PluralCategory category = cardinal ? PLURAL_RULES.evalCardinal(language, operands) : PLURAL_RULES.evalOrdinal(language, operands); Recognizer matcher = PLURAL_MATCHERS[category.ordinal()]; // Scan over the potential choices inside this tag. We will evaluate // the first choice that matches our plural category. char ch; while ((ch = tag.peek()) != Chars.EOF) { // First look for explicit match, falling back to a plural category. if (ch == '=' && tag.seek(PLURAL_EXPLICIT, choice)) { tag.jump(choice); // Skip the '=' character. choice.pos++; // If our argument matches the exact value, recurse and then return. String repr = choice.token().toString(); if (repr.equals(value) && tag.seekBounds(choice, '{', '}')) { recurse(choice, offsetValue); return; } } else if (tag.seek(matcher, choice)) { // Jump over the plural category. tag.jump(choice); tag.skipWs(); // If the choice format is valid, recurse and then return. if (tag.peek() == '{' && tag.seekBounds(choice, '{', '}')) { recurse(choice, offsetValue); } return; } // Skip over this choice and any trailing whitespace, or bail out if no match. if (!tag.seekBounds(choice, '{', '}')) { return; } tag.jump(choice); tag.skip(COMMA_WS); } }
[ "private", "void", "evalPlural", "(", "MessageArg", "arg", ",", "boolean", "cardinal", ")", "{", "tag", ".", "skip", "(", "COMMA_WS", ")", ";", "if", "(", "!", "arg", ".", "resolve", "(", ")", ")", "{", "return", ";", "}", "String", "value", "=", "...
PLURAL - Evaluate the argument as a plural, either cardinal or ordinal.
[ "PLURAL", "-", "Evaluate", "the", "argument", "as", "a", "plural", "either", "cardinal", "or", "ordinal", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L430-L502
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalSelect
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(COMMA_WS); if (!tag.seekBounds(choice, '{', '}')) { break; } if (token.equals(value)) { recurse(choice, value); return; } else if (token.equals("other")) { pos = choice.pos; end = choice.end; } else { tag.jump(choice); tag.skip(COMMA_WS); } } // Evaluate the "other" tag if nothing matched. if (pos != -1 && end != -1) { choice.set(pos, end); recurse(choice, value); } }
java
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(COMMA_WS); if (!tag.seekBounds(choice, '{', '}')) { break; } if (token.equals(value)) { recurse(choice, value); return; } else if (token.equals("other")) { pos = choice.pos; end = choice.end; } else { tag.jump(choice); tag.skip(COMMA_WS); } } // Evaluate the "other" tag if nothing matched. if (pos != -1 && end != -1) { choice.set(pos, end); recurse(choice, value); } }
[ "private", "void", "evalSelect", "(", "MessageArg", "arg", ")", "{", "tag", ".", "skip", "(", "COMMA_WS", ")", ";", "int", "pos", "=", "-", "1", ";", "int", "end", "=", "-", "1", ";", "String", "value", "=", "arg", ".", "asString", "(", ")", ";",...
SELECT - Evaluate the tag that matches the argument's value.
[ "SELECT", "-", "Evaluate", "the", "tag", "that", "matches", "the", "argument", "s", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L507-L541
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalNumber
private void evalNumber(MessageArg arg) { initDecimalArgsParser(); parseArgs(decimalArgsParser); BigDecimal number = arg.asBigDecimal(); NumberFormatter formatter = CLDR_INSTANCE.getNumberFormatter(locale); formatter.formatDecimal(number, buf, decimalArgsParser.options()); }
java
private void evalNumber(MessageArg arg) { initDecimalArgsParser(); parseArgs(decimalArgsParser); BigDecimal number = arg.asBigDecimal(); NumberFormatter formatter = CLDR_INSTANCE.getNumberFormatter(locale); formatter.formatDecimal(number, buf, decimalArgsParser.options()); }
[ "private", "void", "evalNumber", "(", "MessageArg", "arg", ")", "{", "initDecimalArgsParser", "(", ")", ";", "parseArgs", "(", "decimalArgsParser", ")", ";", "BigDecimal", "number", "=", "arg", ".", "asBigDecimal", "(", ")", ";", "NumberFormatter", "formatter", ...
NUMBER - Evaluate the argument as a number, with options specified as key=value.
[ "NUMBER", "-", "Evaluate", "the", "argument", "as", "a", "number", "with", "options", "specified", "as", "key", "=", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L546-L553
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalCurrency
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 number = arg.asBigDecimal(); NumberFormatter formatter = CLDR_INSTANCE.getNumberFormatter(locale); formatter.formatCurrency(number, currency, buf, currencyArgsParser.options()); }
java
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 number = arg.asBigDecimal(); NumberFormatter formatter = CLDR_INSTANCE.getNumberFormatter(locale); formatter.formatCurrency(number, currency, buf, currencyArgsParser.options()); }
[ "private", "void", "evalCurrency", "(", "MessageArg", "arg", ")", "{", "String", "currencyCode", "=", "arg", ".", "currency", "(", ")", ";", "if", "(", "currencyCode", "==", "null", ")", "{", "return", ";", "}", "CLDR", ".", "Currency", "currency", "=", ...
CURRENCY - Evaluate the argument as a currency, with options specified as key=value.
[ "CURRENCY", "-", "Evaluate", "the", "argument", "as", "a", "currency", "with", "options", "specified", "as", "key", "=", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L558-L574
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalDateTime
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, calendarArgsParser.options(), buf); }
java
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, calendarArgsParser.options(), buf); }
[ "private", "void", "evalDateTime", "(", "MessageArg", "arg", ")", "{", "if", "(", "!", "arg", ".", "resolve", "(", ")", ")", "{", "return", ";", "}", "initCalendarArgsParser", "(", ")", ";", "parseArgs", "(", "calendarArgsParser", ")", ";", "ZonedDateTime"...
DATETIME - Evaluate the argument as a datetime, with options specified as key=value.
[ "DATETIME", "-", "Evaluate", "the", "argument", "as", "a", "datetime", "with", "options", "specified", "as", "key", "=", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L579-L590
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.evalDateTimeInterval
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.get(1)); // Parse optional skeleton argument DateTimeIntervalSkeleton skeleton = null; tag.skip(COMMA_WS); if (tag.seek(SKELETON, choice)) { String skel = choice.toString(); tag.jump(choice); skeleton = DateTimeIntervalSkeleton.fromString(skel); } CalendarFormatter formatter = CLDR_INSTANCE.getCalendarFormatter(locale); formatter.format(start, end, skeleton, buf); }
java
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.get(1)); // Parse optional skeleton argument DateTimeIntervalSkeleton skeleton = null; tag.skip(COMMA_WS); if (tag.seek(SKELETON, choice)) { String skel = choice.toString(); tag.jump(choice); skeleton = DateTimeIntervalSkeleton.fromString(skel); } CalendarFormatter formatter = CLDR_INSTANCE.getCalendarFormatter(locale); formatter.format(start, end, skeleton, buf); }
[ "private", "void", "evalDateTimeInterval", "(", "List", "<", "MessageArg", ">", "args", ")", "{", "int", "size", "=", "args", ".", "size", "(", ")", ";", "if", "(", "size", "!=", "2", ")", "{", "return", ";", "}", "for", "(", "int", "i", "=", "0"...
DATETIME-INTERVAL - Evaluate the argument as a date-time interval with an optional skeleton argument.
[ "DATETIME", "-", "INTERVAL", "-", "Evaluate", "the", "argument", "as", "a", "date", "-", "time", "interval", "with", "an", "optional", "skeleton", "argument", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L596-L621
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.parseDateTime
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); }
java
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); }
[ "private", "ZonedDateTime", "parseDateTime", "(", "MessageArg", "arg", ")", "{", "long", "instant", "=", "arg", ".", "asLong", "(", ")", ";", "ZoneId", "timeZone", "=", "arg", ".", "timeZone", "(", ")", "!=", "null", "?", "arg", ".", "timeZone", "(", "...
Parse the argument as a date-time with the format-wide time zone.
[ "Parse", "the", "argument", "as", "a", "date", "-", "time", "with", "the", "format", "-", "wide", "time", "zone", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L739-L743
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageFormat.java
MessageFormat.emit
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++; } }
java
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++; } }
[ "private", "void", "emit", "(", "int", "pos", ",", "int", "end", ",", "String", "arg", ")", "{", "while", "(", "pos", "<", "end", ")", "{", "char", "ch", "=", "format", ".", "charAt", "(", "pos", ")", ";", "if", "(", "ch", "==", "'", "'", ")"...
Append characters from 'raw' in the range [pos, end) to the output buffer.
[ "Append", "characters", "from", "raw", "in", "the", "range", "[", "pos", "end", ")", "to", "the", "output", "buffer", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageFormat.java#L813-L823
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/LazyLoader.java
LazyLoader.get
public V get(K key) { Entry<V> entry = classMap.get(key); return entry == null ? null : entry.get(); }
java
public V get(K key) { Entry<V> entry = classMap.get(key); return entry == null ? null : entry.get(); }
[ "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.
[ "Gets", "a", "new", "instance", "of", "the", "class", "corresponding", "to", "the", "key", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LazyLoader.java#L18-L21
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/LazyLoader.java
LazyLoader.put
public void put(K key, Class<? extends V> cls) { classMap.put(key, new Entry<>(cls)); }
java
public void put(K key, Class<? extends V> cls) { classMap.put(key, new Entry<>(cls)); }
[ "public", "void", "put", "(", "K", "key", ",", "Class", "<", "?", "extends", "V", ">", "cls", ")", "{", "classMap", ".", "put", "(", "key", ",", "new", "Entry", "<>", "(", "cls", ")", ")", ";", "}" ]
Puts a class into the map.
[ "Puts", "a", "class", "into", "the", "map", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LazyLoader.java#L26-L28
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java
LanguageResolver.addLikelySubtags
protected MetaLocale addLikelySubtags(MetaLocale src) { // Always return a copy. MetaLocale dst = src.copy(); // If the locale has all fields populated (language, script, territory) // then do nothing. if (src.hasAll()) { return dst; } // Build a temporary locale for matching and clear the variant since it // is not used for likely subtags. MetaLocale temp = src.copy(); temp.setVariant(null); // Iterate over the match flags, from most specific to least. for (int flags : MATCH_ORDER) { set(src, temp, flags); MetaLocale match = likelySubtagsMap.get(temp); if (match != null) { // Use the first match we find. We only replace subtags that // are undefined, copying them from the matched locale. if (!dst.hasLanguage()) { dst.setLanguage(match._language()); } if (!dst.hasScript()) { dst.setScript(match._script()); } if (!dst.hasTerritory()) { dst.setTerritory(match._territory()); } break; } } return dst; }
java
protected MetaLocale addLikelySubtags(MetaLocale src) { // Always return a copy. MetaLocale dst = src.copy(); // If the locale has all fields populated (language, script, territory) // then do nothing. if (src.hasAll()) { return dst; } // Build a temporary locale for matching and clear the variant since it // is not used for likely subtags. MetaLocale temp = src.copy(); temp.setVariant(null); // Iterate over the match flags, from most specific to least. for (int flags : MATCH_ORDER) { set(src, temp, flags); MetaLocale match = likelySubtagsMap.get(temp); if (match != null) { // Use the first match we find. We only replace subtags that // are undefined, copying them from the matched locale. if (!dst.hasLanguage()) { dst.setLanguage(match._language()); } if (!dst.hasScript()) { dst.setScript(match._script()); } if (!dst.hasTerritory()) { dst.setTerritory(match._territory()); } break; } } return dst; }
[ "protected", "MetaLocale", "addLikelySubtags", "(", "MetaLocale", "src", ")", "{", "// Always return a copy.", "MetaLocale", "dst", "=", "src", ".", "copy", "(", ")", ";", "// If the locale has all fields populated (language, script, territory)", "// then do nothing.", "if", ...
Add likely subtags, producing the max bundle ID.
[ "Add", "likely", "subtags", "producing", "the", "max", "bundle", "ID", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java#L53-L89
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java
LanguageResolver.removeLikelySubtags
protected MetaLocale removeLikelySubtags(MetaLocale src) { // Using "en-Latn-US" for examples. // 1. match "en-Zzzz-ZZ" MetaLocale temp = new MetaLocale(); temp.setLanguage(src._language()); MetaLocale match = addLikelySubtags(temp); if (match.equals(src)) { return temp; } // 2. match "en-Zzzz-US" temp.setTerritory(src._territory()); match = addLikelySubtags(temp); if (match.equals(src)) { temp.setLanguage(src._language()); return temp; } // 3. match "en-Latn-ZZ" temp.setTerritory(null); temp.setScript(temp._script()); match = addLikelySubtags(temp); if (match.equals(src)) { return temp; } // 4. Nothing matched, return a copy of the original. return src.copy(); }
java
protected MetaLocale removeLikelySubtags(MetaLocale src) { // Using "en-Latn-US" for examples. // 1. match "en-Zzzz-ZZ" MetaLocale temp = new MetaLocale(); temp.setLanguage(src._language()); MetaLocale match = addLikelySubtags(temp); if (match.equals(src)) { return temp; } // 2. match "en-Zzzz-US" temp.setTerritory(src._territory()); match = addLikelySubtags(temp); if (match.equals(src)) { temp.setLanguage(src._language()); return temp; } // 3. match "en-Latn-ZZ" temp.setTerritory(null); temp.setScript(temp._script()); match = addLikelySubtags(temp); if (match.equals(src)) { return temp; } // 4. Nothing matched, return a copy of the original. return src.copy(); }
[ "protected", "MetaLocale", "removeLikelySubtags", "(", "MetaLocale", "src", ")", "{", "// Using \"en-Latn-US\" for examples.", "// 1. match \"en-Zzzz-ZZ\"", "MetaLocale", "temp", "=", "new", "MetaLocale", "(", ")", ";", "temp", ".", "setLanguage", "(", "src", ".", "_l...
Removes all subtags that would be added by addLikelySubtags. This produces the min bundle ID.
[ "Removes", "all", "subtags", "that", "would", "be", "added", "by", "addLikelySubtags", ".", "This", "produces", "the", "min", "bundle", "ID", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java#L95-L124
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java
LanguageResolver.set
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()); }
java
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()); }
[ "protected", "static", "void", "set", "(", "MetaLocale", "src", ",", "MetaLocale", "dst", ",", "int", "flags", ")", "{", "dst", ".", "setLanguage", "(", "(", "flags", "&", "LANGUAGE", ")", "==", "0", "?", "null", ":", "src", ".", "_language", "(", ")...
Set or clear fields on the destination locale according to the flags.
[ "Set", "or", "clear", "fields", "on", "the", "destination", "locale", "according", "to", "the", "flags", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageResolver.java#L129-L133
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/PartitionTable.java
PartitionTable.getPartition
private String getPartition(Set<String> variables) { String key = buildKey(variables); return partitionIds.computeIfAbsent(key, k -> Character.toString((char)(BASE_ID + idSequence++))); }
java
private String getPartition(Set<String> variables) { String key = buildKey(variables); return partitionIds.computeIfAbsent(key, k -> Character.toString((char)(BASE_ID + idSequence++))); }
[ "private", "String", "getPartition", "(", "Set", "<", "String", ">", "variables", ")", "{", "String", "key", "=", "buildKey", "(", "variables", ")", ";", "return", "partitionIds", ".", "computeIfAbsent", "(", "key", ",", "k", "->", "Character", ".", "toStr...
Retrieve the partition identifier for this set of matching variables.
[ "Retrieve", "the", "partition", "identifier", "for", "this", "set", "of", "matching", "variables", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/PartitionTable.java#L144-L147
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/PartitionTable.java
PartitionTable.buildKey
private static String buildKey(Set<String> variables) { return variables.stream().sorted().collect(Collectors.joining(", ")); }
java
private static String buildKey(Set<String> variables) { return variables.stream().sorted().collect(Collectors.joining(", ")); }
[ "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.
[ "Sort", "the", "set", "of", "variables", "and", "join", "to", "a", "comma", "-", "delimited", "string", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/PartitionTable.java#L152-L154
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/PartitionTable.java
PartitionTable.makeSetsImmutable
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)); } }
java
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)); } }
[ "private", "static", "<", "K", ",", "V", ">", "void", "makeSetsImmutable", "(", "Map", "<", "K", ",", "Set", "<", "V", ">", ">", "map", ")", "{", "Set", "<", "K", ">", "keys", "=", "map", ".", "keySet", "(", ")", ";", "for", "(", "K", "key", ...
Convert values to immutable sets.
[ "Convert", "values", "to", "immutable", "sets", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/PartitionTable.java#L175-L181
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java
BaseUnitConverter.convert
@Override public UnitValue convert(UnitValue value) { Unit src = value.unit(); switch (src.category()) { case CONCENTR: case LIGHT: // Not available break; case ACCELERATION: return convert(value, Unit.METER_PER_SECOND_SQUARED, UnitFactors.ACCELERATION); case ANGLE: return convert(value, UnitFactorSets.ANGLE); case AREA: return convert(value, areaFactors()); case CONSUMPTION: return convert(value, consumptionUnit()); case DIGITAL: return convert(value, UnitFactorSets.DIGITAL_BYTES); case DURATION: return convert(value, UnitFactorSets.DURATION); case ELECTRIC: return convert(value, UnitFactorSets.ELECTRIC); case ENERGY: return convert(value, energyFactors()); case FREQUENCY: return convert(value, UnitFactorSets.FREQUENCY); case LENGTH: return convert(value, lengthFactors()); case MASS: return convert(value, massFactors()); case POWER: return convert(value, UnitFactorSets.POWER); case PRESSURE: return convert(value, Unit.MILLIBAR); case SPEED: return convert(value, speedUnit()); case TEMPERATURE: return convert(value, temperatureUnit()); case VOLUME: return convert(value, volumeFactors()); } return value; }
java
@Override public UnitValue convert(UnitValue value) { Unit src = value.unit(); switch (src.category()) { case CONCENTR: case LIGHT: // Not available break; case ACCELERATION: return convert(value, Unit.METER_PER_SECOND_SQUARED, UnitFactors.ACCELERATION); case ANGLE: return convert(value, UnitFactorSets.ANGLE); case AREA: return convert(value, areaFactors()); case CONSUMPTION: return convert(value, consumptionUnit()); case DIGITAL: return convert(value, UnitFactorSets.DIGITAL_BYTES); case DURATION: return convert(value, UnitFactorSets.DURATION); case ELECTRIC: return convert(value, UnitFactorSets.ELECTRIC); case ENERGY: return convert(value, energyFactors()); case FREQUENCY: return convert(value, UnitFactorSets.FREQUENCY); case LENGTH: return convert(value, lengthFactors()); case MASS: return convert(value, massFactors()); case POWER: return convert(value, UnitFactorSets.POWER); case PRESSURE: return convert(value, Unit.MILLIBAR); case SPEED: return convert(value, speedUnit()); case TEMPERATURE: return convert(value, temperatureUnit()); case VOLUME: return convert(value, volumeFactors()); } return value; }
[ "@", "Override", "public", "UnitValue", "convert", "(", "UnitValue", "value", ")", "{", "Unit", "src", "=", "value", ".", "unit", "(", ")", ";", "switch", "(", "src", ".", "category", "(", ")", ")", "{", "case", "CONCENTR", ":", "case", "LIGHT", ":",...
Convert the given unit value into the best unit for its category relative to the current measurement system.
[ "Convert", "the", "given", "unit", "value", "into", "the", "best", "unit", "for", "its", "category", "relative", "to", "the", "current", "measurement", "system", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java#L54-L98
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java
BaseUnitConverter.convert
@Override 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: // Not available break; case CONSUMPTION: return consumption(value, target); case TEMPERATURE: return temperature(value, target); case VOLUME: if (measurementSystem == MeasurementSystem.UK) { return convert(value, target, UnitFactors.VOLUME_UK); } return convert(value, target, UnitFactors.VOLUME); default: UnitFactorMap factors = FACTORS_MAP.get(category); if (factors != null) { return convert(value, target, factors); } break; } return value; }
java
@Override 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: // Not available break; case CONSUMPTION: return consumption(value, target); case TEMPERATURE: return temperature(value, target); case VOLUME: if (measurementSystem == MeasurementSystem.UK) { return convert(value, target, UnitFactors.VOLUME_UK); } return convert(value, target, UnitFactors.VOLUME); default: UnitFactorMap factors = FACTORS_MAP.get(category); if (factors != null) { return convert(value, target, factors); } break; } return value; }
[ "@", "Override", "public", "UnitValue", "convert", "(", "UnitValue", "value", ",", "Unit", "target", ")", "{", "Unit", "src", "=", "value", ".", "unit", "(", ")", ";", "UnitCategory", "category", "=", "src", ".", "category", "(", ")", ";", "if", "(", ...
Convert the given unit value into the target unit relative to the current measurement system.
[ "Convert", "the", "given", "unit", "value", "into", "the", "target", "unit", "relative", "to", "the", "current", "measurement", "system", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java#L104-L139
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java
BaseUnitConverter.convert
public UnitValue convert(UnitValue value, UnitFactorSet factorSet) { value = convert(value, factorSet.base()); BigDecimal n = value.amount(); // Use absolute value to simplify comparisons with divisors boolean negative = false; if (n.signum() == -1) { negative = true; n = n.abs(); } List<UnitValue> factors = factorSet.factors(); int size = factors.size(); int last = size - 1; for (int i = 0; i < size; i++) { UnitValue factor = factors.get(i); BigDecimal divisor = factor.amount(); if (divisor == null) { continue; } // Use this divisor if it is <= the number or if we've run out of // factors to try. if (divisor.compareTo(n) <= 0 || i == last) { int scale = n.precision() + divisor.precision(); n = n.divide(divisor, scale, RoundingMode.HALF_EVEN); if (negative) { n = n.negate(); } return new UnitValue(n.stripTrailingZeros(), factor.unit()); } } // Should only be reached if list of factors is empty. return value; }
java
public UnitValue convert(UnitValue value, UnitFactorSet factorSet) { value = convert(value, factorSet.base()); BigDecimal n = value.amount(); // Use absolute value to simplify comparisons with divisors boolean negative = false; if (n.signum() == -1) { negative = true; n = n.abs(); } List<UnitValue> factors = factorSet.factors(); int size = factors.size(); int last = size - 1; for (int i = 0; i < size; i++) { UnitValue factor = factors.get(i); BigDecimal divisor = factor.amount(); if (divisor == null) { continue; } // Use this divisor if it is <= the number or if we've run out of // factors to try. if (divisor.compareTo(n) <= 0 || i == last) { int scale = n.precision() + divisor.precision(); n = n.divide(divisor, scale, RoundingMode.HALF_EVEN); if (negative) { n = n.negate(); } return new UnitValue(n.stripTrailingZeros(), factor.unit()); } } // Should only be reached if list of factors is empty. return value; }
[ "public", "UnitValue", "convert", "(", "UnitValue", "value", ",", "UnitFactorSet", "factorSet", ")", "{", "value", "=", "convert", "(", "value", ",", "factorSet", ".", "base", "(", ")", ")", ";", "BigDecimal", "n", "=", "value", ".", "amount", "(", ")", ...
Convert to the best display unit among the available factors. By "best" we mean the most compact representation.
[ "Convert", "to", "the", "best", "display", "unit", "among", "the", "available", "factors", ".", "By", "best", "we", "mean", "the", "most", "compact", "representation", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java#L166-L201
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java
BaseUnitConverter.sequence
public List<UnitValue> sequence(UnitValue value, UnitFactorSet factorSet) { value = convert(value, factorSet.base()); boolean negative = false; BigDecimal n = value.amount(); // Use absolute value for all comparisons. if (n.signum() == -1) { negative = true; n = n.abs(); } List<UnitValue> result = new ArrayList<>(); List<UnitValue> factors = factorSet.factors(); int size = factors.size(); int last = size - 1; for (int i = 0; i < size; i++) { UnitValue factor = factors.get(i); BigDecimal divisor = factor.amount(); if (divisor == null) { continue; } if (i == last && (n.compareTo(BigDecimal.ZERO) != 0 || result.isEmpty())) { // Include decimals on the last unit. int scale = n.precision() + divisor.precision(); BigDecimal res = n.divide(divisor, scale, RoundingMode.HALF_EVEN); if (negative && result.isEmpty()) { res = res.negate(); } result.add(new UnitValue(res.stripTrailingZeros(), factor.unit())); } else if (divisor.compareTo(n) <= 0) { BigDecimal[] res = n.divideAndRemainder(divisor); if (negative && result.isEmpty()) { res[0] = res[0].negate(); } result.add(new UnitValue(res[0].stripTrailingZeros(), factor.unit())); n = res[1]; } } return result; }
java
public List<UnitValue> sequence(UnitValue value, UnitFactorSet factorSet) { value = convert(value, factorSet.base()); boolean negative = false; BigDecimal n = value.amount(); // Use absolute value for all comparisons. if (n.signum() == -1) { negative = true; n = n.abs(); } List<UnitValue> result = new ArrayList<>(); List<UnitValue> factors = factorSet.factors(); int size = factors.size(); int last = size - 1; for (int i = 0; i < size; i++) { UnitValue factor = factors.get(i); BigDecimal divisor = factor.amount(); if (divisor == null) { continue; } if (i == last && (n.compareTo(BigDecimal.ZERO) != 0 || result.isEmpty())) { // Include decimals on the last unit. int scale = n.precision() + divisor.precision(); BigDecimal res = n.divide(divisor, scale, RoundingMode.HALF_EVEN); if (negative && result.isEmpty()) { res = res.negate(); } result.add(new UnitValue(res.stripTrailingZeros(), factor.unit())); } else if (divisor.compareTo(n) <= 0) { BigDecimal[] res = n.divideAndRemainder(divisor); if (negative && result.isEmpty()) { res[0] = res[0].negate(); } result.add(new UnitValue(res[0].stripTrailingZeros(), factor.unit())); n = res[1]; } } return result; }
[ "public", "List", "<", "UnitValue", ">", "sequence", "(", "UnitValue", "value", ",", "UnitFactorSet", "factorSet", ")", "{", "value", "=", "convert", "(", "value", ",", "factorSet", ".", "base", "(", ")", ")", ";", "boolean", "negative", "=", "false", ";...
Breaks down the unit value into a sequence of units, using the given divisors and allowed units.
[ "Breaks", "down", "the", "unit", "value", "into", "a", "sequence", "of", "units", "using", "the", "given", "divisors", "and", "allowed", "units", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java#L207-L250
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java
BaseUnitConverter.temperature
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(THIRTY_TWO); n = new Rational(n, BigDecimal.ONE).multiply(FIVE_NINTHS).compute(RoundingMode.HALF_EVEN); } else if (target == Unit.KELVIN) { n = n.add(KELVIN_FAHRENHEIT); n = new Rational(n, BigDecimal.ONE).multiply(FIVE_NINTHS).compute(RoundingMode.HALF_EVEN); } break; case CELSIUS: if (target == Unit.FAHRENHEIT) { Rational r = new Rational(n, BigDecimal.ONE); n = r.multiply(NINE_FIFTHS).compute(RoundingMode.HALF_EVEN).add(THIRTY_TWO); } else if (target == Unit.KELVIN) { n = n.add(KELVIN_CELSIUS); } break; case KELVIN: if (target == Unit.CELSIUS) { n = n.subtract(KELVIN_CELSIUS); } else if (target == Unit.FAHRENHEIT) { Rational r = new Rational(n, BigDecimal.ONE).multiply(NINE_FIFTHS); n = r.compute(RoundingMode.HALF_EVEN).subtract(KELVIN_FAHRENHEIT); } break; default: return new UnitValue(n, Unit.TEMPERATURE_GENERIC); } return new UnitValue(n.stripTrailingZeros(), target); }
java
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(THIRTY_TWO); n = new Rational(n, BigDecimal.ONE).multiply(FIVE_NINTHS).compute(RoundingMode.HALF_EVEN); } else if (target == Unit.KELVIN) { n = n.add(KELVIN_FAHRENHEIT); n = new Rational(n, BigDecimal.ONE).multiply(FIVE_NINTHS).compute(RoundingMode.HALF_EVEN); } break; case CELSIUS: if (target == Unit.FAHRENHEIT) { Rational r = new Rational(n, BigDecimal.ONE); n = r.multiply(NINE_FIFTHS).compute(RoundingMode.HALF_EVEN).add(THIRTY_TWO); } else if (target == Unit.KELVIN) { n = n.add(KELVIN_CELSIUS); } break; case KELVIN: if (target == Unit.CELSIUS) { n = n.subtract(KELVIN_CELSIUS); } else if (target == Unit.FAHRENHEIT) { Rational r = new Rational(n, BigDecimal.ONE).multiply(NINE_FIFTHS); n = r.compute(RoundingMode.HALF_EVEN).subtract(KELVIN_FAHRENHEIT); } break; default: return new UnitValue(n, Unit.TEMPERATURE_GENERIC); } return new UnitValue(n.stripTrailingZeros(), target); }
[ "private", "static", "UnitValue", "temperature", "(", "UnitValue", "value", ",", "Unit", "target", ")", "{", "BigDecimal", "n", "=", "value", ".", "amount", "(", ")", ";", "if", "(", "target", "==", "Unit", ".", "TEMPERATURE_GENERIC", ")", "{", "return", ...
Temperature conversions.
[ "Temperature", "conversions", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/units/BaseUnitConverter.java#L403-L443
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageArgs.java
MessageArgs.get
public MessageArg get(int index) { return index < args.size() ? args.get(index) : null; }
java
public MessageArg get(int index) { return index < args.size() ? args.get(index) : null; }
[ "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.
[ "Return", "a", "positional", "argument", "using", "a", "zero", "-", "based", "index", "or", "null", "if", "not", "enough", "arguments", "exist", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgs.java#L21-L23
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageArgs.java
MessageArgs.get
public MessageArg get(String name) { return map == null ? null : map.get(name); }
java
public MessageArg get(String name) { return map == null ? null : map.get(name); }
[ "public", "MessageArg", "get", "(", "String", "name", ")", "{", "return", "map", "==", "null", "?", "null", ":", "map", ".", "get", "(", "name", ")", ";", "}" ]
Return a named argument or null if does not exist.
[ "Return", "a", "named", "argument", "or", "null", "if", "does", "not", "exist", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgs.java#L28-L30
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageArgs.java
MessageArgs.add
public void add(String name, MessageArg arg) { args.add(arg); if (map == null) { map = new HashMap<>(); } map.put(name, arg); }
java
public void add(String name, MessageArg arg) { args.add(arg); if (map == null) { map = new HashMap<>(); } map.put(name, arg); }
[ "public", "void", "add", "(", "String", "name", ",", "MessageArg", "arg", ")", "{", "args", ".", "add", "(", "arg", ")", ";", "if", "(", "map", "==", "null", ")", "{", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "map", ".", "put", ...
Add a named argument. Also accessible by index.
[ "Add", "a", "named", "argument", ".", "Also", "accessible", "by", "index", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgs.java#L42-L48
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.generate
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()) { NumberData data = entry.getValue(); LocaleID localeId = entry.getKey(); String className = "_NumberFormatter_" + localeId.safe; UnitData unitData = unitMap.get(localeId); TypeSpec type = create(data, unitData, className); CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_NUMBERS, className, type); ClassName cls = ClassName.get(PACKAGE_CLDR_NUMBERS, className); numberClasses.put(localeId, cls); } // generate currency digit utility class String className = "_CurrencyUtil"; TypeSpec type = createCurrencyUtil(className, reader.currencies()); CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_NUMBERS, className, type); return numberClasses; }
java
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()) { NumberData data = entry.getValue(); LocaleID localeId = entry.getKey(); String className = "_NumberFormatter_" + localeId.safe; UnitData unitData = unitMap.get(localeId); TypeSpec type = create(data, unitData, className); CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_NUMBERS, className, type); ClassName cls = ClassName.get(PACKAGE_CLDR_NUMBERS, className); numberClasses.put(localeId, cls); } // generate currency digit utility class String className = "_CurrencyUtil"; TypeSpec type = createCurrencyUtil(className, reader.currencies()); CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_NUMBERS, className, type); return numberClasses; }
[ "public", "Map", "<", "LocaleID", ",", "ClassName", ">", "generate", "(", "Path", "outputDir", ",", "DataReader", "reader", ")", "throws", "IOException", "{", "Map", "<", "LocaleID", ",", "ClassName", ">", "numberClasses", "=", "new", "TreeMap", "<>", "(", ...
Generate all number formatting classes.
[ "Generate", "all", "number", "formatting", "classes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L70-L94
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.create
private TypeSpec create(NumberData data, UnitData unitData, String className) { LocaleID id = data.id(); // TODO: add descriptive javadoc to type TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(NUMBER_FORMATTER_BASE) .addModifiers(Modifier.PUBLIC); // Build the constructor's code block String fmt = "super(\n"; List<Object> args = new ArrayList<>(); fmt += "$T.$L,\n"; args.add(CLDR_LOCALE_IF); args.add(id.safe); fmt += "new _Params(),\n"; fmt += "// decimal standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.decimalFormatStandard)); fmt += "// percent standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.percentFormatStandard)); fmt += "// currency standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.currencyFormatStandard)); fmt += "// currency accounting\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.currencyFormatAccounting)); fmt += "// units standard\n"; fmt += "patterns($S, $S)\n"; List<NumberPattern> unitPatterns = data.decimalFormatStandard.stream() .map(p -> { p = NUMBER_PARSER.parse(p.render()); p.format().setMaximumFractionDigits(1); p.format().setMinimumFractionDigits(0); return p; }).collect(Collectors.toList()); args.addAll(getPatterns(unitPatterns)); fmt += ")"; // Build the constructor. MethodSpec.Builder code = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addStatement(fmt, args.toArray()); type.addMethod(code.build()); // Create a private instance of the NumberFormatterParams type addParams(type, id, data); addCompactPattern(type, "DECIMAL_SHORT", data.decimalFormatShort, false, data); addCompactPattern(type, "DECIMAL_LONG", data.decimalFormatLong, false, data); addCompactPattern(type, "CURRENCY_SHORT", data.currencyFormatShort, true, data); addUnitPattern(type, "UNITS_LONG", unitData.long_); addUnitPattern(type, "UNITS_NARROW", unitData.narrow); addUnitPattern(type, "UNITS_SHORT", unitData.short_); addCurrencyInfo(type, data); addUnitWrappers(type, data); return type.build(); }
java
private TypeSpec create(NumberData data, UnitData unitData, String className) { LocaleID id = data.id(); // TODO: add descriptive javadoc to type TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(NUMBER_FORMATTER_BASE) .addModifiers(Modifier.PUBLIC); // Build the constructor's code block String fmt = "super(\n"; List<Object> args = new ArrayList<>(); fmt += "$T.$L,\n"; args.add(CLDR_LOCALE_IF); args.add(id.safe); fmt += "new _Params(),\n"; fmt += "// decimal standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.decimalFormatStandard)); fmt += "// percent standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.percentFormatStandard)); fmt += "// currency standard\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.currencyFormatStandard)); fmt += "// currency accounting\n"; fmt += "patterns($S, $S),\n"; args.addAll(getPatterns(data.currencyFormatAccounting)); fmt += "// units standard\n"; fmt += "patterns($S, $S)\n"; List<NumberPattern> unitPatterns = data.decimalFormatStandard.stream() .map(p -> { p = NUMBER_PARSER.parse(p.render()); p.format().setMaximumFractionDigits(1); p.format().setMinimumFractionDigits(0); return p; }).collect(Collectors.toList()); args.addAll(getPatterns(unitPatterns)); fmt += ")"; // Build the constructor. MethodSpec.Builder code = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addStatement(fmt, args.toArray()); type.addMethod(code.build()); // Create a private instance of the NumberFormatterParams type addParams(type, id, data); addCompactPattern(type, "DECIMAL_SHORT", data.decimalFormatShort, false, data); addCompactPattern(type, "DECIMAL_LONG", data.decimalFormatLong, false, data); addCompactPattern(type, "CURRENCY_SHORT", data.currencyFormatShort, true, data); addUnitPattern(type, "UNITS_LONG", unitData.long_); addUnitPattern(type, "UNITS_NARROW", unitData.narrow); addUnitPattern(type, "UNITS_SHORT", unitData.short_); addCurrencyInfo(type, data); addUnitWrappers(type, data); return type.build(); }
[ "private", "TypeSpec", "create", "(", "NumberData", "data", ",", "UnitData", "unitData", ",", "String", "className", ")", "{", "LocaleID", "id", "=", "data", ".", "id", "(", ")", ";", "// TODO: add descriptive javadoc to type", "TypeSpec", ".", "Builder", "type"...
Creates a number formatter class.
[ "Creates", "a", "number", "formatter", "class", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L109-L177
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.createCurrencyUtil
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 code = MethodSpec.methodBuilder("getCurrencyDigits") .addModifiers(PUBLIC, STATIC) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .returns(int.class); code.beginControlFlow("switch (code)"); for (Map.Entry<String, CurrencyData> entry : currencies.entrySet()) { CurrencyData data = entry.getValue(); code.addStatement("case $L: return $L", entry.getKey(), data.digits); } code.addStatement("default: return $L", defaultData.digits); code.endControlFlow(); type.addMethod(code.build()); return type.build(); }
java
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 code = MethodSpec.methodBuilder("getCurrencyDigits") .addModifiers(PUBLIC, STATIC) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .returns(int.class); code.beginControlFlow("switch (code)"); for (Map.Entry<String, CurrencyData> entry : currencies.entrySet()) { CurrencyData data = entry.getValue(); code.addStatement("case $L: return $L", entry.getKey(), data.digits); } code.addStatement("default: return $L", defaultData.digits); code.endControlFlow(); type.addMethod(code.build()); return type.build(); }
[ "public", "TypeSpec", "createCurrencyUtil", "(", "String", "className", ",", "Map", "<", "String", ",", "CurrencyData", ">", "currencies", ")", "{", "TypeSpec", ".", "Builder", "type", "=", "TypeSpec", ".", "classBuilder", "(", "className", ")", ".", "addModif...
Create class to hold global currency information.
[ "Create", "class", "to", "hold", "global", "currency", "information", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L182-L204
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.getPatterns
private List<String> getPatterns(List<NumberPattern> patterns) { return patterns.stream() .map(p -> p.render()) .collect(Collectors.toList()); }
java
private List<String> getPatterns(List<NumberPattern> patterns) { return patterns.stream() .map(p -> p.render()) .collect(Collectors.toList()); }
[ "private", "List", "<", "String", ">", "getPatterns", "(", "List", "<", "NumberPattern", ">", "patterns", ")", "{", "return", "patterns", ".", "stream", "(", ")", ".", "map", "(", "p", "->", "p", ".", "render", "(", ")", ")", ".", "collect", "(", "...
Return a list of the string patterns embedded in the NumberPattern instances.
[ "Return", "a", "list", "of", "the", "string", "patterns", "embedded", "in", "the", "NumberPattern", "instances", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L209-L213
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.addParams
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", data.percent); code.addStatement("this.minus = $S", data.minus); code.addStatement("this.plus = $S", data.plus); code.addStatement("this.exponential = $S", data.exponential); code.addStatement("this.superscriptingExponent = $S", data.superscriptingExponent); code.addStatement("this.perMille = $S", data.perMille); code.addStatement("this.infinity = $S", data.infinity); code.addStatement("this.nan = $S", data.nan); code.addStatement("this.currencyDecimal = $S", data.currencyDecimal); code.addStatement("this.currencyGroup = $S", data.currencyGroup); TypeSpec.Builder params = TypeSpec.classBuilder("_Params") .superclass(NumberFormatterParams.class) .addModifiers(PRIVATE, STATIC) .addMethod(code.build()); parent.addType(params.build()); }
java
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", data.percent); code.addStatement("this.minus = $S", data.minus); code.addStatement("this.plus = $S", data.plus); code.addStatement("this.exponential = $S", data.exponential); code.addStatement("this.superscriptingExponent = $S", data.superscriptingExponent); code.addStatement("this.perMille = $S", data.perMille); code.addStatement("this.infinity = $S", data.infinity); code.addStatement("this.nan = $S", data.nan); code.addStatement("this.currencyDecimal = $S", data.currencyDecimal); code.addStatement("this.currencyGroup = $S", data.currencyGroup); TypeSpec.Builder params = TypeSpec.classBuilder("_Params") .superclass(NumberFormatterParams.class) .addModifiers(PRIVATE, STATIC) .addMethod(code.build()); parent.addType(params.build()); }
[ "private", "void", "addParams", "(", "TypeSpec", ".", "Builder", "parent", ",", "LocaleID", "id", ",", "NumberData", "data", ")", "{", "MethodSpec", ".", "Builder", "code", "=", "MethodSpec", ".", "constructorBuilder", "(", ")", ";", "code", ".", "addStateme...
Construct's the locale's number formatter params.
[ "Construct", "s", "the", "locale", "s", "number", "formatter", "params", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L218-L239
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.addCurrencyInfo
private void addCurrencyInfo(TypeSpec.Builder type, NumberData data) { addCurrencyInfoMethod(type, "getCurrencySymbol", data.currencySymbols); addCurrencyInfoMethod(type, "getNarrowCurrencySymbol", data.narrowCurrencySymbols); addCurrencyInfoMethod(type, "getCurrencyDisplayName", data.currencyDisplayName); MethodSpec.Builder method = MethodSpec.methodBuilder("getCurrencyPluralName") .addModifiers(PROTECTED) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .addParameter(PluralCategory.class, "category") .returns(String.class); method.beginControlFlow("switch (code)"); for (Map.Entry<String, Map<String, String>> currencyMap : data.currencyDisplayNames.entrySet()) { String code = currencyMap.getKey(); Map<String, String> mapping = currencyMap.getValue(); if (mapping.isEmpty()) { continue; } method.beginControlFlow("case $L:", code); method.beginControlFlow("switch (category)"); for (Map.Entry<String, String> entry : mapping.entrySet()) { String[] parts = entry.getKey().split("-"); PluralCategory category = PluralCategory.fromString(parts[2]); if (category == PluralCategory.OTHER) { method.addStatement("case $L:\ndefault: return $S", category, entry.getValue()); } else { method.addStatement("case $L: return $S", category, entry.getValue()); } } method.endControlFlow(); method.endControlFlow(); } method.addStatement("default: return $S", ""); method.endControlFlow(); type.addMethod(method.build()); method = MethodSpec.methodBuilder("getCurrencyDigits") .addModifiers(PUBLIC) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .returns(int.class); method.addStatement("return _CurrencyUtil.getCurrencyDigits(code)"); type.addMethod(method.build()); }
java
private void addCurrencyInfo(TypeSpec.Builder type, NumberData data) { addCurrencyInfoMethod(type, "getCurrencySymbol", data.currencySymbols); addCurrencyInfoMethod(type, "getNarrowCurrencySymbol", data.narrowCurrencySymbols); addCurrencyInfoMethod(type, "getCurrencyDisplayName", data.currencyDisplayName); MethodSpec.Builder method = MethodSpec.methodBuilder("getCurrencyPluralName") .addModifiers(PROTECTED) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .addParameter(PluralCategory.class, "category") .returns(String.class); method.beginControlFlow("switch (code)"); for (Map.Entry<String, Map<String, String>> currencyMap : data.currencyDisplayNames.entrySet()) { String code = currencyMap.getKey(); Map<String, String> mapping = currencyMap.getValue(); if (mapping.isEmpty()) { continue; } method.beginControlFlow("case $L:", code); method.beginControlFlow("switch (category)"); for (Map.Entry<String, String> entry : mapping.entrySet()) { String[] parts = entry.getKey().split("-"); PluralCategory category = PluralCategory.fromString(parts[2]); if (category == PluralCategory.OTHER) { method.addStatement("case $L:\ndefault: return $S", category, entry.getValue()); } else { method.addStatement("case $L: return $S", category, entry.getValue()); } } method.endControlFlow(); method.endControlFlow(); } method.addStatement("default: return $S", ""); method.endControlFlow(); type.addMethod(method.build()); method = MethodSpec.methodBuilder("getCurrencyDigits") .addModifiers(PUBLIC) .addParameter(Types.CLDR_CURRENCY_ENUM, "code") .returns(int.class); method.addStatement("return _CurrencyUtil.getCurrencyDigits(code)"); type.addMethod(method.build()); }
[ "private", "void", "addCurrencyInfo", "(", "TypeSpec", ".", "Builder", "type", ",", "NumberData", "data", ")", "{", "addCurrencyInfoMethod", "(", "type", ",", "\"getCurrencySymbol\"", ",", "data", ".", "currencySymbols", ")", ";", "addCurrencyInfoMethod", "(", "ty...
Adds methods to return information about a currency.
[ "Adds", "methods", "to", "return", "information", "about", "a", "currency", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L425-L470
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java
NumberCodeGenerator.addCurrencyInfoMethod
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("if (code == null)"); method.addStatement("return $S", ""); method.endControlFlow(); method.beginControlFlow("switch (code)"); for (Map.Entry<String, String> entry : mapping.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if (!key.equals(val)) { method.addStatement("case $L: return $S", key, val); } } method.addStatement("default: return code.name()"); method.endControlFlow(); type.addMethod(method.build()); }
java
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("if (code == null)"); method.addStatement("return $S", ""); method.endControlFlow(); method.beginControlFlow("switch (code)"); for (Map.Entry<String, String> entry : mapping.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if (!key.equals(val)) { method.addStatement("case $L: return $S", key, val); } } method.addStatement("default: return code.name()"); method.endControlFlow(); type.addMethod(method.build()); }
[ "private", "void", "addCurrencyInfoMethod", "(", "TypeSpec", ".", "Builder", "type", ",", "String", "name", ",", "Map", "<", "String", ",", "String", ">", "mapping", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "...
Adds a method to return the symbol or display name for a currency.
[ "Adds", "a", "method", "to", "return", "the", "symbol", "or", "display", "name", "for", "a", "currency", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/NumberCodeGenerator.java#L475-L497
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java
LanguageCodeGenerator.buildMatchVariables
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", HASHMAP, STRING, SET, STRING); for (Map.Entry<String, Set<String>> entry : territories.entrySet()) { code.add(" put($S, new $T<>(", entry.getKey(), HASHSET); List<String> list = new ArrayList<>(entry.getValue()); Collections.sort(list); addStringList(code, list, " "); code.add("));\n"); } code.add("\n}}"); TypeName typeName = ParameterizedTypeName.get(MAP, STRING, SET_STRING); type.addField(FieldSpec.builder(typeName, "TERRITORIES", PROTECTED, STATIC, FINAL) .initializer(code.build()) .build()); // Generate mapping for each variable and its inverse. Map<String, Set<String>> variables = new LinkedHashMap<>(); for (Pair<String, String> pair : data.matchVariables) { String variable = pair._1; Set<String> countries = new HashSet<>(); for (String regionId : pair._2.split("\\+")) { Set<String> children = territories.get(regionId); if (children != null) { countries.addAll(children); } else { countries.add(regionId); } } variables.put(variable, countries); } // Build the final variable tables. code = CodeBlock.builder(); code.add("new $T<$T, $T<$T>>() {{\n", HASHMAP, STRING, SET, STRING); for (Map.Entry<String, Set<String>> entry : variables.entrySet()) { code.add(" put($S, new $T<>(", entry.getKey(), HASHSET); List<String> list = new ArrayList<>(entry.getValue()); Collections.sort(list); addStringList(code, list, " "); code.add("));\n"); } code.add("\n}}"); type.addField(FieldSpec.builder(typeName, "VARIABLES", PROTECTED, STATIC, FINAL) .initializer(code.build()) .build()); }
java
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", HASHMAP, STRING, SET, STRING); for (Map.Entry<String, Set<String>> entry : territories.entrySet()) { code.add(" put($S, new $T<>(", entry.getKey(), HASHSET); List<String> list = new ArrayList<>(entry.getValue()); Collections.sort(list); addStringList(code, list, " "); code.add("));\n"); } code.add("\n}}"); TypeName typeName = ParameterizedTypeName.get(MAP, STRING, SET_STRING); type.addField(FieldSpec.builder(typeName, "TERRITORIES", PROTECTED, STATIC, FINAL) .initializer(code.build()) .build()); // Generate mapping for each variable and its inverse. Map<String, Set<String>> variables = new LinkedHashMap<>(); for (Pair<String, String> pair : data.matchVariables) { String variable = pair._1; Set<String> countries = new HashSet<>(); for (String regionId : pair._2.split("\\+")) { Set<String> children = territories.get(regionId); if (children != null) { countries.addAll(children); } else { countries.add(regionId); } } variables.put(variable, countries); } // Build the final variable tables. code = CodeBlock.builder(); code.add("new $T<$T, $T<$T>>() {{\n", HASHMAP, STRING, SET, STRING); for (Map.Entry<String, Set<String>> entry : variables.entrySet()) { code.add(" put($S, new $T<>(", entry.getKey(), HASHSET); List<String> list = new ArrayList<>(entry.getValue()); Collections.sort(list); addStringList(code, list, " "); code.add("));\n"); } code.add("\n}}"); type.addField(FieldSpec.builder(typeName, "VARIABLES", PROTECTED, STATIC, FINAL) .initializer(code.build()) .build()); }
[ "private", "static", "void", "buildMatchVariables", "(", "TypeSpec", ".", "Builder", "type", ",", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "territoryData", ",", "LanguageMatchingData", "data", ")", "{", "Map", "<", "String", ",", "Set", "...
Build table containing language matching variables.
[ "Build", "table", "containing", "language", "matching", "variables", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java#L98-L153
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java
LanguageCodeGenerator.flatten
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(key, values); } return territories; }
java
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(key, values); } return territories; }
[ "private", "static", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "flatten", "(", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "data", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "territories", ...
Flatten the territory containment hierarchy.
[ "Flatten", "the", "territory", "containment", "hierarchy", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java#L158-L166
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java
LanguageCodeGenerator.flatten
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.containsKey(region)) { Set<String> children = flatten(region, flat, data); flat.put(region, children); countries.addAll(children); } else { countries.add(region); } } return countries; }
java
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.containsKey(region)) { Set<String> children = flatten(region, flat, data); flat.put(region, children); countries.addAll(children); } else { countries.add(region); } } return countries; }
[ "private", "static", "Set", "<", "String", ">", "flatten", "(", "String", "parent", ",", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "flat", ",", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "data", ")", "{", "Set", "...
Flatten one level of the territory containment hierarchy.
[ "Flatten", "one", "level", "of", "the", "territory", "containment", "hierarchy", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java#L171-L189
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java
LanguageCodeGenerator.addStringList
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 (width > 80) { width = indent.length(); code.add("\n$L", indent); } String element = list.get(i); code.add("$S", element); width += element.length() + 2; } code.add("\n$L)", indent); }
java
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 (width > 80) { width = indent.length(); code.add("\n$L", indent); } String element = list.get(i); code.add("$S", element); width += element.length() + 2; } code.add("\n$L)", indent); }
[ "private", "static", "void", "addStringList", "(", "CodeBlock", ".", "Builder", "code", ",", "List", "<", "String", ">", "list", ",", "String", "indent", ")", "{", "int", "size", "=", "list", ".", "size", "(", ")", ";", "code", ".", "add", "(", "\"$T...
Helper to add a list of strings to a code block.
[ "Helper", "to", "add", "a", "list", "of", "strings", "to", "a", "code", "block", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/LanguageCodeGenerator.java#L194-L212
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/NumberPatternParser.java
NumberPatternParser.parse
public NumberPattern parse(String raw) { this.buf.setLength(0); this.nodes = new ArrayList<>(); this.attached = false; this.format = new Format(); // Length of the pattern. int length = raw.length(); // Position in the pattern. int i = 0; // Indicate we've seen a group separator and are "inside" a digit group. boolean inGroup = false; // Indicate we're in the decimal portion of the format. boolean inDecimal = false; while (i < length) { char ch = raw.charAt(i); switch (ch) { case '\'': // Single-quote escaping of reserved characters. while (i++ < length) { ch = raw.charAt(i); if (ch == '\'') { break; } buf.append(ch); } break; case '-': pushText(); nodes.add(NumberPattern.Symbol.MINUS); break; case '%': pushText(); nodes.add(NumberPattern.Symbol.PERCENT); break; case '\u00a4': pushText(); nodes.add(NumberPattern.Symbol.CURRENCY); break; case '#': // Optional digit placeholder. attach(); if (inGroup) { format.primaryGroupingSize++; } else if (inDecimal) { format.maximumFractionDigits++; } break; case ',': // Digit grouping delimiter. attach(); if (inGroup) { format.secondaryGroupingSize = format.primaryGroupingSize; format.primaryGroupingSize = 0; } else { inGroup = true; } break; case '.': // Decimal point character. inGroup = false; attach(); inDecimal = true; break; case '0': // Required digit placeholder. If the number being formatted does not // contain a digit, a zero will be output. attach(); if (inGroup) { format.primaryGroupingSize++; } else if (inDecimal) { format.minimumFractionDigits++; format.maximumFractionDigits++; } if (!inDecimal) { format.minimumIntegerDigits++; } break; default: // Rest of characters are assumed to be static. buf.append(ch); break; } i++; } pushText(); return new NumberPattern(raw, nodes, format); }
java
public NumberPattern parse(String raw) { this.buf.setLength(0); this.nodes = new ArrayList<>(); this.attached = false; this.format = new Format(); // Length of the pattern. int length = raw.length(); // Position in the pattern. int i = 0; // Indicate we've seen a group separator and are "inside" a digit group. boolean inGroup = false; // Indicate we're in the decimal portion of the format. boolean inDecimal = false; while (i < length) { char ch = raw.charAt(i); switch (ch) { case '\'': // Single-quote escaping of reserved characters. while (i++ < length) { ch = raw.charAt(i); if (ch == '\'') { break; } buf.append(ch); } break; case '-': pushText(); nodes.add(NumberPattern.Symbol.MINUS); break; case '%': pushText(); nodes.add(NumberPattern.Symbol.PERCENT); break; case '\u00a4': pushText(); nodes.add(NumberPattern.Symbol.CURRENCY); break; case '#': // Optional digit placeholder. attach(); if (inGroup) { format.primaryGroupingSize++; } else if (inDecimal) { format.maximumFractionDigits++; } break; case ',': // Digit grouping delimiter. attach(); if (inGroup) { format.secondaryGroupingSize = format.primaryGroupingSize; format.primaryGroupingSize = 0; } else { inGroup = true; } break; case '.': // Decimal point character. inGroup = false; attach(); inDecimal = true; break; case '0': // Required digit placeholder. If the number being formatted does not // contain a digit, a zero will be output. attach(); if (inGroup) { format.primaryGroupingSize++; } else if (inDecimal) { format.minimumFractionDigits++; format.maximumFractionDigits++; } if (!inDecimal) { format.minimumIntegerDigits++; } break; default: // Rest of characters are assumed to be static. buf.append(ch); break; } i++; } pushText(); return new NumberPattern(raw, nodes, format); }
[ "public", "NumberPattern", "parse", "(", "String", "raw", ")", "{", "this", ".", "buf", ".", "setLength", "(", "0", ")", ";", "this", ".", "nodes", "=", "new", "ArrayList", "<>", "(", ")", ";", "this", ".", "attached", "=", "false", ";", "this", "....
Parse a number formatting pattern.
[ "Parse", "a", "number", "formatting", "pattern", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberPatternParser.java#L34-L135
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/NumberPatternParser.java
NumberPatternParser.pushText
private void pushText() { if (buf.length() > 0) { nodes.add(new NumberPattern.Text(buf.toString())); buf.setLength(0); } }
java
private void pushText() { if (buf.length() > 0) { nodes.add(new NumberPattern.Text(buf.toString())); buf.setLength(0); } }
[ "private", "void", "pushText", "(", ")", "{", "if", "(", "buf", ".", "length", "(", ")", ">", "0", ")", "{", "nodes", ".", "add", "(", "new", "NumberPattern", ".", "Text", "(", "buf", ".", "toString", "(", ")", ")", ")", ";", "buf", ".", "setLe...
If the buffer is not empty, push it onto the node list and reset it.
[ "If", "the", "buffer", "is", "not", "empty", "push", "it", "onto", "the", "node", "list", "and", "reset", "it", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberPatternParser.java#L151-L156
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.fromJavaLocale
public CLDR.Locale fromJavaLocale(java.util.Locale javaLocale) { return MetaLocale.fromJavaLocale(javaLocale); }
java
public CLDR.Locale fromJavaLocale(java.util.Locale javaLocale) { return MetaLocale.fromJavaLocale(javaLocale); }
[ "public", "CLDR", ".", "Locale", "fromJavaLocale", "(", "java", ".", "util", ".", "Locale", "javaLocale", ")", "{", "return", "MetaLocale", ".", "fromJavaLocale", "(", "javaLocale", ")", ";", "}" ]
Convert the Java locale to a CLDR locale object.
[ "Convert", "the", "Java", "locale", "to", "a", "CLDR", "locale", "object", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L80-L82
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.minimize
public CLDR.Locale minimize(CLDR.Locale locale) { return languageResolver.removeLikelySubtags((MetaLocale)locale); }
java
public CLDR.Locale minimize(CLDR.Locale locale) { return languageResolver.removeLikelySubtags((MetaLocale)locale); }
[ "public", "CLDR", ".", "Locale", "minimize", "(", "CLDR", ".", "Locale", "locale", ")", "{", "return", "languageResolver", ".", "removeLikelySubtags", "(", "(", "MetaLocale", ")", "locale", ")", ";", "}" ]
Produce the minimal representation of this locale by removing likely subtags.
[ "Produce", "the", "minimal", "representation", "of", "this", "locale", "by", "removing", "likely", "subtags", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L87-L89
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.getCalendarFormatter
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; }
java
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; }
[ "public", "CalendarFormatter", "getCalendarFormatter", "(", "CLDR", ".", "Locale", "locale", ")", "{", "locale", "=", "bundleMatch", "(", "locale", ")", ";", "CalendarFormatter", "formatter", "=", "CALENDAR_FORMATTERS", ".", "get", "(", "locale", ")", ";", "retu...
Returns a calendar formatter for the given locale, translating it before lookup.
[ "Returns", "a", "calendar", "formatter", "for", "the", "given", "locale", "translating", "it", "before", "lookup", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L94-L98
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.getNumberFormatter
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; }
java
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; }
[ "public", "NumberFormatter", "getNumberFormatter", "(", "CLDR", ".", "Locale", "locale", ")", "{", "locale", "=", "bundleMatch", "(", "locale", ")", ";", "NumberFormatter", "formatter", "=", "NUMBER_FORMATTERS", ".", "get", "(", "locale", ")", ";", "return", "...
Returns a number formatter for the given locale, translating it before lookup.
[ "Returns", "a", "number", "formatter", "for", "the", "given", "locale", "translating", "it", "before", "lookup", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L103-L107
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.addLanguageAlias
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_ALIAS_MAP.get(language); if (aliases == null) { aliases = new ArrayList<>(); LANGUAGE_ALIAS_MAP.put(language, aliases); } aliases.add(Pair.pair(type, replacement)); }
java
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_ALIAS_MAP.get(language); if (aliases == null) { aliases = new ArrayList<>(); LANGUAGE_ALIAS_MAP.put(language, aliases); } aliases.add(Pair.pair(type, replacement)); }
[ "protected", "static", "void", "addLanguageAlias", "(", "String", "rawType", ",", "String", "rawReplacement", ")", "{", "LanguageAlias", "type", "=", "LanguageAlias", ".", "parse", "(", "rawType", ")", ";", "LanguageAlias", "replacement", "=", "LanguageAlias", "."...
Add a language alias entry.
[ "Add", "a", "language", "alias", "entry", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L183-L193
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/CLDRBase.java
CLDRBase.bundleMatch
protected CLDR.Locale bundleMatch(CLDR.Locale locale) { locale = DEFAULT_CONTENT.getOrDefault(locale, locale); return bundleMatcher.match((MetaLocale)locale); }
java
protected CLDR.Locale bundleMatch(CLDR.Locale locale) { locale = DEFAULT_CONTENT.getOrDefault(locale, locale); return bundleMatcher.match((MetaLocale)locale); }
[ "protected", "CLDR", ".", "Locale", "bundleMatch", "(", "CLDR", ".", "Locale", "locale", ")", "{", "locale", "=", "DEFAULT_CONTENT", ".", "getOrDefault", "(", "locale", ",", "locale", ")", ";", "return", "bundleMatcher", ".", "match", "(", "(", "MetaLocale",...
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 subtags and as such should not be used to identify the "en-Latn-US" 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", "ma...
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/CLDRBase.java#L208-L211
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java
DigitBuffer.append
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; }
java
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; }
[ "public", "DigitBuffer", "append", "(", "String", "s", ")", "{", "int", "len", "=", "s", ".", "length", "(", ")", ";", "check", "(", "len", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "this", ...
Append a string to the buffer, expanding it if necessary.
[ "Append", "a", "string", "to", "the", "buffer", "expanding", "it", "if", "necessary", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java#L86-L94
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java
DigitBuffer.append
public void append(DigitBuffer other) { check(other.size); System.arraycopy(other.buf, 0, buf, size, other.size); size += other.size; }
java
public void append(DigitBuffer other) { check(other.size); System.arraycopy(other.buf, 0, buf, size, other.size); size += other.size; }
[ "public", "void", "append", "(", "DigitBuffer", "other", ")", "{", "check", "(", "other", ".", "size", ")", ";", "System", ".", "arraycopy", "(", "other", ".", "buf", ",", "0", ",", "buf", ",", "size", ",", "other", ".", "size", ")", ";", "size", ...
Append the contents of the other buffer to this one.
[ "Append", "the", "contents", "of", "the", "other", "buffer", "to", "this", "one", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java#L99-L103
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java
DigitBuffer.reverse
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; } }
java
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; } }
[ "public", "void", "reverse", "(", "int", "start", ")", "{", "int", "end", "=", "size", "-", "1", ";", "int", "num", "=", "end", "-", "start", ">>", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "num", ";", "i", "++", ")", "{",...
Reverse all characters from start to end of buffer.
[ "Reverse", "all", "characters", "from", "start", "to", "end", "of", "buffer", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java#L125-L135
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java
DigitBuffer.check
private void check(int length) { if (size + length >= buf.length) { buf = Arrays.copyOf(buf, buf.length + length + 16); } }
java
private void check(int length) { if (size + length >= buf.length) { buf = Arrays.copyOf(buf, buf.length + length + 16); } }
[ "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.
[ "Ensure", "the", "buffer", "is", "large", "enough", "for", "the", "next", "append", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/DigitBuffer.java#L148-L152
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.get
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; }
java
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; }
[ "public", "static", "DataReader", "get", "(", ")", "throws", "IOException", "{", "if", "(", "!", "instance", ".", "initialized", ")", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "instance", ".", "init", "(", ")", ";", ...
Returns the global DataReader instance, populating it if necessary.
[ "Returns", "the", "global", "DataReader", "instance", "populating", "it", "if", "necessary", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L168-L176
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.loadPatches
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); } } }
java
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); } } }
[ "private", "void", "loadPatches", "(", ")", "throws", "IOException", "{", "List", "<", "Path", ">", "paths", "=", "Utils", ".", "listResources", "(", "PATCHES", ")", ";", "for", "(", "Path", "path", ":", "paths", ")", "{", "String", "fileName", "=", "p...
Load patches which override values in the CLDR data. Use this to restore certain cases to our preferred form.
[ "Load", "patches", "which", "override", "values", "in", "the", "CLDR", "data", ".", "Use", "this", "to", "restore", "certain", "cases", "to", "our", "preferred", "form", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L425-L434
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.patch
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; } // Check if this patch should be applied to the locale we're processing/ JsonArray locales = patch.getAsJsonArray("locales"); boolean shouldPatch = false; if (code == null) { shouldPatch = true; } else { // Only patch if the locale matches. for (JsonElement locale : locales) { if (locale.getAsString().equals(code)) { shouldPatch = true; break; } } } if (!shouldPatch) { return root; } JsonObject src = resolve(patch, "patch"); JsonObject dst = root; if (patch.get("type").getAsString().equals("main")) { dst = resolve(root, "main", code); } System.out.printf("Applying patch %s to %s\n", entry.getKey(), code); patchObject(src, dst); } return root; }
java
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; } // Check if this patch should be applied to the locale we're processing/ JsonArray locales = patch.getAsJsonArray("locales"); boolean shouldPatch = false; if (code == null) { shouldPatch = true; } else { // Only patch if the locale matches. for (JsonElement locale : locales) { if (locale.getAsString().equals(code)) { shouldPatch = true; break; } } } if (!shouldPatch) { return root; } JsonObject src = resolve(patch, "patch"); JsonObject dst = root; if (patch.get("type").getAsString().equals("main")) { dst = resolve(root, "main", code); } System.out.printf("Applying patch %s to %s\n", entry.getKey(), code); patchObject(src, dst); } return root; }
[ "private", "JsonObject", "patch", "(", "String", "fileName", ",", "String", "code", ",", "JsonObject", "root", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "JsonObject", ">", "entry", ":", "patches", ".", "entrySet", "(", ")", ")", "{...
Apply a patch to the given filename, if applicable.
[ "Apply", "a", "patch", "to", "the", "given", "filename", "if", "applicable", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L439-L476
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.patchObject
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.getAsJsonObject()); continue; } if (se.isJsonPrimitive() && de.isJsonPrimitive()) { dst.add(key, se); } } }
java
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.getAsJsonObject()); continue; } if (se.isJsonPrimitive() && de.isJsonPrimitive()) { dst.add(key, se); } } }
[ "private", "void", "patchObject", "(", "JsonObject", "src", ",", "JsonObject", "dst", ")", "{", "for", "(", "String", "key", ":", "objectKeys", "(", "src", ")", ")", "{", "JsonElement", "se", "=", "src", ".", "get", "(", "key", ")", ";", "JsonElement",...
Overlay nested values from src on top of dst.
[ "Overlay", "nested", "values", "from", "src", "on", "top", "of", "dst", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L481-L496
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.sanityCheck
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 DATA MISSING! Can't find '%s'. " + " You may need to run 'git submodule update'", name); throw new RuntimeException(msg); } } }
java
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 DATA MISSING! Can't find '%s'. " + " You may need to run 'git submodule update'", name); throw new RuntimeException(msg); } } }
[ "private", "void", "sanityCheck", "(", "List", "<", "Path", ">", "resources", ")", "{", "Set", "<", "String", ">", "fileNames", "=", "resources", ".", "stream", "(", ")", ".", "map", "(", "p", "->", "p", ".", "getFileName", "(", ")", ".", "toString",...
Blow up if required paths do not exist.
[ "Blow", "up", "if", "required", "paths", "do", "not", "exist", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L501-L512
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.load
private JsonObject load(Path path) throws IOException { try (InputStream stream = Resources.getResource(path.toString()).openStream()) { return (JsonObject) JSON_PARSER.parse(new InputStreamReader(stream)); } }
java
private JsonObject load(Path path) throws IOException { try (InputStream stream = Resources.getResource(path.toString()).openStream()) { return (JsonObject) JSON_PARSER.parse(new InputStreamReader(stream)); } }
[ "private", "JsonObject", "load", "(", "Path", "path", ")", "throws", "IOException", "{", "try", "(", "InputStream", "stream", "=", "Resources", ".", "getResource", "(", "path", ".", "toString", "(", ")", ")", ".", "openStream", "(", ")", ")", "{", "retur...
Loads and parses a JSON file, returning a reference to its root object node.
[ "Loads", "and", "parses", "a", "JSON", "file", "returning", "a", "reference", "to", "its", "root", "object", "node", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L517-L521
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseIdentity
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")); }
java
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")); }
[ "private", "LocaleID", "parseIdentity", "(", "String", "code", ",", "JsonObject", "root", ")", "throws", "IOException", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"main\"", ",", "code", ",", "\"identity\"", ")", ";", "return", "new", "Loc...
Parse the locale identity header from a calendar JSON tree.
[ "Parse", "the", "locale", "identity", "header", "from", "a", "calendar", "JSON", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L526-L533
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseLikelySubtags
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()); } }
java
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()); } }
[ "private", "void", "parseLikelySubtags", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"likelySubtags\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "JsonElement", ...
Parse likely subtags tree.
[ "Parse", "likely", "subtags", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L548-L553
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseLanguageMatchingFix
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 = string(value, "desired"); String supported = string(value, "supported"); Integer distance = Integer.parseInt(string(value, "distance")); boolean oneway = string(value, "oneway", null) != null; LanguageMatch match = new LanguageMatch(desired, supported, distance, oneway); languageMatching.languageMatches.add(match); } JsonObject variables = resolve(node, "matchVariable"); for (Map.Entry<String, JsonElement> entry : variables.entrySet()) { String value = entry.getValue().getAsString(); languageMatching.matchVariables.add(Pair.pair(entry.getKey(), value)); } for (String code : string(node, "paradigmLocales").split("\\s+")) { languageMatching.paradigmLocales.add(code); } }
java
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 = string(value, "desired"); String supported = string(value, "supported"); Integer distance = Integer.parseInt(string(value, "distance")); boolean oneway = string(value, "oneway", null) != null; LanguageMatch match = new LanguageMatch(desired, supported, distance, oneway); languageMatching.languageMatches.add(match); } JsonObject variables = resolve(node, "matchVariable"); for (Map.Entry<String, JsonElement> entry : variables.entrySet()) { String value = entry.getValue().getAsString(); languageMatching.matchVariables.add(Pair.pair(entry.getKey(), value)); } for (String code : string(node, "paradigmLocales").split("\\s+")) { languageMatching.paradigmLocales.add(code); } }
[ "private", "void", "parseLanguageMatchingFix", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"languageMatching\"", ",", "\"written_new\"", ")", ";", "JsonArray", "matches", "=", "node", ".",...
Parse enhanced language matching fix tree.
[ "Parse", "enhanced", "language", "matching", "fix", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L558-L581
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTerritoryContainment
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.endsWith("-status-grouping")) { continue; } parentCode = parentCode.split("-")[0]; } JsonObject value = entry.getValue().getAsJsonObject(); JsonArray elements = (JsonArray) value.get("_contains"); if (elements == null) { throw new RuntimeException("Unexpected object structure: " + value); } List<String> children = new ArrayList<>(); for (JsonElement element : elements) { String code = element.getAsString(); children.add(code); } Set<String> regions = territoryContainment.get(parentCode); if (regions == null) { regions = new TreeSet<>(); territoryContainment.put(parentCode, regions); } regions.addAll(children); } }
java
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.endsWith("-status-grouping")) { continue; } parentCode = parentCode.split("-")[0]; } JsonObject value = entry.getValue().getAsJsonObject(); JsonArray elements = (JsonArray) value.get("_contains"); if (elements == null) { throw new RuntimeException("Unexpected object structure: " + value); } List<String> children = new ArrayList<>(); for (JsonElement element : elements) { String code = element.getAsString(); children.add(code); } Set<String> regions = territoryContainment.get(parentCode); if (regions == null) { regions = new TreeSet<>(); territoryContainment.put(parentCode, regions); } regions.addAll(children); } }
[ "private", "void", "parseTerritoryContainment", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"territoryContainment\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Js...
Parse territory containment tree.
[ "Parse", "territory", "containment", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L586-L616
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseCalendar
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 = parseDayPeriods(node, "stand-alone"); data.monthsFormat = parseMonths(node, "format"); data.monthsStandalone = parseMonths(node, "stand-alone"); data.weekdaysFormat = parseWeekdays(node, "format"); data.weekdaysStandalone = parseWeekdays(node, "stand-alone"); data.quartersFormat = parseQuarters(node, "format"); data.quartersStandalone = parseQuarters(node, "stand-alone"); data.dateFormats = parseDateFormats(node); data.timeFormats = parseTimeFormats(node); data.dateTimeFormats = parseDateTimeFormats(node); data.dateTimeSkeletons = parseDateTimeSkeletons(node); // date time intervals and fallback format data.intervalFormats = new HashMap<>(); node = resolve(node, "dateTimeFormats", "intervalFormats"); for (String key : objectKeys(node)) { if (key.equals("intervalFormatFallback")) { data.intervalFallbackFormat = string(node, key); } else { Map<String, String> format = data.intervalFormats.get(key); if (format == null) { format = new HashMap<>(); data.intervalFormats.put(key, format); } JsonObject fieldNode = node.getAsJsonObject(key); for (String field : objectKeys(fieldNode)) { if (!field.endsWith("-alt-variant")) { format.put(field, string(fieldNode, field)); } } } } return data; }
java
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 = parseDayPeriods(node, "stand-alone"); data.monthsFormat = parseMonths(node, "format"); data.monthsStandalone = parseMonths(node, "stand-alone"); data.weekdaysFormat = parseWeekdays(node, "format"); data.weekdaysStandalone = parseWeekdays(node, "stand-alone"); data.quartersFormat = parseQuarters(node, "format"); data.quartersStandalone = parseQuarters(node, "stand-alone"); data.dateFormats = parseDateFormats(node); data.timeFormats = parseTimeFormats(node); data.dateTimeFormats = parseDateTimeFormats(node); data.dateTimeSkeletons = parseDateTimeSkeletons(node); // date time intervals and fallback format data.intervalFormats = new HashMap<>(); node = resolve(node, "dateTimeFormats", "intervalFormats"); for (String key : objectKeys(node)) { if (key.equals("intervalFormatFallback")) { data.intervalFallbackFormat = string(node, key); } else { Map<String, String> format = data.intervalFormats.get(key); if (format == null) { format = new HashMap<>(); data.intervalFormats.put(key, format); } JsonObject fieldNode = node.getAsJsonObject(key); for (String field : objectKeys(fieldNode)) { if (!field.endsWith("-alt-variant")) { format.put(field, string(fieldNode, field)); } } } } return data; }
[ "private", "DateTimeData", "parseCalendar", "(", "JsonObject", "root", ")", "throws", "IOException", "{", "DateTimeData", "data", "=", "new", "DateTimeData", "(", ")", ";", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"dates\"", ",", "\"calendars\""...
Parse calendar date-time attributes.
[ "Parse", "calendar", "date", "-", "time", "attributes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L621-L662
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseDateFormats
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")); }
java
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")); }
[ "private", "Format", "parseDateFormats", "(", "JsonObject", "calendar", ")", "{", "JsonObject", "node", "=", "resolve", "(", "calendar", ",", "\"dateFormats\"", ")", ";", "return", "new", "Format", "(", "string", "(", "node", ",", "\"short\"", ")", ",", "str...
Parse standard date formats of varying sizes.
[ "Parse", "standard", "date", "formats", "of", "varying", "sizes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L737-L744
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTimeFormats
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")); }
java
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")); }
[ "private", "Format", "parseTimeFormats", "(", "JsonObject", "calendar", ")", "{", "JsonObject", "node", "=", "resolve", "(", "calendar", ",", "\"timeFormats\"", ")", ";", "return", "new", "Format", "(", "string", "(", "node", ",", "\"short\"", ")", ",", "str...
Parse standard time formats of varying sizes.
[ "Parse", "standard", "time", "formats", "of", "varying", "sizes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L749-L756
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseDateTimeFormats
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")); }
java
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")); }
[ "private", "Format", "parseDateTimeFormats", "(", "JsonObject", "calendar", ")", "{", "JsonObject", "node", "=", "resolve", "(", "calendar", ",", "\"dateTimeFormats\"", ")", ";", "return", "new", "Format", "(", "string", "(", "node", ",", "\"short\"", ")", ","...
Parse standard date-time wrapper formats of varying sizes.
[ "Parse", "standard", "date", "-", "time", "wrapper", "formats", "of", "varying", "sizes", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L761-L768
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseDateTimeSkeletons
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))); } return value; }
java
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))); } return value; }
[ "private", "List", "<", "Skeleton", ">", "parseDateTimeSkeletons", "(", "JsonObject", "calendar", ")", "{", "JsonObject", "node", "=", "resolve", "(", "calendar", ",", "\"dateTimeFormats\"", ",", "\"availableFormats\"", ")", ";", "List", "<", "Skeleton", ">", "v...
Parse date-time skeletons.
[ "Parse", "date", "-", "time", "skeletons", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L773-L780
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseMinDays
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; }
java
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; }
[ "private", "Map", "<", "String", ",", "Integer", ">", "parseMinDays", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"weekData\"", ",", "\"minDays\"", ")", ";", "Map", "<", "String", ...
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.
[ "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", ...
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L787-L794
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseFirstDays
private Map<String, Integer> parseFirstDays(JsonObject root) { JsonObject node = resolve(root, "supplemental", "weekData", "firstDay"); Map<String, Integer> m = new HashMap<>(); for (String key : objectKeys(node)) { String value = string(node, key); m.put(key, NUMERIC_DAYS.get(value)); } return m; }
java
private Map<String, Integer> parseFirstDays(JsonObject root) { JsonObject node = resolve(root, "supplemental", "weekData", "firstDay"); Map<String, Integer> m = new HashMap<>(); for (String key : objectKeys(node)) { String value = string(node, key); m.put(key, NUMERIC_DAYS.get(value)); } return m; }
[ "private", "Map", "<", "String", ",", "Integer", ">", "parseFirstDays", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"weekData\"", ",", "\"firstDay\"", ")", ";", "Map", "<", "String",...
Parse the "first day" values. This is the value of the first day of the week in a calendar view.
[ "Parse", "the", "first", "day", "values", ".", "This", "is", "the", "value", "of", "the", "first", "day", "of", "the", "week", "in", "a", "calendar", "view", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L800-L808
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.weekdayMap
private String[] weekdayMap(JsonObject node) { String[] res = new String[7]; for (int i = 0; i < 7; i++) { res[i] = node.get(WEEKDAY_KEYS[i]).getAsString(); } return res; }
java
private String[] weekdayMap(JsonObject node) { String[] res = new String[7]; for (int i = 0; i < 7; i++) { res[i] = node.get(WEEKDAY_KEYS[i]).getAsString(); } return res; }
[ "private", "String", "[", "]", "weekdayMap", "(", "JsonObject", "node", ")", "{", "String", "[", "]", "res", "=", "new", "String", "[", "7", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "7", ";", "i", "++", ")", "{", "res", "[",...
Extract weekday names from a locale's mapping.
[ "Extract", "weekday", "names", "from", "a", "locale", "s", "mapping", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L813-L819
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parsePlurals
private void parsePlurals(JsonObject root, String type, Map<String, PluralData> map) { JsonObject node = resolve(root, "supplemental", type); for (Map.Entry<String, JsonElement> entry : node.entrySet()) { String language = entry.getKey(); PluralData data = new PluralData(); for (Map.Entry<String, JsonElement> ruleNode : entry.getValue().getAsJsonObject().entrySet()) { String category = ruleNode.getKey().replaceFirst("^pluralRule-count-", ""); String value = ruleNode.getValue().getAsString(); Maybe<Pair<Node<PluralType>, CharSequence>> result = PluralRuleGrammar.parse(value); if (result.isNothing()) { throw new IllegalArgumentException(format("failed to parse rule: \"%s\"", StringEscapeUtils.escapeJava(value))); } Struct<PluralType> rule = result.get()._1.asStruct(); Node<PluralType> conditionNode = findChild(rule, PluralType.OR_CONDITION); Node<PluralType> sampleNode = findChild(rule, PluralType.SAMPLE); String sample = sampleNode == null ? "" : (String) sampleNode.asAtom().value(); data.add(category, new PluralData.Rule(value, conditionNode, sample)); } map.put(language, data); } }
java
private void parsePlurals(JsonObject root, String type, Map<String, PluralData> map) { JsonObject node = resolve(root, "supplemental", type); for (Map.Entry<String, JsonElement> entry : node.entrySet()) { String language = entry.getKey(); PluralData data = new PluralData(); for (Map.Entry<String, JsonElement> ruleNode : entry.getValue().getAsJsonObject().entrySet()) { String category = ruleNode.getKey().replaceFirst("^pluralRule-count-", ""); String value = ruleNode.getValue().getAsString(); Maybe<Pair<Node<PluralType>, CharSequence>> result = PluralRuleGrammar.parse(value); if (result.isNothing()) { throw new IllegalArgumentException(format("failed to parse rule: \"%s\"", StringEscapeUtils.escapeJava(value))); } Struct<PluralType> rule = result.get()._1.asStruct(); Node<PluralType> conditionNode = findChild(rule, PluralType.OR_CONDITION); Node<PluralType> sampleNode = findChild(rule, PluralType.SAMPLE); String sample = sampleNode == null ? "" : (String) sampleNode.asAtom().value(); data.add(category, new PluralData.Rule(value, conditionNode, sample)); } map.put(language, data); } }
[ "private", "void", "parsePlurals", "(", "JsonObject", "root", ",", "String", "type", ",", "Map", "<", "String", ",", "PluralData", ">", "map", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "type", ")", ";", "f...
Parse pluralization rules. These rules indicate which pluralization category is in effect, based on the value of the plural operands which are computed from an integer or decimal value.
[ "Parse", "pluralization", "rules", ".", "These", "rules", "indicate", "which", "pluralization", "category", "is", "in", "effect", "based", "on", "the", "value", "of", "the", "plural", "operands", "which", "are", "computed", "from", "an", "integer", "or", "deci...
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L826-L848
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseNumberData
private NumberData parseNumberData(LocaleID id, String code, JsonObject root) { NumberData data = getNumberData(id); JsonObject numbers = resolve(root, "numbers"); data.minimumGroupingDigits = Integer.valueOf(string(numbers, "minimumGroupingDigits")); JsonObject symbols = resolve(numbers, "symbols-numberSystem-latn"); data.decimal = string(symbols, "decimal"); data.group = string(symbols, "group"); data.percent = string(symbols, "percentSign"); data.plus = string(symbols, "plusSign"); data.minus = string(symbols, "minusSign"); data.exponential = string(symbols, "exponential"); data.superscriptingExponent = string(symbols, "superscriptingExponent"); data.perMille = string(symbols, "perMille"); data.infinity = string(symbols, "infinity"); data.nan = string(symbols, "nan"); // The fields 'currencyDecimal' and 'currencyGroup' are only defined for a few locales data.currencyDecimal = string(symbols, "currencyDecimal", data.decimal); data.currencyGroup = string(symbols, "currencyGroup", data.group); JsonObject decimalFormats = resolve(numbers, "decimalFormats-numberSystem-latn"); data.decimalFormatStandard = getNumberPattern(string(decimalFormats, "standard")); data.decimalFormatShort = getPluralNumberPattern(resolve(decimalFormats, "short", "decimalFormat")); data.decimalFormatLong = getPluralNumberPattern(resolve(decimalFormats, "long", "decimalFormat")); JsonObject percentFormats = resolve(numbers, "percentFormats-numberSystem-latn"); data.percentFormatStandard = getNumberPattern(string(percentFormats, "standard")); JsonObject currencyFormats = resolve(numbers, "currencyFormats-numberSystem-latn"); data.currencyFormatStandard = getNumberPattern(string(currencyFormats, "standard")); data.currencyFormatAccounting = getNumberPattern(string(currencyFormats, "accounting")); data.currencyFormatShort = getPluralNumberPattern(resolve(currencyFormats, "short", "standard")); data.currencyUnitPattern = new HashMap<>(); for (String key : objectKeys(currencyFormats)) { if (key.startsWith("unitPattern-count")) { data.currencyUnitPattern.put(key, string(currencyFormats, key)); } } return data; }
java
private NumberData parseNumberData(LocaleID id, String code, JsonObject root) { NumberData data = getNumberData(id); JsonObject numbers = resolve(root, "numbers"); data.minimumGroupingDigits = Integer.valueOf(string(numbers, "minimumGroupingDigits")); JsonObject symbols = resolve(numbers, "symbols-numberSystem-latn"); data.decimal = string(symbols, "decimal"); data.group = string(symbols, "group"); data.percent = string(symbols, "percentSign"); data.plus = string(symbols, "plusSign"); data.minus = string(symbols, "minusSign"); data.exponential = string(symbols, "exponential"); data.superscriptingExponent = string(symbols, "superscriptingExponent"); data.perMille = string(symbols, "perMille"); data.infinity = string(symbols, "infinity"); data.nan = string(symbols, "nan"); // The fields 'currencyDecimal' and 'currencyGroup' are only defined for a few locales data.currencyDecimal = string(symbols, "currencyDecimal", data.decimal); data.currencyGroup = string(symbols, "currencyGroup", data.group); JsonObject decimalFormats = resolve(numbers, "decimalFormats-numberSystem-latn"); data.decimalFormatStandard = getNumberPattern(string(decimalFormats, "standard")); data.decimalFormatShort = getPluralNumberPattern(resolve(decimalFormats, "short", "decimalFormat")); data.decimalFormatLong = getPluralNumberPattern(resolve(decimalFormats, "long", "decimalFormat")); JsonObject percentFormats = resolve(numbers, "percentFormats-numberSystem-latn"); data.percentFormatStandard = getNumberPattern(string(percentFormats, "standard")); JsonObject currencyFormats = resolve(numbers, "currencyFormats-numberSystem-latn"); data.currencyFormatStandard = getNumberPattern(string(currencyFormats, "standard")); data.currencyFormatAccounting = getNumberPattern(string(currencyFormats, "accounting")); data.currencyFormatShort = getPluralNumberPattern(resolve(currencyFormats, "short", "standard")); data.currencyUnitPattern = new HashMap<>(); for (String key : objectKeys(currencyFormats)) { if (key.startsWith("unitPattern-count")) { data.currencyUnitPattern.put(key, string(currencyFormats, key)); } } return data; }
[ "private", "NumberData", "parseNumberData", "(", "LocaleID", "id", ",", "String", "code", ",", "JsonObject", "root", ")", "{", "NumberData", "data", "=", "getNumberData", "(", "id", ")", ";", "JsonObject", "numbers", "=", "resolve", "(", "root", ",", "\"numb...
Parse number and some currency data for locale.
[ "Parse", "number", "and", "some", "currency", "data", "for", "locale", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L853-L895
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseCurrencyData
private void parseCurrencyData(LocaleID id, String code, JsonObject root) { NumberData data = getNumberData(id); data.currencySymbols = new LinkedHashMap<>(); data.narrowCurrencySymbols = new LinkedHashMap<>(); data.currencyDisplayName = new LinkedHashMap<>(); data.currencyDisplayNames = new LinkedHashMap<>(); JsonObject currencies = resolve(root, "numbers", "currencies"); for (String currencyCode : objectKeys(currencies)) { JsonObject node = resolve(currencies, currencyCode); data.currencyDisplayName.put(currencyCode, string(node, "displayName")); String symbol = string(node, "symbol"); String narrowSymbol = string(node, "symbol-alt-narrow"); narrowSymbol = narrowSymbol.equals("") ? symbol : narrowSymbol; data.currencySymbols.put(currencyCode, symbol); data.narrowCurrencySymbols.put(currencyCode, narrowSymbol); Map<String, String> displayNames = new LinkedHashMap<>(); for (String key : objectKeys(node)) { if (key.startsWith("displayName-count")) { displayNames.put(key, node.get(key).getAsString()); } } data.currencyDisplayNames.put(currencyCode, displayNames); } }
java
private void parseCurrencyData(LocaleID id, String code, JsonObject root) { NumberData data = getNumberData(id); data.currencySymbols = new LinkedHashMap<>(); data.narrowCurrencySymbols = new LinkedHashMap<>(); data.currencyDisplayName = new LinkedHashMap<>(); data.currencyDisplayNames = new LinkedHashMap<>(); JsonObject currencies = resolve(root, "numbers", "currencies"); for (String currencyCode : objectKeys(currencies)) { JsonObject node = resolve(currencies, currencyCode); data.currencyDisplayName.put(currencyCode, string(node, "displayName")); String symbol = string(node, "symbol"); String narrowSymbol = string(node, "symbol-alt-narrow"); narrowSymbol = narrowSymbol.equals("") ? symbol : narrowSymbol; data.currencySymbols.put(currencyCode, symbol); data.narrowCurrencySymbols.put(currencyCode, narrowSymbol); Map<String, String> displayNames = new LinkedHashMap<>(); for (String key : objectKeys(node)) { if (key.startsWith("displayName-count")) { displayNames.put(key, node.get(key).getAsString()); } } data.currencyDisplayNames.put(currencyCode, displayNames); } }
[ "private", "void", "parseCurrencyData", "(", "LocaleID", "id", ",", "String", "code", ",", "JsonObject", "root", ")", "{", "NumberData", "data", "=", "getNumberData", "(", "id", ")", ";", "data", ".", "currencySymbols", "=", "new", "LinkedHashMap", "<>", "("...
Parse locale-specific currency data.
[ "Parse", "locale", "-", "specific", "currency", "data", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L900-L925
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseSupplementalCurrencyData
private void parseSupplementalCurrencyData(JsonObject root) { JsonObject fractions = resolve(root, "supplemental", "currencyData", "fractions"); for (String code : objectKeys(fractions)) { CurrencyData data = getCurrencyData(code); JsonObject node = fractions.get(code).getAsJsonObject(); data.digits = Integer.valueOf(string(node, "_digits")); // Note: _rounding = 0 for all currencies in the modern data set. } }
java
private void parseSupplementalCurrencyData(JsonObject root) { JsonObject fractions = resolve(root, "supplemental", "currencyData", "fractions"); for (String code : objectKeys(fractions)) { CurrencyData data = getCurrencyData(code); JsonObject node = fractions.get(code).getAsJsonObject(); data.digits = Integer.valueOf(string(node, "_digits")); // Note: _rounding = 0 for all currencies in the modern data set. } }
[ "private", "void", "parseSupplementalCurrencyData", "(", "JsonObject", "root", ")", "{", "JsonObject", "fractions", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"currencyData\"", ",", "\"fractions\"", ")", ";", "for", "(", "String", "code", ":", ...
Parse supplemental currency data.
[ "Parse", "supplemental", "currency", "data", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L930-L938
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.getNumberData
private NumberData getNumberData(LocaleID id) { NumberData data = numbers.get(id); if (data == null) { data = new NumberData(); data.setID(id); numbers.put(id, data); } return data; }
java
private NumberData getNumberData(LocaleID id) { NumberData data = numbers.get(id); if (data == null) { data = new NumberData(); data.setID(id); numbers.put(id, data); } return data; }
[ "private", "NumberData", "getNumberData", "(", "LocaleID", "id", ")", "{", "NumberData", "data", "=", "numbers", ".", "get", "(", "id", ")", ";", "if", "(", "data", "==", "null", ")", "{", "data", "=", "new", "NumberData", "(", ")", ";", "data", ".",...
Get or create the number data object for this locale.
[ "Get", "or", "create", "the", "number", "data", "object", "for", "this", "locale", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L943-L951
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.getCurrencyData
private CurrencyData getCurrencyData(String code) { CurrencyData data = currencies.get(code); if (data == null) { data = new CurrencyData(); data.setCode(code); currencies.put(code, data); } return data; }
java
private CurrencyData getCurrencyData(String code) { CurrencyData data = currencies.get(code); if (data == null) { data = new CurrencyData(); data.setCode(code); currencies.put(code, data); } return data; }
[ "private", "CurrencyData", "getCurrencyData", "(", "String", "code", ")", "{", "CurrencyData", "data", "=", "currencies", ".", "get", "(", "code", ")", ";", "if", "(", "data", "==", "null", ")", "{", "data", "=", "new", "CurrencyData", "(", ")", ";", "...
Get or create the currency data object for this code.
[ "Get", "or", "create", "the", "currency", "data", "object", "for", "this", "code", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L956-L964
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTimeZoneInfos
private List<TimeZoneInfo> parseTimeZoneInfos(String code, JsonObject root) { JsonObject node = resolve(root, "main", code, "dates", "timeZoneNames", "zone"); return parseTimeZoneInfo(node, Collections.emptyList()); }
java
private List<TimeZoneInfo> parseTimeZoneInfos(String code, JsonObject root) { JsonObject node = resolve(root, "main", code, "dates", "timeZoneNames", "zone"); return parseTimeZoneInfo(node, Collections.emptyList()); }
[ "private", "List", "<", "TimeZoneInfo", ">", "parseTimeZoneInfos", "(", "String", "code", ",", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"main\"", ",", "code", ",", "\"dates\"", ",", "\"timeZoneNames\"", ",", "...
Parse timezone names.
[ "Parse", "timezone", "names", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1029-L1032
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTimeZoneInfo
private List<TimeZoneInfo> parseTimeZoneInfo(JsonObject root, List<String> prefix) { List<TimeZoneInfo> zones = new ArrayList<>(); for (String label : objectKeys(root)) { JsonObject value = resolve(root, label); List<String> zone = new ArrayList<>(prefix); zone.add(label); if (isTimeZone(value)) { TimeZoneInfo info = parseTimeZoneObject(value, zone); zones.add(info); } else { zones.addAll(parseTimeZoneInfo(value, zone)); } } return zones; }
java
private List<TimeZoneInfo> parseTimeZoneInfo(JsonObject root, List<String> prefix) { List<TimeZoneInfo> zones = new ArrayList<>(); for (String label : objectKeys(root)) { JsonObject value = resolve(root, label); List<String> zone = new ArrayList<>(prefix); zone.add(label); if (isTimeZone(value)) { TimeZoneInfo info = parseTimeZoneObject(value, zone); zones.add(info); } else { zones.addAll(parseTimeZoneInfo(value, zone)); } } return zones; }
[ "private", "List", "<", "TimeZoneInfo", ">", "parseTimeZoneInfo", "(", "JsonObject", "root", ",", "List", "<", "String", ">", "prefix", ")", "{", "List", "<", "TimeZoneInfo", ">", "zones", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String...
Recursively parse the zone labels until we get to a zone info object.
[ "Recursively", "parse", "the", "zone", "labels", "until", "we", "get", "to", "a", "zone", "info", "object", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1037-L1051
train