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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java | LuceneGazetteer.sanitizeQueryText | private String sanitizeQueryText(final GazetteerQuery query) {
String sanitized = "";
if (query != null && query.getOccurrence() != null) {
String text = query.getOccurrence().getText();
if (text != null) {
sanitized = escape(text.trim().toLowerCase());
}
}
return sanitized;
} | java | private String sanitizeQueryText(final GazetteerQuery query) {
String sanitized = "";
if (query != null && query.getOccurrence() != null) {
String text = query.getOccurrence().getText();
if (text != null) {
sanitized = escape(text.trim().toLowerCase());
}
}
return sanitized;
} | [
"private",
"String",
"sanitizeQueryText",
"(",
"final",
"GazetteerQuery",
"query",
")",
"{",
"String",
"sanitized",
"=",
"\"\"",
";",
"if",
"(",
"query",
"!=",
"null",
"&&",
"query",
".",
"getOccurrence",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"text",... | Sanitizes the text of the LocationOccurrence in the query parameters for
use in a Lucene query, returning an empty string if no text is found.
@param query the query configuration
@return the santitized query text or the empty string if there is no query text | [
"Sanitizes",
"the",
"text",
"of",
"the",
"LocationOccurrence",
"in",
"the",
"query",
"parameters",
"for",
"use",
"in",
"a",
"Lucene",
"query",
"returning",
"an",
"empty",
"string",
"if",
"no",
"text",
"is",
"found",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java#L332-L341 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java | LuceneGazetteer.buildFilter | private Filter buildFilter(final GazetteerQuery params) {
List<Query> queryParts = new ArrayList<Query>();
// create the historical locations restriction if we are not including historical locations
if (!params.isIncludeHistorical()) {
int val = IndexField.getBooleanIndexValue(false);
queryParts.add(NumericRangeQuery.newIntRange(HISTORICAL.key(), val, val, true, true));
}
// create the parent ID restrictions if we were provided at least one parent ID
Set<Integer> parentIds = params.getParentIds();
if (!parentIds.isEmpty()) {
BooleanQuery parentQuery = new BooleanQuery();
// locations must descend from at least one of the specified parents (OR)
for (Integer id : parentIds) {
parentQuery.add(NumericRangeQuery.newIntRange(ANCESTOR_IDS.key(), id, id, true, true), Occur.SHOULD);
}
queryParts.add(parentQuery);
}
// create the feature code restrictions if we were provided some, but not all, feature codes
Set<FeatureCode> codes = params.getFeatureCodes();
if (!(codes.isEmpty() || ALL_CODES.equals(codes))) {
BooleanQuery codeQuery = new BooleanQuery();
// locations must be one of the specified feature codes (OR)
for (FeatureCode code : codes) {
codeQuery.add(new TermQuery(new Term(FEATURE_CODE.key(), code.name())), Occur.SHOULD);
}
queryParts.add(codeQuery);
}
Filter filter = null;
if (!queryParts.isEmpty()) {
BooleanQuery bq = new BooleanQuery();
for (Query part : queryParts) {
bq.add(part, Occur.MUST);
}
filter = new QueryWrapperFilter(bq);
}
return filter;
} | java | private Filter buildFilter(final GazetteerQuery params) {
List<Query> queryParts = new ArrayList<Query>();
// create the historical locations restriction if we are not including historical locations
if (!params.isIncludeHistorical()) {
int val = IndexField.getBooleanIndexValue(false);
queryParts.add(NumericRangeQuery.newIntRange(HISTORICAL.key(), val, val, true, true));
}
// create the parent ID restrictions if we were provided at least one parent ID
Set<Integer> parentIds = params.getParentIds();
if (!parentIds.isEmpty()) {
BooleanQuery parentQuery = new BooleanQuery();
// locations must descend from at least one of the specified parents (OR)
for (Integer id : parentIds) {
parentQuery.add(NumericRangeQuery.newIntRange(ANCESTOR_IDS.key(), id, id, true, true), Occur.SHOULD);
}
queryParts.add(parentQuery);
}
// create the feature code restrictions if we were provided some, but not all, feature codes
Set<FeatureCode> codes = params.getFeatureCodes();
if (!(codes.isEmpty() || ALL_CODES.equals(codes))) {
BooleanQuery codeQuery = new BooleanQuery();
// locations must be one of the specified feature codes (OR)
for (FeatureCode code : codes) {
codeQuery.add(new TermQuery(new Term(FEATURE_CODE.key(), code.name())), Occur.SHOULD);
}
queryParts.add(codeQuery);
}
Filter filter = null;
if (!queryParts.isEmpty()) {
BooleanQuery bq = new BooleanQuery();
for (Query part : queryParts) {
bq.add(part, Occur.MUST);
}
filter = new QueryWrapperFilter(bq);
}
return filter;
} | [
"private",
"Filter",
"buildFilter",
"(",
"final",
"GazetteerQuery",
"params",
")",
"{",
"List",
"<",
"Query",
">",
"queryParts",
"=",
"new",
"ArrayList",
"<",
"Query",
">",
"(",
")",
";",
"// create the historical locations restriction if we are not including historical... | Builds a Lucene search filter based on the provided parameters.
@param params the query configuration parameters
@return a Lucene search filter that will restrict the returned documents to the criteria provided or <code>null</code>
if no filtering is necessary | [
"Builds",
"a",
"Lucene",
"search",
"filter",
"based",
"on",
"the",
"provided",
"parameters",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java#L349-L389 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java | LuceneGazetteer.resolveParents | private void resolveParents(final Map<Integer, Set<GeoName>> childMap) throws IOException {
Map<Integer, GeoName> parentMap = new HashMap<Integer, GeoName>();
Map<Integer, Set<GeoName>> grandParentMap = new HashMap<Integer, Set<GeoName>>();
for (Integer parentId : childMap.keySet()) {
// Lucene query used to look for exact match on the "geonameID" field
Query q = NumericRangeQuery.newIntRange(GEONAME_ID.key(), parentId, parentId, true, true);
TopDocs results = indexSearcher.search(q, null, 1, POPULATION_SORT);
if (results.scoreDocs.length > 0) {
Document doc = indexSearcher.doc(results.scoreDocs[0].doc);
GeoName parent = BasicGeoName.parseFromGeoNamesRecord(doc.get(GEONAME.key()), doc.get(PREFERRED_NAME.key()));
parentMap.put(parent.getGeonameID(), parent);
if (!parent.isAncestryResolved()) {
Integer grandParentId = PARENT_ID.getValue(doc);
if (grandParentId != null) {
Set<GeoName> geos = grandParentMap.get(grandParentId);
if (geos == null) {
geos = new HashSet<GeoName>();
grandParentMap.put(grandParentId, geos);
}
geos.add(parent);
}
}
} else {
LOG.error("Unable to find parent GeoName [{}]", parentId);
}
}
// find all parents of the parents
if (!grandParentMap.isEmpty()) {
resolveParents(grandParentMap);
}
// set parents of children
for (Integer parentId : childMap.keySet()) {
GeoName parent = parentMap.get(parentId);
if (parent == null) {
LOG.info("Unable to find parent with ID [{}]", parentId);
continue;
}
for (GeoName child : childMap.get(parentId)) {
child.setParent(parent);
}
}
} | java | private void resolveParents(final Map<Integer, Set<GeoName>> childMap) throws IOException {
Map<Integer, GeoName> parentMap = new HashMap<Integer, GeoName>();
Map<Integer, Set<GeoName>> grandParentMap = new HashMap<Integer, Set<GeoName>>();
for (Integer parentId : childMap.keySet()) {
// Lucene query used to look for exact match on the "geonameID" field
Query q = NumericRangeQuery.newIntRange(GEONAME_ID.key(), parentId, parentId, true, true);
TopDocs results = indexSearcher.search(q, null, 1, POPULATION_SORT);
if (results.scoreDocs.length > 0) {
Document doc = indexSearcher.doc(results.scoreDocs[0].doc);
GeoName parent = BasicGeoName.parseFromGeoNamesRecord(doc.get(GEONAME.key()), doc.get(PREFERRED_NAME.key()));
parentMap.put(parent.getGeonameID(), parent);
if (!parent.isAncestryResolved()) {
Integer grandParentId = PARENT_ID.getValue(doc);
if (grandParentId != null) {
Set<GeoName> geos = grandParentMap.get(grandParentId);
if (geos == null) {
geos = new HashSet<GeoName>();
grandParentMap.put(grandParentId, geos);
}
geos.add(parent);
}
}
} else {
LOG.error("Unable to find parent GeoName [{}]", parentId);
}
}
// find all parents of the parents
if (!grandParentMap.isEmpty()) {
resolveParents(grandParentMap);
}
// set parents of children
for (Integer parentId : childMap.keySet()) {
GeoName parent = parentMap.get(parentId);
if (parent == null) {
LOG.info("Unable to find parent with ID [{}]", parentId);
continue;
}
for (GeoName child : childMap.get(parentId)) {
child.setParent(parent);
}
}
} | [
"private",
"void",
"resolveParents",
"(",
"final",
"Map",
"<",
"Integer",
",",
"Set",
"<",
"GeoName",
">",
">",
"childMap",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"Integer",
",",
"GeoName",
">",
"parentMap",
"=",
"new",
"HashMap",
"<",
"Integer",
... | Retrieves and sets the parents of the provided children.
@param childMap the map of parent geonameID to the set of children that belong to it
@throws IOException if an error occurs during parent resolution | [
"Retrieves",
"and",
"sets",
"the",
"parents",
"of",
"the",
"provided",
"children",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/query/LuceneGazetteer.java#L396-L439 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/index/WhitespaceLowerCaseAnalyzer.java | WhitespaceLowerCaseAnalyzer.createComponents | @Override
protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
return new TokenStreamComponents(new WhitespaceLowerCaseTokenizer(matchVersion, reader));
} | java | @Override
protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
return new TokenStreamComponents(new WhitespaceLowerCaseTokenizer(matchVersion, reader));
} | [
"@",
"Override",
"protected",
"TokenStreamComponents",
"createComponents",
"(",
"final",
"String",
"fieldName",
",",
"final",
"Reader",
"reader",
")",
"{",
"return",
"new",
"TokenStreamComponents",
"(",
"new",
"WhitespaceLowerCaseTokenizer",
"(",
"matchVersion",
",",
... | Provides tokenizer access for the analyzer.
@param fieldName field to be tokenized
@param reader | [
"Provides",
"tokenizer",
"access",
"for",
"the",
"analyzer",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/index/WhitespaceLowerCaseAnalyzer.java#L60-L63 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/index/IndexDirectoryBuilder.java | IndexDirectoryBuilder.main | public static void main(String[] args) throws IOException {
Options options = getOptions();
CommandLine cmd = null;
CommandLineParser parser = new GnuParser();
try {
cmd = parser.parse(options, args);
} catch (ParseException pe) {
LOG.error(pe.getMessage());
printHelp(options);
System.exit(-1);
}
if (cmd.hasOption(HELP_OPTION)) {
printHelp(options);
System.exit(0);
}
String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY);
String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION);
if (gazetteerPaths == null || gazetteerPaths.length == 0) {
gazetteerPaths = DEFAULT_GAZETTEER_FILES;
}
boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION);
boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION);
File idir = new File(indexPath);
// if the index directory exists, delete it if we are replacing, otherwise
// exit gracefully
if (idir.exists() ) {
if (replaceIndex) {
LOG.info("Replacing index: {}", idir.getAbsolutePath());
FileUtils.deleteDirectory(idir);
} else {
LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath());
System.exit(-1);
}
}
List<File> gazetteerFiles = new ArrayList<File>();
for (String gp : gazetteerPaths) {
File gf = new File(gp);
if (gf.isFile() && gf.canRead()) {
gazetteerFiles.add(gf);
} else {
LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath());
}
}
if (gazetteerFiles.isEmpty()) {
LOG.error("No Gazetteer files found.");
System.exit(-1);
}
String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION);
File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null;
if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) {
LOG.error("Unable to read alternate names file: {}", altNamesPath);
System.exit(-1);
}
new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile);
} | java | public static void main(String[] args) throws IOException {
Options options = getOptions();
CommandLine cmd = null;
CommandLineParser parser = new GnuParser();
try {
cmd = parser.parse(options, args);
} catch (ParseException pe) {
LOG.error(pe.getMessage());
printHelp(options);
System.exit(-1);
}
if (cmd.hasOption(HELP_OPTION)) {
printHelp(options);
System.exit(0);
}
String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY);
String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION);
if (gazetteerPaths == null || gazetteerPaths.length == 0) {
gazetteerPaths = DEFAULT_GAZETTEER_FILES;
}
boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION);
boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION);
File idir = new File(indexPath);
// if the index directory exists, delete it if we are replacing, otherwise
// exit gracefully
if (idir.exists() ) {
if (replaceIndex) {
LOG.info("Replacing index: {}", idir.getAbsolutePath());
FileUtils.deleteDirectory(idir);
} else {
LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath());
System.exit(-1);
}
}
List<File> gazetteerFiles = new ArrayList<File>();
for (String gp : gazetteerPaths) {
File gf = new File(gp);
if (gf.isFile() && gf.canRead()) {
gazetteerFiles.add(gf);
} else {
LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath());
}
}
if (gazetteerFiles.isEmpty()) {
LOG.error("No Gazetteer files found.");
System.exit(-1);
}
String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION);
File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null;
if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) {
LOG.error("Unable to read alternate names file: {}", altNamesPath);
System.exit(-1);
}
new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile);
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"IOException",
"{",
"Options",
"options",
"=",
"getOptions",
"(",
")",
";",
"CommandLine",
"cmd",
"=",
"null",
";",
"CommandLineParser",
"parser",
"=",
"new",
"GnuParser",
... | Turns a GeoNames gazetteer file into a Lucene index, and adds
some supplementary gazetteer records at the end.
@param args not used
@throws IOException | [
"Turns",
"a",
"GeoNames",
"gazetteer",
"file",
"into",
"a",
"Lucene",
"index",
"and",
"adds",
"some",
"supplementary",
"gazetteer",
"records",
"at",
"the",
"end",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/index/IndexDirectoryBuilder.java#L504-L564 | train |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java | KontonummerValidator.isValid | public static boolean isValid(String kontonummer) {
try {
KontonummerValidator.getKontonummer(kontonummer);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} | java | public static boolean isValid(String kontonummer) {
try {
KontonummerValidator.getKontonummer(kontonummer);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} | [
"public",
"static",
"boolean",
"isValid",
"(",
"String",
"kontonummer",
")",
"{",
"try",
"{",
"KontonummerValidator",
".",
"getKontonummer",
"(",
"kontonummer",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"ret... | Return true if the provided String is a valid Kontonummmer.
@param kontonummer A String containing a Kontonummer
@return true or false | [
"Return",
"true",
"if",
"the",
"provided",
"String",
"is",
"a",
"valid",
"Kontonummmer",
"."
] | 5a576696390cecaac111fa97fde581e0c1afb9b8 | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java#L34-L41 | train |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java | KontonummerValidator.getKontonummer | public static Kontonummer getKontonummer(String kontonummer) throws IllegalArgumentException {
validateSyntax(kontonummer);
validateChecksum(kontonummer);
return new Kontonummer(kontonummer);
} | java | public static Kontonummer getKontonummer(String kontonummer) throws IllegalArgumentException {
validateSyntax(kontonummer);
validateChecksum(kontonummer);
return new Kontonummer(kontonummer);
} | [
"public",
"static",
"Kontonummer",
"getKontonummer",
"(",
"String",
"kontonummer",
")",
"throws",
"IllegalArgumentException",
"{",
"validateSyntax",
"(",
"kontonummer",
")",
";",
"validateChecksum",
"(",
"kontonummer",
")",
";",
"return",
"new",
"Kontonummer",
"(",
... | Returns an object that represents a Kontonummer.
@param kontonummer A String containing a Kontonummer
@return A Kontonummer instance
@throws IllegalArgumentException thrown if String contains an invalid Kontonummer | [
"Returns",
"an",
"object",
"that",
"represents",
"a",
"Kontonummer",
"."
] | 5a576696390cecaac111fa97fde581e0c1afb9b8 | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java#L50-L54 | train |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java | KontonummerValidator.getAndForceValidKontonummer | public static Kontonummer getAndForceValidKontonummer(String kontonummer) {
validateSyntax(kontonummer);
try {
validateChecksum(kontonummer);
} catch (IllegalArgumentException iae) {
Kontonummer k = new Kontonummer(kontonummer);
int checksum = calculateMod11CheckSum(getMod11Weights(k), k);
kontonummer = kontonummer.substring(0, LENGTH - 1) + checksum;
}
return new Kontonummer(kontonummer);
} | java | public static Kontonummer getAndForceValidKontonummer(String kontonummer) {
validateSyntax(kontonummer);
try {
validateChecksum(kontonummer);
} catch (IllegalArgumentException iae) {
Kontonummer k = new Kontonummer(kontonummer);
int checksum = calculateMod11CheckSum(getMod11Weights(k), k);
kontonummer = kontonummer.substring(0, LENGTH - 1) + checksum;
}
return new Kontonummer(kontonummer);
} | [
"public",
"static",
"Kontonummer",
"getAndForceValidKontonummer",
"(",
"String",
"kontonummer",
")",
"{",
"validateSyntax",
"(",
"kontonummer",
")",
";",
"try",
"{",
"validateChecksum",
"(",
"kontonummer",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"ia... | Returns an object that represents a Kontonummer. The checksum of the
supplied kontonummer is changed to a valid checksum if the original
kontonummer has an invalid checksum.
@param kontonummer A String containing a Kontonummer
@return A Kontonummer instance
@throws IllegalArgumentException thrown if String contains an invalid Kontonummer, ie. a
number which for one cannot calculate a valid checksum. | [
"Returns",
"an",
"object",
"that",
"represents",
"a",
"Kontonummer",
".",
"The",
"checksum",
"of",
"the",
"supplied",
"kontonummer",
"is",
"changed",
"to",
"a",
"valid",
"checksum",
"if",
"the",
"original",
"kontonummer",
"has",
"an",
"invalid",
"checksum",
".... | 5a576696390cecaac111fa97fde581e0c1afb9b8 | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/KontonummerValidator.java#L66-L76 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/resolver/ClavinLocationResolver.java | ClavinLocationResolver.pickBestCandidates | private List<ResolvedLocation> pickBestCandidates(final List<List<ResolvedLocation>> allCandidates) {
// initialize return object
List<ResolvedLocation> bestCandidates = new ArrayList<ResolvedLocation>();
// variables used in heuristic matching
Set<CountryCode> countries;
Set<String> states;
float score;
// initial values for variables controlling recursion
float newMaxScore = 0;
float oldMaxScore;
// controls window of Lucene hits for each location considered
// context-based heuristic matching, initialized as a "magic
// number" of *3* based on tests of the "Springfield Problem"
int candidateDepth = 3;
// keep searching deeper & deeper for better combinations of
// candidate matches, as long as the scores are improving
do {
// reset the threshold for recursion
oldMaxScore = newMaxScore;
// loop through all combinations up to the specified depth.
// first recursive call for each depth starts at index 0
for (List<ResolvedLocation> combo : generateAllCombos(allCandidates, 0, candidateDepth)) {
// these lists store the country codes & admin1 codes for each candidate
countries = EnumSet.noneOf(CountryCode.class);
states = new HashSet<String>();
for (ResolvedLocation location: combo) {
countries.add(location.getGeoname().getPrimaryCountryCode());
states.add(location.getGeoname().getPrimaryCountryCode() + location.getGeoname().getAdmin1Code());
}
// calculate a score for this particular combination based on commonality
// of country codes & admin1 codes, and the cost of searching this deep
// TODO: tune this score calculation!
score = ((float)allCandidates.size() / (countries.size() + states.size())) / candidateDepth;
/* ***********************************************************
* "So, at last we meet for the first time for the last time."
*
* The fact that you're interested enough in CLAVIN to be
* reading this means we're interested in talking with you.
*
* Are you looking for a job, or are you in need of a
* customized solution built around CLAVIN?
*
* Drop us a line at clavin@bericotechnologies.com
*
* "What's the matter, Colonel Sandurz? CHICKEN?"
* **********************************************************/
// if this is the best we've seen during this loop, update the return value
if (score > newMaxScore) {
newMaxScore = score;
bestCandidates = combo;
}
}
// search one level deeper in the next loop
candidateDepth++;
} while (newMaxScore > oldMaxScore);
// keep searching while the scores are monotonically increasing
return bestCandidates;
} | java | private List<ResolvedLocation> pickBestCandidates(final List<List<ResolvedLocation>> allCandidates) {
// initialize return object
List<ResolvedLocation> bestCandidates = new ArrayList<ResolvedLocation>();
// variables used in heuristic matching
Set<CountryCode> countries;
Set<String> states;
float score;
// initial values for variables controlling recursion
float newMaxScore = 0;
float oldMaxScore;
// controls window of Lucene hits for each location considered
// context-based heuristic matching, initialized as a "magic
// number" of *3* based on tests of the "Springfield Problem"
int candidateDepth = 3;
// keep searching deeper & deeper for better combinations of
// candidate matches, as long as the scores are improving
do {
// reset the threshold for recursion
oldMaxScore = newMaxScore;
// loop through all combinations up to the specified depth.
// first recursive call for each depth starts at index 0
for (List<ResolvedLocation> combo : generateAllCombos(allCandidates, 0, candidateDepth)) {
// these lists store the country codes & admin1 codes for each candidate
countries = EnumSet.noneOf(CountryCode.class);
states = new HashSet<String>();
for (ResolvedLocation location: combo) {
countries.add(location.getGeoname().getPrimaryCountryCode());
states.add(location.getGeoname().getPrimaryCountryCode() + location.getGeoname().getAdmin1Code());
}
// calculate a score for this particular combination based on commonality
// of country codes & admin1 codes, and the cost of searching this deep
// TODO: tune this score calculation!
score = ((float)allCandidates.size() / (countries.size() + states.size())) / candidateDepth;
/* ***********************************************************
* "So, at last we meet for the first time for the last time."
*
* The fact that you're interested enough in CLAVIN to be
* reading this means we're interested in talking with you.
*
* Are you looking for a job, or are you in need of a
* customized solution built around CLAVIN?
*
* Drop us a line at clavin@bericotechnologies.com
*
* "What's the matter, Colonel Sandurz? CHICKEN?"
* **********************************************************/
// if this is the best we've seen during this loop, update the return value
if (score > newMaxScore) {
newMaxScore = score;
bestCandidates = combo;
}
}
// search one level deeper in the next loop
candidateDepth++;
} while (newMaxScore > oldMaxScore);
// keep searching while the scores are monotonically increasing
return bestCandidates;
} | [
"private",
"List",
"<",
"ResolvedLocation",
">",
"pickBestCandidates",
"(",
"final",
"List",
"<",
"List",
"<",
"ResolvedLocation",
">",
">",
"allCandidates",
")",
"{",
"// initialize return object",
"List",
"<",
"ResolvedLocation",
">",
"bestCandidates",
"=",
"new",... | Uses heuristics to select the best match for each location name
extracted from a document, choosing from among a list of lists
of candidate matches.
Although not guaranteeing an optimal solution (enumerating &
evaluating each possible combination is too costly), it does a
decent job of cracking the "Springfield Problem" by selecting
candidates that would make sense to appear together based on
common country and admin1 codes (i.e., states or provinces).
For example, if we also see "Boston" mentioned in a document
that contains "Springfield," we'd use this as a clue that we
ought to choose Springfield, MA over Springfield, IL or
Springfield, MO.
TODO: consider lat/lon distance in addition to shared
CountryCodes and Admin1Codes.
@param allCandidates list of lists of candidate matches for locations names
@return list of best matches for each location name | [
"Uses",
"heuristics",
"to",
"select",
"the",
"best",
"match",
"for",
"each",
"location",
"name",
"extracted",
"from",
"a",
"document",
"choosing",
"from",
"among",
"a",
"list",
"of",
"lists",
"of",
"candidate",
"matches",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/resolver/ClavinLocationResolver.java#L264-L332 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/gazetteer/query/QueryBuilder.java | QueryBuilder.build | public GazetteerQuery build() {
return new GazetteerQuery(location, maxResults, fuzzyMode, ancestryMode, includeHistorical, filterDupes, parentIds, featureCodes);
} | java | public GazetteerQuery build() {
return new GazetteerQuery(location, maxResults, fuzzyMode, ancestryMode, includeHistorical, filterDupes, parentIds, featureCodes);
} | [
"public",
"GazetteerQuery",
"build",
"(",
")",
"{",
"return",
"new",
"GazetteerQuery",
"(",
"location",
",",
"maxResults",
",",
"fuzzyMode",
",",
"ancestryMode",
",",
"includeHistorical",
",",
"filterDupes",
",",
"parentIds",
",",
"featureCodes",
")",
";",
"}"
] | Constructs a query from the current configuration of this Builder.
@return a {@link GazetteerQuery} configuration object | [
"Constructs",
"a",
"query",
"from",
"the",
"current",
"configuration",
"of",
"this",
"Builder",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/query/QueryBuilder.java#L124-L126 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/util/DamerauLevenshtein.java | DamerauLevenshtein.isEditDistance1 | public static boolean isEditDistance1(String str1, String str2) {
// one or both strings is empty or null
if ((str1 == null) || str1.isEmpty()) {
if ((str2 == null) || str2.isEmpty()) {
return true;
} else {
return (str2.length() <= 1);
}
} else if ((str2 == null) || str2.isEmpty()) {
return (str1.length() <= 1);
}
// difference between string lengths ensures edit distance > bound
if (Math.abs(str1.length() - str2.length()) > 1) return false;
// initialize counters
int offset1 = 0;
int offset2 = 0;
int i = 0;
InfiniteCharArray chars1 = new InfiniteCharArray(str1.toCharArray());
InfiniteCharArray chars2 = new InfiniteCharArray(str2.toCharArray());
while (!chars1.get(i + offset1).equals(endMarker) || !chars2.get(i + offset2).equals(endMarker)) {
if (!chars1.get(i + offset1).equals(chars2.get(i + offset2))) { // character mismatch
if ((chars1.get(i + offset1).equals(chars2.get(i + offset2 + 1))) &&
(chars1.get(i + offset1 + 1).equals(chars2.get(i + offset2))) &&
(chars1.remainder(i + offset1 + 2).equals(chars2.remainder(i + offset2 + 2)))) { // transposition
i = i + 2; // move past the transposition
} else if (chars1.remainder(i + offset1).equals(chars2.remainder(i + offset2 + 1))) { // insertion
offset2++; // realign
} else if (chars1.remainder(i + offset1 + 1).equals(chars2.remainder(i + offset2))) { // deletion
offset1++; // realign
} else if (chars1.remainder(i + offset1 + 1).equals(chars2.remainder(i + offset2 + 1))) { // substitution
i++; //
} else return false; // multiple edits
}
i++;
}
return true;
} | java | public static boolean isEditDistance1(String str1, String str2) {
// one or both strings is empty or null
if ((str1 == null) || str1.isEmpty()) {
if ((str2 == null) || str2.isEmpty()) {
return true;
} else {
return (str2.length() <= 1);
}
} else if ((str2 == null) || str2.isEmpty()) {
return (str1.length() <= 1);
}
// difference between string lengths ensures edit distance > bound
if (Math.abs(str1.length() - str2.length()) > 1) return false;
// initialize counters
int offset1 = 0;
int offset2 = 0;
int i = 0;
InfiniteCharArray chars1 = new InfiniteCharArray(str1.toCharArray());
InfiniteCharArray chars2 = new InfiniteCharArray(str2.toCharArray());
while (!chars1.get(i + offset1).equals(endMarker) || !chars2.get(i + offset2).equals(endMarker)) {
if (!chars1.get(i + offset1).equals(chars2.get(i + offset2))) { // character mismatch
if ((chars1.get(i + offset1).equals(chars2.get(i + offset2 + 1))) &&
(chars1.get(i + offset1 + 1).equals(chars2.get(i + offset2))) &&
(chars1.remainder(i + offset1 + 2).equals(chars2.remainder(i + offset2 + 2)))) { // transposition
i = i + 2; // move past the transposition
} else if (chars1.remainder(i + offset1).equals(chars2.remainder(i + offset2 + 1))) { // insertion
offset2++; // realign
} else if (chars1.remainder(i + offset1 + 1).equals(chars2.remainder(i + offset2))) { // deletion
offset1++; // realign
} else if (chars1.remainder(i + offset1 + 1).equals(chars2.remainder(i + offset2 + 1))) { // substitution
i++; //
} else return false; // multiple edits
}
i++;
}
return true;
} | [
"public",
"static",
"boolean",
"isEditDistance1",
"(",
"String",
"str1",
",",
"String",
"str2",
")",
"{",
"// one or both strings is empty or null",
"if",
"(",
"(",
"str1",
"==",
"null",
")",
"||",
"str1",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"("... | Fast method for determining whether the Damerau-Levenshtein edit
distance between two strings is less than 2.
Returns as quick as possibly by stopping once multiple edits are
found. Significantly faster than {@link #damerauLevenshteinDistance(String str1, String str2)}
which explores every path between every string to get the exact
edit distance. Despite the speed boost, we maintain consistency
with {@link #damerauLevenshteinDistance(String str1, String str2)}.
@param str1 First string being compared
@param str2 Second string being compared
@return True if DL edit distance < 2, false otherwise | [
"Fast",
"method",
"for",
"determining",
"whether",
"the",
"Damerau",
"-",
"Levenshtein",
"edit",
"distance",
"between",
"two",
"strings",
"is",
"less",
"than",
"2",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/util/DamerauLevenshtein.java#L143-L185 | train |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/util/DamerauLevenshtein.java | InfiniteCharArray.remainder | protected String remainder(int index) {
if (index > this.array.length)
return "";
else return new String(Arrays.copyOfRange(this.array, index, this.array.length));
} | java | protected String remainder(int index) {
if (index > this.array.length)
return "";
else return new String(Arrays.copyOfRange(this.array, index, this.array.length));
} | [
"protected",
"String",
"remainder",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"index",
">",
"this",
".",
"array",
".",
"length",
")",
"return",
"\"\"",
";",
"else",
"return",
"new",
"String",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"this",
".",
"array"... | Get the contents of the char array to the right of the given
index, and return it as a String.
@param index left bound of the string we're pulling from the char array
@return a string representing everything to the right of the index | [
"Get",
"the",
"contents",
"of",
"the",
"char",
"array",
"to",
"the",
"right",
"of",
"the",
"given",
"index",
"and",
"return",
"it",
"as",
"a",
"String",
"."
] | f73c741f33a01b91aa5b06e71860bc354ef3010d | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/util/DamerauLevenshtein.java#L230-L234 | train |
psjava/psjava | src/main/java/org/psjava/algo/PermutationWithRepetitionIterable.java | PermutationWithRepetitionIterable.create | public static <T> Iterable<PSArray<T>> create(Iterable<T> items, final Comparator<T> comparator) {
MutableArray<T> initial = MutableArrayFromIterable.create(items);
GoodSortingAlgorithm.getInstance().sort(initial, comparator);
return IterableUsingStatusUpdater.create(initial, new Updater<PSArray<T>>() {
@Override
public PSArray<T> getUpdatedOrNull(PSArray<T> current) {
MutableArray<T> next = MutableArrayFromIterable.create(current);
boolean success = NextPermutation.step(next, comparator);
return success ? next : null;
}
});
} | java | public static <T> Iterable<PSArray<T>> create(Iterable<T> items, final Comparator<T> comparator) {
MutableArray<T> initial = MutableArrayFromIterable.create(items);
GoodSortingAlgorithm.getInstance().sort(initial, comparator);
return IterableUsingStatusUpdater.create(initial, new Updater<PSArray<T>>() {
@Override
public PSArray<T> getUpdatedOrNull(PSArray<T> current) {
MutableArray<T> next = MutableArrayFromIterable.create(current);
boolean success = NextPermutation.step(next, comparator);
return success ? next : null;
}
});
} | [
"public",
"static",
"<",
"T",
">",
"Iterable",
"<",
"PSArray",
"<",
"T",
">",
">",
"create",
"(",
"Iterable",
"<",
"T",
">",
"items",
",",
"final",
"Comparator",
"<",
"T",
">",
"comparator",
")",
"{",
"MutableArray",
"<",
"T",
">",
"initial",
"=",
... | SRM464-1-250 is a good problem to solve using this. | [
"SRM464",
"-",
"1",
"-",
"250",
"is",
"a",
"good",
"problem",
"to",
"solve",
"using",
"this",
"."
] | 6a160e385fad340109eca00e3a9042071b1eea1e | https://github.com/psjava/psjava/blob/6a160e385fad340109eca00e3a9042071b1eea1e/src/main/java/org/psjava/algo/PermutationWithRepetitionIterable.java#L17-L28 | train |
psjava/psjava | src/main/java/org/psjava/algo/graph/dfs/AllSourceDFS.java | AllSourceDFS.traverse | public static <V, E extends DirectedEdge<V>> void traverse(Graph<V, E> graph, DFSVisitor<V, E> visitor) {
MultiSourceDFS.traverse(graph, graph.getVertices(), visitor);
} | java | public static <V, E extends DirectedEdge<V>> void traverse(Graph<V, E> graph, DFSVisitor<V, E> visitor) {
MultiSourceDFS.traverse(graph, graph.getVertices(), visitor);
} | [
"public",
"static",
"<",
"V",
",",
"E",
"extends",
"DirectedEdge",
"<",
"V",
">",
">",
"void",
"traverse",
"(",
"Graph",
"<",
"V",
",",
"E",
">",
"graph",
",",
"DFSVisitor",
"<",
"V",
",",
"E",
">",
"visitor",
")",
"{",
"MultiSourceDFS",
".",
"trav... | Remember that visiting order is not ordered. | [
"Remember",
"that",
"visiting",
"order",
"is",
"not",
"ordered",
"."
] | 6a160e385fad340109eca00e3a9042071b1eea1e | https://github.com/psjava/psjava/blob/6a160e385fad340109eca00e3a9042071b1eea1e/src/main/java/org/psjava/algo/graph/dfs/AllSourceDFS.java#L11-L13 | train |
psjava/psjava | src/main/java/org/psjava/algo/geometry/convexhull/DivideAndConquerConvexHull.java | DivideAndConquerConvexHull.findBridgeIndexes | private static <T> IntPair findBridgeIndexes(PSArray<Point2D<T>> earlyHull, PSArray<Point2D<T>> laterHull, int earlyStart, int laterStart, MultipliableNumberSystem<T> ns) {
int early = earlyStart;
int later = laterStart;
while (true) {
int nextEarly = getPreIndex(early, earlyHull.size());
int nextLater = getNextIndex(later, laterHull.size());
if (LeftTurn.is(laterHull.get(later), earlyHull.get(early), earlyHull.get(nextEarly), ns))
early = nextEarly;
else if (RightTurn.is(earlyHull.get(early), laterHull.get(later), laterHull.get(nextLater), ns))
later = nextLater;
else
break;
}
return new IntPair(early, later);
} | java | private static <T> IntPair findBridgeIndexes(PSArray<Point2D<T>> earlyHull, PSArray<Point2D<T>> laterHull, int earlyStart, int laterStart, MultipliableNumberSystem<T> ns) {
int early = earlyStart;
int later = laterStart;
while (true) {
int nextEarly = getPreIndex(early, earlyHull.size());
int nextLater = getNextIndex(later, laterHull.size());
if (LeftTurn.is(laterHull.get(later), earlyHull.get(early), earlyHull.get(nextEarly), ns))
early = nextEarly;
else if (RightTurn.is(earlyHull.get(early), laterHull.get(later), laterHull.get(nextLater), ns))
later = nextLater;
else
break;
}
return new IntPair(early, later);
} | [
"private",
"static",
"<",
"T",
">",
"IntPair",
"findBridgeIndexes",
"(",
"PSArray",
"<",
"Point2D",
"<",
"T",
">",
">",
"earlyHull",
",",
"PSArray",
"<",
"Point2D",
"<",
"T",
">",
">",
"laterHull",
",",
"int",
"earlyStart",
",",
"int",
"laterStart",
",",... | early, later are ordered by ccw order. | [
"early",
"later",
"are",
"ordered",
"by",
"ccw",
"order",
"."
] | 6a160e385fad340109eca00e3a9042071b1eea1e | https://github.com/psjava/psjava/blob/6a160e385fad340109eca00e3a9042071b1eea1e/src/main/java/org/psjava/algo/geometry/convexhull/DivideAndConquerConvexHull.java#L75-L89 | train |
psjava/psjava | src/main/java/org/psjava/ds/tree/trie/TrieNodeFactoryForBooleanKey.java | TrieNodeFactoryForBooleanKey.getInstance | public static TrieNodeFactory<Boolean> getInstance() {
return new TrieNodeFactory<Boolean>() {
@Override
public TrieNode<Boolean> create() {
return new BooleanTrieNode();
}
};
} | java | public static TrieNodeFactory<Boolean> getInstance() {
return new TrieNodeFactory<Boolean>() {
@Override
public TrieNode<Boolean> create() {
return new BooleanTrieNode();
}
};
} | [
"public",
"static",
"TrieNodeFactory",
"<",
"Boolean",
">",
"getInstance",
"(",
")",
"{",
"return",
"new",
"TrieNodeFactory",
"<",
"Boolean",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"TrieNode",
"<",
"Boolean",
">",
"create",
"(",
")",
"{",
"return",... | specialized in speed for boolean keyed nodes. | [
"specialized",
"in",
"speed",
"for",
"boolean",
"keyed",
"nodes",
"."
] | 6a160e385fad340109eca00e3a9042071b1eea1e | https://github.com/psjava/psjava/blob/6a160e385fad340109eca00e3a9042071b1eea1e/src/main/java/org/psjava/ds/tree/trie/TrieNodeFactoryForBooleanKey.java#L10-L17 | train |
greenlaw110/play-excel | src/play/modules/excel/Excel.java | Excel.renderTemplateAsExcel | public static void renderTemplateAsExcel(String templateName, Object... args) {
// Template datas
Scope.RenderArgs templateBinding = Scope.RenderArgs.current();
for (Object o : args) {
List<String> names = LocalvariablesNamesEnhancer.LocalVariablesNamesTracer
.getAllLocalVariableNames(o);
for (String name : names) {
templateBinding.put(name, o);
}
}
templateBinding.put("session", Scope.Session.current());
templateBinding.put("request", Http.Request.current());
templateBinding.put("flash", Scope.Flash.current());
templateBinding.put("params", Scope.Params.current());
if (null == templateBinding.get("fileName")) {
templateBinding.put("fileName", templateName.substring(templateName.lastIndexOf("/") + 1) + ".xls");
}
//Logger.trace("fileName: " + templateBinding.get("fileName"));
try {
templateBinding.put("errors", Validation.errors());
} catch (Exception ex) {
throw new UnexpectedException(ex);
}
try {
throw new RenderExcelTemplate(templateName + ".xls", templateBinding.data, templateBinding.get("fileName").toString());
} catch (TemplateNotFoundException ex) {
if (ex.isSourceAvailable()) {
throw ex;
}
StackTraceElement element = PlayException
.getInterestingStrackTraceElement(ex);
if (element != null) {
throw new TemplateNotFoundException(templateName, Play.classes
.getApplicationClass(element.getClassName()), element
.getLineNumber());
} else {
throw ex;
}
}
} | java | public static void renderTemplateAsExcel(String templateName, Object... args) {
// Template datas
Scope.RenderArgs templateBinding = Scope.RenderArgs.current();
for (Object o : args) {
List<String> names = LocalvariablesNamesEnhancer.LocalVariablesNamesTracer
.getAllLocalVariableNames(o);
for (String name : names) {
templateBinding.put(name, o);
}
}
templateBinding.put("session", Scope.Session.current());
templateBinding.put("request", Http.Request.current());
templateBinding.put("flash", Scope.Flash.current());
templateBinding.put("params", Scope.Params.current());
if (null == templateBinding.get("fileName")) {
templateBinding.put("fileName", templateName.substring(templateName.lastIndexOf("/") + 1) + ".xls");
}
//Logger.trace("fileName: " + templateBinding.get("fileName"));
try {
templateBinding.put("errors", Validation.errors());
} catch (Exception ex) {
throw new UnexpectedException(ex);
}
try {
throw new RenderExcelTemplate(templateName + ".xls", templateBinding.data, templateBinding.get("fileName").toString());
} catch (TemplateNotFoundException ex) {
if (ex.isSourceAvailable()) {
throw ex;
}
StackTraceElement element = PlayException
.getInterestingStrackTraceElement(ex);
if (element != null) {
throw new TemplateNotFoundException(templateName, Play.classes
.getApplicationClass(element.getClassName()), element
.getLineNumber());
} else {
throw ex;
}
}
} | [
"public",
"static",
"void",
"renderTemplateAsExcel",
"(",
"String",
"templateName",
",",
"Object",
"...",
"args",
")",
"{",
"// Template datas",
"Scope",
".",
"RenderArgs",
"templateBinding",
"=",
"Scope",
".",
"RenderArgs",
".",
"current",
"(",
")",
";",
"for",... | Render a specific template
@param templateName
The template name
@param args
The template data | [
"Render",
"a",
"specific",
"template"
] | 6bf18419a52213d06787308c52cb70bfebcac3ab | https://github.com/greenlaw110/play-excel/blob/6bf18419a52213d06787308c52cb70bfebcac3ab/src/play/modules/excel/Excel.java#L48-L88 | train |
greenlaw110/play-excel | src/play/modules/excel/Excel.java | Excel.renderExcel | public static void renderExcel(Object... args) {
String templateName = null;
final Http.Request request = Http.Request.current();
if (args.length > 0
&& args[0] instanceof String
&& LocalvariablesNamesEnhancer.LocalVariablesNamesTracer
.getAllLocalVariableNames(args[0]).isEmpty()) {
templateName = args[0].toString();
} else {
templateName = request.action.replace(".", "/");
}
if (templateName.startsWith("@")) {
templateName = templateName.substring(1);
if (!templateName.contains(".")) {
templateName = request.controller + "." + templateName;
}
templateName = templateName.replace(".", "/");
}
renderTemplateAsExcel(templateName, args);
} | java | public static void renderExcel(Object... args) {
String templateName = null;
final Http.Request request = Http.Request.current();
if (args.length > 0
&& args[0] instanceof String
&& LocalvariablesNamesEnhancer.LocalVariablesNamesTracer
.getAllLocalVariableNames(args[0]).isEmpty()) {
templateName = args[0].toString();
} else {
templateName = request.action.replace(".", "/");
}
if (templateName.startsWith("@")) {
templateName = templateName.substring(1);
if (!templateName.contains(".")) {
templateName = request.controller + "." + templateName;
}
templateName = templateName.replace(".", "/");
}
renderTemplateAsExcel(templateName, args);
} | [
"public",
"static",
"void",
"renderExcel",
"(",
"Object",
"...",
"args",
")",
"{",
"String",
"templateName",
"=",
"null",
";",
"final",
"Http",
".",
"Request",
"request",
"=",
"Http",
".",
"Request",
".",
"current",
"(",
")",
";",
"if",
"(",
"args",
".... | Render the corresponding template
@param args
The template data | [
"Render",
"the",
"corresponding",
"template"
] | 6bf18419a52213d06787308c52cb70bfebcac3ab | https://github.com/greenlaw110/play-excel/blob/6bf18419a52213d06787308c52cb70bfebcac3ab/src/play/modules/excel/Excel.java#L96-L116 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/numbers/NumberFormattingUtils.java | NumberFormattingUtils.setup | public static BigDecimal setup(
BigDecimal n, // number to be formatted
NumberRoundMode roundMode, // rounding mode
NumberFormatMode formatMode, // formatting mode (significant digits, etc)
int minIntDigits, // maximum integer digits to emit
int maxFracDigits, // maximum fractional digits to emit
int minFracDigits, // minimum fractional digits to emit
int maxSigDigits, // maximum significant digits to emit
int minSigDigits) { // minimum significant digits to emit
RoundingMode mode = roundMode.toRoundingMode();
boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC;
// Select "significant digits" or "integer/fraction digits" mode
if (useSignificant && minSigDigits > 0 && maxSigDigits > 0) {
// Scale the number to have at most the maximum significant digits.
if (n.precision() > maxSigDigits) {
int scale = maxSigDigits - n.precision() + n.scale();
n = n.setScale(scale, mode);
}
// Ensure we don't exceed the maximum number of fraction digits allowed.
if (formatMode == NumberFormatMode.SIGNIFICANT_MAXFRAC && maxFracDigits < n.scale()) {
n = n.setScale(maxFracDigits, mode);
}
// Ensure that one less digit is emitted if the number is exactly zero.
n = n.stripTrailingZeros();
boolean zero = n.signum() == 0;
int precision = n.precision();
if (zero && n.scale() == 1) {
precision--;
}
// Scale the number to have at least the minimum significant digits.
if (precision < minSigDigits) {
int scale = minSigDigits - precision + n.scale();
n = n.setScale(scale, mode);
}
} else {
// This mode provides precise control over the number of integer and fractional
// digits to include in the result, e.g. when formatting exact currency values.
int scale = Math.max(minFracDigits, Math.min(n.scale(), maxFracDigits));
n = n.setScale(scale, mode);
n = n.stripTrailingZeros();
// Ensure minimum fraction digits is met, even if it means outputting trailing zeros
if (n.scale() < minFracDigits) {
n = n.setScale(minFracDigits, mode);
}
}
return n;
} | java | public static BigDecimal setup(
BigDecimal n, // number to be formatted
NumberRoundMode roundMode, // rounding mode
NumberFormatMode formatMode, // formatting mode (significant digits, etc)
int minIntDigits, // maximum integer digits to emit
int maxFracDigits, // maximum fractional digits to emit
int minFracDigits, // minimum fractional digits to emit
int maxSigDigits, // maximum significant digits to emit
int minSigDigits) { // minimum significant digits to emit
RoundingMode mode = roundMode.toRoundingMode();
boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC;
// Select "significant digits" or "integer/fraction digits" mode
if (useSignificant && minSigDigits > 0 && maxSigDigits > 0) {
// Scale the number to have at most the maximum significant digits.
if (n.precision() > maxSigDigits) {
int scale = maxSigDigits - n.precision() + n.scale();
n = n.setScale(scale, mode);
}
// Ensure we don't exceed the maximum number of fraction digits allowed.
if (formatMode == NumberFormatMode.SIGNIFICANT_MAXFRAC && maxFracDigits < n.scale()) {
n = n.setScale(maxFracDigits, mode);
}
// Ensure that one less digit is emitted if the number is exactly zero.
n = n.stripTrailingZeros();
boolean zero = n.signum() == 0;
int precision = n.precision();
if (zero && n.scale() == 1) {
precision--;
}
// Scale the number to have at least the minimum significant digits.
if (precision < minSigDigits) {
int scale = minSigDigits - precision + n.scale();
n = n.setScale(scale, mode);
}
} else {
// This mode provides precise control over the number of integer and fractional
// digits to include in the result, e.g. when formatting exact currency values.
int scale = Math.max(minFracDigits, Math.min(n.scale(), maxFracDigits));
n = n.setScale(scale, mode);
n = n.stripTrailingZeros();
// Ensure minimum fraction digits is met, even if it means outputting trailing zeros
if (n.scale() < minFracDigits) {
n = n.setScale(minFracDigits, mode);
}
}
return n;
} | [
"public",
"static",
"BigDecimal",
"setup",
"(",
"BigDecimal",
"n",
",",
"// number to be formatted",
"NumberRoundMode",
"roundMode",
",",
"// rounding mode",
"NumberFormatMode",
"formatMode",
",",
"// formatting mode (significant digits, etc)",
"int",
"minIntDigits",
",",
"//... | Calculates the number of integer and fractional digits to emit, returning
them in a 2-element array, and updates the operands.
In one of the two significant digit modes, SIGNIFICANT and SIGNIFICANT_MAXFRAC,
a min/max number significant digits will be emitted. This is useful for formatting
compact formats where the width of the final output is constrained to <= N chars.
For example, with the settings minSigDigits=1 and maxSigDigits=2, and a format
pattern "0K", the value 1000 would produce "1K", the values 1200 and 1234 would
produce "1.2K", and 1599 would produce "1.6K". | [
"Calculates",
"the",
"number",
"of",
"integer",
"and",
"fractional",
"digits",
"to",
"emit",
"returning",
"them",
"in",
"a",
"2",
"-",
"element",
"array",
"and",
"updates",
"the",
"operands",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberFormattingUtils.java#L34-L89 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/numbers/NumberFormattingUtils.java | NumberFormattingUtils.format | public static void format(
BigDecimal n,
DigitBuffer buf,
NumberFormatterParams params,
boolean currencyMode,
boolean grouping,
int minIntDigits,
int primaryGroupingSize,
int secondaryGroupingSize) {
// Setup integer digit grouping.
if (secondaryGroupingSize <= 0) {
secondaryGroupingSize = primaryGroupingSize;
}
// Check if we need to perform digit grouping.
int groupSize = primaryGroupingSize;
boolean shouldGroup = false;
// Output as many integer digits as are available, unless minIntDigits == 0
// and our value is < 1.
long intDigits = integerDigits(n);
if (minIntDigits == 0 && n.compareTo(BigDecimal.ONE) == -1) {
intDigits = 0;
} else {
intDigits = Math.max(intDigits, minIntDigits);
}
if (grouping) {
if (primaryGroupingSize > 0) {
shouldGroup = intDigits >= (params.minimumGroupingDigits + primaryGroupingSize);
}
}
// Select the decimal and grouping characters.
String decimal = currencyMode ? params.currencyDecimal : params.decimal;
String group = currencyMode ? params.currencyGroup : params.group;
// Keep a pointer to the end of the buffer, since we render the formatted number
// in reverse to be a bit more compact.
int bufferStart = buf.length();
// We only emit the absolute value of the number, since the indication of
// negative numbers is pattern and locale-specific.
if (n.signum() == -1) {
n = n.negate();
}
// Translate the standard decimal representation into the localized form.
// At this point the number of integer and decimal digits is set, all we're
// doing is outputting the correct decimal symbol and grouping symbols.
String s = n.toPlainString();
int end = s.length() - 1;
// Emit decimal digits and decimal point.
int idx = s.lastIndexOf('.');
if (idx != -1) {
while (end > idx) {
buf.append(s.charAt(end));
end--;
}
end--;
buf.append(decimal);
}
// Emit integer part with optional grouping
int emitted = 0;
while (intDigits > 0 && end >= 0) {
// Emit grouping digits.
if (shouldGroup) {
boolean emit = emitted > 0 && emitted % groupSize == 0;
if (emit) {
// Append a grouping character and switch to the secondary grouping size
buf.append(group);
emitted -= groupSize;
groupSize = secondaryGroupingSize;
}
}
buf.append(s.charAt(end));
end--;
emitted++;
intDigits--;
}
// Emit zeroes to pad integer part with optional grouping
if (intDigits > 0) {
for (int i = 0; i < intDigits; i++) {
// Emit grouping digits.
if (shouldGroup) {
boolean emit = emitted > 0 && emitted % groupSize == 0;
if (emit) {
// Append a grouping character and switch to the secondary grouping size
buf.append(group);
emitted -= groupSize;
groupSize = secondaryGroupingSize;
}
}
buf.append('0');
emitted++;
}
}
buf.reverse(bufferStart);
} | java | public static void format(
BigDecimal n,
DigitBuffer buf,
NumberFormatterParams params,
boolean currencyMode,
boolean grouping,
int minIntDigits,
int primaryGroupingSize,
int secondaryGroupingSize) {
// Setup integer digit grouping.
if (secondaryGroupingSize <= 0) {
secondaryGroupingSize = primaryGroupingSize;
}
// Check if we need to perform digit grouping.
int groupSize = primaryGroupingSize;
boolean shouldGroup = false;
// Output as many integer digits as are available, unless minIntDigits == 0
// and our value is < 1.
long intDigits = integerDigits(n);
if (minIntDigits == 0 && n.compareTo(BigDecimal.ONE) == -1) {
intDigits = 0;
} else {
intDigits = Math.max(intDigits, minIntDigits);
}
if (grouping) {
if (primaryGroupingSize > 0) {
shouldGroup = intDigits >= (params.minimumGroupingDigits + primaryGroupingSize);
}
}
// Select the decimal and grouping characters.
String decimal = currencyMode ? params.currencyDecimal : params.decimal;
String group = currencyMode ? params.currencyGroup : params.group;
// Keep a pointer to the end of the buffer, since we render the formatted number
// in reverse to be a bit more compact.
int bufferStart = buf.length();
// We only emit the absolute value of the number, since the indication of
// negative numbers is pattern and locale-specific.
if (n.signum() == -1) {
n = n.negate();
}
// Translate the standard decimal representation into the localized form.
// At this point the number of integer and decimal digits is set, all we're
// doing is outputting the correct decimal symbol and grouping symbols.
String s = n.toPlainString();
int end = s.length() - 1;
// Emit decimal digits and decimal point.
int idx = s.lastIndexOf('.');
if (idx != -1) {
while (end > idx) {
buf.append(s.charAt(end));
end--;
}
end--;
buf.append(decimal);
}
// Emit integer part with optional grouping
int emitted = 0;
while (intDigits > 0 && end >= 0) {
// Emit grouping digits.
if (shouldGroup) {
boolean emit = emitted > 0 && emitted % groupSize == 0;
if (emit) {
// Append a grouping character and switch to the secondary grouping size
buf.append(group);
emitted -= groupSize;
groupSize = secondaryGroupingSize;
}
}
buf.append(s.charAt(end));
end--;
emitted++;
intDigits--;
}
// Emit zeroes to pad integer part with optional grouping
if (intDigits > 0) {
for (int i = 0; i < intDigits; i++) {
// Emit grouping digits.
if (shouldGroup) {
boolean emit = emitted > 0 && emitted % groupSize == 0;
if (emit) {
// Append a grouping character and switch to the secondary grouping size
buf.append(group);
emitted -= groupSize;
groupSize = secondaryGroupingSize;
}
}
buf.append('0');
emitted++;
}
}
buf.reverse(bufferStart);
} | [
"public",
"static",
"void",
"format",
"(",
"BigDecimal",
"n",
",",
"DigitBuffer",
"buf",
",",
"NumberFormatterParams",
"params",
",",
"boolean",
"currencyMode",
",",
"boolean",
"grouping",
",",
"int",
"minIntDigits",
",",
"int",
"primaryGroupingSize",
",",
"int",
... | Formats the number into the digit buffer. | [
"Formats",
"the",
"number",
"into",
"the",
"digit",
"buffer",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberFormattingUtils.java#L94-L199 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/DistanceTable.java | DistanceTable.distance | public int distance(CLDR.Locale desired, CLDR.Locale supported) {
return distance(desired, supported, DEFAULT_THRESHOLD);
} | java | public int distance(CLDR.Locale desired, CLDR.Locale supported) {
return distance(desired, supported, DEFAULT_THRESHOLD);
} | [
"public",
"int",
"distance",
"(",
"CLDR",
".",
"Locale",
"desired",
",",
"CLDR",
".",
"Locale",
"supported",
")",
"{",
"return",
"distance",
"(",
"desired",
",",
"supported",
",",
"DEFAULT_THRESHOLD",
")",
";",
"}"
] | Returns the distance between the desired and supported locale, using the
default distance threshold. | [
"Returns",
"the",
"distance",
"between",
"the",
"desired",
"and",
"supported",
"locale",
"using",
"the",
"default",
"distance",
"threshold",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/DistanceTable.java#L86-L88 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/DistanceTable.java | DistanceTable.distance | public int distance(CLDR.Locale desired, CLDR.Locale supported, int threshold) {
// Query the top level LANGUAGE
boolean langEquals = desired.language().equals(supported.language());
Node node = distanceMap.get(desired.language(), supported.language());
if (node == null) {
node = distanceMap.get(ANY, ANY);
}
int distance = node.wildcard() ? (langEquals ? 0 : node.distance()) : node.distance();
if (distance >= threshold) {
return MAX_DISTANCE;
}
// Go to the next level SCRIPT
DistanceMap map = node.map();
boolean scriptEquals = desired.script().equals(supported.script());
node = map.get(desired.script(), supported.script());
if (node == null) {
node = map.get(ANY, ANY);
}
distance += node.wildcard() ? (scriptEquals ? 0 : node.distance()) : node.distance();
if (distance >= threshold) {
return MAX_DISTANCE;
}
// Go to the next level TERRITORY
map = node.map();
// If the territories happen to be equal, distance is 0 so we're done.
if (desired.territory().equals(supported.territory())) {
return distance;
}
// Check if the map contains a distance between these two regions.
node = map.get(desired.territory(), supported.territory());
if (node == null) {
// Compare the desired region against supported partitions, and vice-versa.
node = scanTerritory(map, desired.territory(), supported.territory());
}
if (node != null) {
distance += node.distance();
return distance < threshold ? distance : MAX_DISTANCE;
}
// Find the maximum distance between the partitions.
int maxDistance = 0;
// These partition sets are always guaranteed to exist and contain at least 1 member.
boolean match = false;
Set<String> desiredPartitions = PARTITION_TABLE.getRegionPartition(desired.territory());
Set<String> supportedPartitions = PARTITION_TABLE.getRegionPartition(supported.territory());
for (String desiredPartition : desiredPartitions) {
for (String supportedPartition : supportedPartitions) {
node = map.get(desiredPartition, supportedPartition);
if (node != null) {
maxDistance = Math.max(maxDistance, node.distance());
match = true;
}
}
}
if (!match) {
node = map.get(ANY, ANY);
maxDistance = Math.max(maxDistance, node.distance());
}
distance += maxDistance;
return distance < threshold ? distance : MAX_DISTANCE;
} | java | public int distance(CLDR.Locale desired, CLDR.Locale supported, int threshold) {
// Query the top level LANGUAGE
boolean langEquals = desired.language().equals(supported.language());
Node node = distanceMap.get(desired.language(), supported.language());
if (node == null) {
node = distanceMap.get(ANY, ANY);
}
int distance = node.wildcard() ? (langEquals ? 0 : node.distance()) : node.distance();
if (distance >= threshold) {
return MAX_DISTANCE;
}
// Go to the next level SCRIPT
DistanceMap map = node.map();
boolean scriptEquals = desired.script().equals(supported.script());
node = map.get(desired.script(), supported.script());
if (node == null) {
node = map.get(ANY, ANY);
}
distance += node.wildcard() ? (scriptEquals ? 0 : node.distance()) : node.distance();
if (distance >= threshold) {
return MAX_DISTANCE;
}
// Go to the next level TERRITORY
map = node.map();
// If the territories happen to be equal, distance is 0 so we're done.
if (desired.territory().equals(supported.territory())) {
return distance;
}
// Check if the map contains a distance between these two regions.
node = map.get(desired.territory(), supported.territory());
if (node == null) {
// Compare the desired region against supported partitions, and vice-versa.
node = scanTerritory(map, desired.territory(), supported.territory());
}
if (node != null) {
distance += node.distance();
return distance < threshold ? distance : MAX_DISTANCE;
}
// Find the maximum distance between the partitions.
int maxDistance = 0;
// These partition sets are always guaranteed to exist and contain at least 1 member.
boolean match = false;
Set<String> desiredPartitions = PARTITION_TABLE.getRegionPartition(desired.territory());
Set<String> supportedPartitions = PARTITION_TABLE.getRegionPartition(supported.territory());
for (String desiredPartition : desiredPartitions) {
for (String supportedPartition : supportedPartitions) {
node = map.get(desiredPartition, supportedPartition);
if (node != null) {
maxDistance = Math.max(maxDistance, node.distance());
match = true;
}
}
}
if (!match) {
node = map.get(ANY, ANY);
maxDistance = Math.max(maxDistance, node.distance());
}
distance += maxDistance;
return distance < threshold ? distance : MAX_DISTANCE;
} | [
"public",
"int",
"distance",
"(",
"CLDR",
".",
"Locale",
"desired",
",",
"CLDR",
".",
"Locale",
"supported",
",",
"int",
"threshold",
")",
"{",
"// Query the top level LANGUAGE",
"boolean",
"langEquals",
"=",
"desired",
".",
"language",
"(",
")",
".",
"equals"... | Returns the distance between the desired and supported locale, using the
given distance threshold. Any distance equal to or greater than the threshold
will return the maximum distance. | [
"Returns",
"the",
"distance",
"between",
"the",
"desired",
"and",
"supported",
"locale",
"using",
"the",
"given",
"distance",
"threshold",
".",
"Any",
"distance",
"equal",
"to",
"or",
"greater",
"than",
"the",
"threshold",
"will",
"return",
"the",
"maximum",
"... | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/DistanceTable.java#L95-L166 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/DistanceTable.java | DistanceTable.scanTerritory | private Node scanTerritory(DistanceMap map, String desired, String supported) {
Node node;
for (String partition : PARTITION_TABLE.getRegionPartition(desired)) {
node = map.get(partition, supported);
if (node != null) {
return node;
}
}
for (String partition : PARTITION_TABLE.getRegionPartition(supported)) {
node = map.get(desired, partition);
if (node != null) {
return node;
}
}
return null;
} | java | private Node scanTerritory(DistanceMap map, String desired, String supported) {
Node node;
for (String partition : PARTITION_TABLE.getRegionPartition(desired)) {
node = map.get(partition, supported);
if (node != null) {
return node;
}
}
for (String partition : PARTITION_TABLE.getRegionPartition(supported)) {
node = map.get(desired, partition);
if (node != null) {
return node;
}
}
return null;
} | [
"private",
"Node",
"scanTerritory",
"(",
"DistanceMap",
"map",
",",
"String",
"desired",
",",
"String",
"supported",
")",
"{",
"Node",
"node",
";",
"for",
"(",
"String",
"partition",
":",
"PARTITION_TABLE",
".",
"getRegionPartition",
"(",
"desired",
")",
")",
... | Scan the desired region against the supported partitions and vice versa.
Return the first matching node. | [
"Scan",
"the",
"desired",
"region",
"against",
"the",
"supported",
"partitions",
"and",
"vice",
"versa",
".",
"Return",
"the",
"first",
"matching",
"node",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/DistanceTable.java#L172-L189 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/MetaZone.java | MetaZone.applies | public String applies(ZonedDateTime d) {
long epoch = d.toEpochSecond();
for (int i = 0; i < size; i++) {
Entry entry = entries[i];
if (entry.from == -1) {
if (entry.to == -1 || epoch < entry.to) {
return entry.metazoneId;
}
} else if (entry.to == -1) {
if (entry.from <= epoch) {
return entry.metazoneId;
}
} else if (entry.from <= epoch && epoch < entry.to) {
return entry.metazoneId;
}
}
return null;
} | java | public String applies(ZonedDateTime d) {
long epoch = d.toEpochSecond();
for (int i = 0; i < size; i++) {
Entry entry = entries[i];
if (entry.from == -1) {
if (entry.to == -1 || epoch < entry.to) {
return entry.metazoneId;
}
} else if (entry.to == -1) {
if (entry.from <= epoch) {
return entry.metazoneId;
}
} else if (entry.from <= epoch && epoch < entry.to) {
return entry.metazoneId;
}
}
return null;
} | [
"public",
"String",
"applies",
"(",
"ZonedDateTime",
"d",
")",
"{",
"long",
"epoch",
"=",
"d",
".",
"toEpochSecond",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"Entry",
"entry",
"=",
"entries... | Find the metazone that applies for a given timestamp. | [
"Find",
"the",
"metazone",
"that",
"applies",
"for",
"a",
"given",
"timestamp",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/MetaZone.java#L30-L47 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java | LanguageMatcher.match | public Match match(List<String> desired, int threshold) {
return matchImpl(parse(desired), threshold);
} | java | public Match match(List<String> desired, int threshold) {
return matchImpl(parse(desired), threshold);
} | [
"public",
"Match",
"match",
"(",
"List",
"<",
"String",
">",
"desired",
",",
"int",
"threshold",
")",
"{",
"return",
"matchImpl",
"(",
"parse",
"(",
"desired",
")",
",",
"threshold",
")",
";",
"}"
] | Return the best match that exceeds the threshold.
If the default is returned its distance is set to MAX_DISTANCE. | [
"Return",
"the",
"best",
"match",
"that",
"exceeds",
"the",
"threshold",
".",
"If",
"the",
"default",
"is",
"returned",
"its",
"distance",
"is",
"set",
"to",
"MAX_DISTANCE",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java#L117-L119 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java | LanguageMatcher.matches | public List<Match> matches(List<String> desired) {
return matchesImpl(parse(desired), DEFAULT_THRESHOLD);
} | java | public List<Match> matches(List<String> desired) {
return matchesImpl(parse(desired), DEFAULT_THRESHOLD);
} | [
"public",
"List",
"<",
"Match",
">",
"matches",
"(",
"List",
"<",
"String",
">",
"desired",
")",
"{",
"return",
"matchesImpl",
"(",
"parse",
"(",
"desired",
")",
",",
"DEFAULT_THRESHOLD",
")",
";",
"}"
] | Return all matches and their distances, if they exceed the default threshold.
If no match exceeds the threshold this returns an empty list. | [
"Return",
"all",
"matches",
"and",
"their",
"distances",
"if",
"they",
"exceed",
"the",
"default",
"threshold",
".",
"If",
"no",
"match",
"exceeds",
"the",
"threshold",
"this",
"returns",
"an",
"empty",
"list",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java#L141-L143 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java | LanguageMatcher.matchImpl | private Match matchImpl(List<Entry> desiredLocales, int threshold) {
int bestDistance = MAX_DISTANCE;
Entry bestMatch = null;
for (Entry desired : desiredLocales) {
List<String> exact = exactMatch.get(desired.locale);
if (exact != null) {
return new Match(exact.get(0), 0);
}
for (Entry supported : supportedLocales) {
int distance = DISTANCE_TABLE.distance(desired.locale, supported.locale, threshold);
if (distance < bestDistance) {
bestDistance = distance;
bestMatch = supported;
}
}
}
return bestMatch == null
? new Match(firstEntry.bundleId, MAX_DISTANCE)
: new Match(bestMatch.bundleId, bestDistance);
} | java | private Match matchImpl(List<Entry> desiredLocales, int threshold) {
int bestDistance = MAX_DISTANCE;
Entry bestMatch = null;
for (Entry desired : desiredLocales) {
List<String> exact = exactMatch.get(desired.locale);
if (exact != null) {
return new Match(exact.get(0), 0);
}
for (Entry supported : supportedLocales) {
int distance = DISTANCE_TABLE.distance(desired.locale, supported.locale, threshold);
if (distance < bestDistance) {
bestDistance = distance;
bestMatch = supported;
}
}
}
return bestMatch == null
? new Match(firstEntry.bundleId, MAX_DISTANCE)
: new Match(bestMatch.bundleId, bestDistance);
} | [
"private",
"Match",
"matchImpl",
"(",
"List",
"<",
"Entry",
">",
"desiredLocales",
",",
"int",
"threshold",
")",
"{",
"int",
"bestDistance",
"=",
"MAX_DISTANCE",
";",
"Entry",
"bestMatch",
"=",
"null",
";",
"for",
"(",
"Entry",
"desired",
":",
"desiredLocale... | Return the best match that exceeds the threshold, or the default.
If the default is returned its distance is set to MAX_DISTANCE.
An exact match has distance of 0. | [
"Return",
"the",
"best",
"match",
"that",
"exceeds",
"the",
"threshold",
"or",
"the",
"default",
".",
"If",
"the",
"default",
"is",
"returned",
"its",
"distance",
"is",
"set",
"to",
"MAX_DISTANCE",
".",
"An",
"exact",
"match",
"has",
"distance",
"of",
"0",... | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/LanguageMatcher.java#L158-L177 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.generate | public void generate(Path outputDir, DataReader reader) throws IOException {
String className = "_PluralRules";
TypeSpec.Builder type = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.superclass(TYPE_BASE);
Map<String, FieldSpec> fieldMap = buildConditionFields(reader.cardinals(), reader.ordinals());
for (Map.Entry<String, FieldSpec> entry : fieldMap.entrySet()) {
type.addField(entry.getValue());
}
buildPluralMethod(type, "Cardinal", reader.cardinals(), fieldMap);
buildPluralMethod(type, "Ordinal", reader.ordinals(), fieldMap);
CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_PLURALS, className, type.build());
} | java | public void generate(Path outputDir, DataReader reader) throws IOException {
String className = "_PluralRules";
TypeSpec.Builder type = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.superclass(TYPE_BASE);
Map<String, FieldSpec> fieldMap = buildConditionFields(reader.cardinals(), reader.ordinals());
for (Map.Entry<String, FieldSpec> entry : fieldMap.entrySet()) {
type.addField(entry.getValue());
}
buildPluralMethod(type, "Cardinal", reader.cardinals(), fieldMap);
buildPluralMethod(type, "Ordinal", reader.ordinals(), fieldMap);
CodeGenerator.saveClass(outputDir, PACKAGE_CLDR_PLURALS, className, type.build());
} | [
"public",
"void",
"generate",
"(",
"Path",
"outputDir",
",",
"DataReader",
"reader",
")",
"throws",
"IOException",
"{",
"String",
"className",
"=",
"\"_PluralRules\"",
";",
"TypeSpec",
".",
"Builder",
"type",
"=",
"TypeSpec",
".",
"classBuilder",
"(",
"className... | Generate a class for plural rule evaluation.
This will build several Condition fields which evaluate specific AND conditions,
and methods which call these AND conditions joined by an OR operator. | [
"Generate",
"a",
"class",
"for",
"plural",
"rule",
"evaluation",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L55-L70 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.buildRuleMethod | private MethodSpec buildRuleMethod(String methodName, PluralData data, Map<String, FieldSpec> fieldMap) {
MethodSpec.Builder method = MethodSpec.methodBuilder(methodName)
.addModifiers(PRIVATE, STATIC)
.addParameter(NUMBER_OPERANDS, "o")
.returns(PLURAL_CATEGORY);
for (Map.Entry<String, PluralData.Rule> entry : data.rules().entrySet()) {
String category = entry.getKey();
// Other is always the last condition in a set of rules.
if (category.equals("other")) {
// Last condition.
method.addStatement("return PluralCategory.OTHER");
break;
}
// Create a representation of the full rule for commenting.
PluralData.Rule rule = entry.getValue();
String ruleRepr = PluralRulePrinter.print(rule.condition);
// Append all of the lambda methods we'll be invoking to evaluate this rule.
List<String> fields = new ArrayList<>();
for (Node<PluralType> condition : rule.condition.asStruct().nodes()) {
String repr = PluralRulePrinter.print(condition);
fields.add(fieldMap.get(repr).name);
}
// Header comment to indicate which conditions are evaluated.
method.addComment(" $L", ruleRepr);
if (!Objects.equals(rule.sample, "")) {
List<String> samples = Splitter.on("@").splitToList(rule.sample);
for (String sample : samples) {
method.addComment(" $L", sample);
}
}
// Emit the chain of OR conditions. If one is true we return the current category.
int size = fields.size();
String stmt = "if (";
for (int i = 0; i < size; i++) {
if (i > 0) {
stmt += " || ";
}
stmt += fields.get(i) + ".eval(o)";
}
stmt += ")";
// If the rule evaluates to true, return the associated plural category.
method.beginControlFlow(stmt);
method.addStatement("return PluralCategory." + category.toUpperCase());
method.endControlFlow();
method.addCode("\n");
}
return method.build();
} | java | private MethodSpec buildRuleMethod(String methodName, PluralData data, Map<String, FieldSpec> fieldMap) {
MethodSpec.Builder method = MethodSpec.methodBuilder(methodName)
.addModifiers(PRIVATE, STATIC)
.addParameter(NUMBER_OPERANDS, "o")
.returns(PLURAL_CATEGORY);
for (Map.Entry<String, PluralData.Rule> entry : data.rules().entrySet()) {
String category = entry.getKey();
// Other is always the last condition in a set of rules.
if (category.equals("other")) {
// Last condition.
method.addStatement("return PluralCategory.OTHER");
break;
}
// Create a representation of the full rule for commenting.
PluralData.Rule rule = entry.getValue();
String ruleRepr = PluralRulePrinter.print(rule.condition);
// Append all of the lambda methods we'll be invoking to evaluate this rule.
List<String> fields = new ArrayList<>();
for (Node<PluralType> condition : rule.condition.asStruct().nodes()) {
String repr = PluralRulePrinter.print(condition);
fields.add(fieldMap.get(repr).name);
}
// Header comment to indicate which conditions are evaluated.
method.addComment(" $L", ruleRepr);
if (!Objects.equals(rule.sample, "")) {
List<String> samples = Splitter.on("@").splitToList(rule.sample);
for (String sample : samples) {
method.addComment(" $L", sample);
}
}
// Emit the chain of OR conditions. If one is true we return the current category.
int size = fields.size();
String stmt = "if (";
for (int i = 0; i < size; i++) {
if (i > 0) {
stmt += " || ";
}
stmt += fields.get(i) + ".eval(o)";
}
stmt += ")";
// If the rule evaluates to true, return the associated plural category.
method.beginControlFlow(stmt);
method.addStatement("return PluralCategory." + category.toUpperCase());
method.endControlFlow();
method.addCode("\n");
}
return method.build();
} | [
"private",
"MethodSpec",
"buildRuleMethod",
"(",
"String",
"methodName",
",",
"PluralData",
"data",
",",
"Map",
"<",
"String",
",",
"FieldSpec",
">",
"fieldMap",
")",
"{",
"MethodSpec",
".",
"Builder",
"method",
"=",
"MethodSpec",
".",
"methodBuilder",
"(",
"m... | Builds a method that when called evaluates the rule and returns a PluralCategory. | [
"Builds",
"a",
"method",
"that",
"when",
"called",
"evaluates",
"the",
"rule",
"and",
"returns",
"a",
"PluralCategory",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L110-L165 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.buildConditionFields | @SafeVarargs
private final Map<String, FieldSpec> buildConditionFields(Map<String, PluralData>... pluralMaps) {
Map<String, FieldSpec> index = new LinkedHashMap<>();
int seq = 0;
for (Map<String, PluralData> pluralMap : pluralMaps) {
for (Map.Entry<String, PluralData> entry : pluralMap.entrySet()) {
PluralData data = entry.getValue();
// Iterate over the rules, drilling into the OR conditions and
// building a field to evaluate each AND condition.
for (Map.Entry<String, PluralData.Rule> rule : data.rules().entrySet()) {
Node<PluralType> orCondition = rule.getValue().condition;
if (orCondition == null) {
continue;
}
// Render the representation for each AND condition, using that as a
// key to map to the corresponding lambda Condition field that
// computes it.
for (Node<PluralType> andCondition : orCondition.asStruct().nodes()) {
String repr = PluralRulePrinter.print(andCondition);
if (index.containsKey(repr)) {
continue;
}
// Build the field that represents the evaluation of the AND condition.
FieldSpec field = buildConditionField(seq, andCondition.asStruct());
index.put(repr, field);
seq++;
}
}
}
}
return index;
} | java | @SafeVarargs
private final Map<String, FieldSpec> buildConditionFields(Map<String, PluralData>... pluralMaps) {
Map<String, FieldSpec> index = new LinkedHashMap<>();
int seq = 0;
for (Map<String, PluralData> pluralMap : pluralMaps) {
for (Map.Entry<String, PluralData> entry : pluralMap.entrySet()) {
PluralData data = entry.getValue();
// Iterate over the rules, drilling into the OR conditions and
// building a field to evaluate each AND condition.
for (Map.Entry<String, PluralData.Rule> rule : data.rules().entrySet()) {
Node<PluralType> orCondition = rule.getValue().condition;
if (orCondition == null) {
continue;
}
// Render the representation for each AND condition, using that as a
// key to map to the corresponding lambda Condition field that
// computes it.
for (Node<PluralType> andCondition : orCondition.asStruct().nodes()) {
String repr = PluralRulePrinter.print(andCondition);
if (index.containsKey(repr)) {
continue;
}
// Build the field that represents the evaluation of the AND condition.
FieldSpec field = buildConditionField(seq, andCondition.asStruct());
index.put(repr, field);
seq++;
}
}
}
}
return index;
} | [
"@",
"SafeVarargs",
"private",
"final",
"Map",
"<",
"String",
",",
"FieldSpec",
">",
"buildConditionFields",
"(",
"Map",
"<",
"String",
",",
"PluralData",
">",
"...",
"pluralMaps",
")",
"{",
"Map",
"<",
"String",
",",
"FieldSpec",
">",
"index",
"=",
"new",... | Maps an integer to each AND condition's canonical representation. | [
"Maps",
"an",
"integer",
"to",
"each",
"AND",
"condition",
"s",
"canonical",
"representation",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L170-L205 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.buildConditionField | public FieldSpec buildConditionField(int index, Struct<PluralType> branch) {
String fieldDoc = PluralRulePrinter.print(branch);
String name = String.format("COND_%d", index);
FieldSpec.Builder field = FieldSpec.builder(PLURAL_CONDITION, name, PRIVATE, STATIC, FINAL)
.addJavadoc(fieldDoc + "\n");
List<Node<PluralType>> expressions = branch.nodes();
CodeBlock.Builder code = CodeBlock.builder();
code.beginControlFlow("(o) ->");
int size = expressions.size();
for (int i = 0; i < size; i++) {
renderExpr(i == 0, code, expressions.get(i));
}
code.addStatement("return true");
code.endControlFlow();
field.initializer(code.build());
return field.build();
} | java | public FieldSpec buildConditionField(int index, Struct<PluralType> branch) {
String fieldDoc = PluralRulePrinter.print(branch);
String name = String.format("COND_%d", index);
FieldSpec.Builder field = FieldSpec.builder(PLURAL_CONDITION, name, PRIVATE, STATIC, FINAL)
.addJavadoc(fieldDoc + "\n");
List<Node<PluralType>> expressions = branch.nodes();
CodeBlock.Builder code = CodeBlock.builder();
code.beginControlFlow("(o) ->");
int size = expressions.size();
for (int i = 0; i < size; i++) {
renderExpr(i == 0, code, expressions.get(i));
}
code.addStatement("return true");
code.endControlFlow();
field.initializer(code.build());
return field.build();
} | [
"public",
"FieldSpec",
"buildConditionField",
"(",
"int",
"index",
",",
"Struct",
"<",
"PluralType",
">",
"branch",
")",
"{",
"String",
"fieldDoc",
"=",
"PluralRulePrinter",
".",
"print",
"(",
"branch",
")",
";",
"String",
"name",
"=",
"String",
".",
"format... | Constructs a lambda Condition field that represents a chain of AND conditions,
that together is a single branch in an OR condition. | [
"Constructs",
"a",
"lambda",
"Condition",
"field",
"that",
"represents",
"a",
"chain",
"of",
"AND",
"conditions",
"that",
"together",
"is",
"a",
"single",
"branch",
"in",
"an",
"OR",
"condition",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L211-L231 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.renderExpr | private static void renderExpr(boolean first, CodeBlock.Builder code, Node<PluralType> expr) {
Iterator<Node<PluralType>> iter = expr.asStruct().nodes().iterator();
// Parse out the two forms of operand expressions we support:
//
// n = <rangelist>
// n % m = <rangelist>
//
Atom<PluralType> operand = iter.next().asAtom();
Atom<PluralType> modop = null;
Atom<PluralType> relop = iter.next().asAtom();
if (relop.type() == PluralType.MODOP) {
modop = relop;
relop = iter.next().asAtom();
}
String var = (String)operand.value();
List<Node<PluralType>> rangeList = iter.next().asStruct().nodes();
boolean decimalsZero = false;
if (var.equals("n") && modop != null) {
// We're applying mod to the 'n' operand, we must also ensure that
// decimal value == 0.
decimalsZero = true;
}
// If this is the first expression, define the variable; otherwise reuse it.
String fmt = "zz = o.$L()";
if (first) {
fmt = "long " + fmt;
}
// Mod operations modify the operand before assignment.
if (modop != null) {
fmt += " % $LL";
}
// Emit the expression.
if (modop != null) {
code.addStatement(fmt, var, (int)modop.value());
} else {
code.addStatement(fmt, var);
}
renderExpr(code, rangeList, relop.value().equals("="), decimalsZero);
} | java | private static void renderExpr(boolean first, CodeBlock.Builder code, Node<PluralType> expr) {
Iterator<Node<PluralType>> iter = expr.asStruct().nodes().iterator();
// Parse out the two forms of operand expressions we support:
//
// n = <rangelist>
// n % m = <rangelist>
//
Atom<PluralType> operand = iter.next().asAtom();
Atom<PluralType> modop = null;
Atom<PluralType> relop = iter.next().asAtom();
if (relop.type() == PluralType.MODOP) {
modop = relop;
relop = iter.next().asAtom();
}
String var = (String)operand.value();
List<Node<PluralType>> rangeList = iter.next().asStruct().nodes();
boolean decimalsZero = false;
if (var.equals("n") && modop != null) {
// We're applying mod to the 'n' operand, we must also ensure that
// decimal value == 0.
decimalsZero = true;
}
// If this is the first expression, define the variable; otherwise reuse it.
String fmt = "zz = o.$L()";
if (first) {
fmt = "long " + fmt;
}
// Mod operations modify the operand before assignment.
if (modop != null) {
fmt += " % $LL";
}
// Emit the expression.
if (modop != null) {
code.addStatement(fmt, var, (int)modop.value());
} else {
code.addStatement(fmt, var);
}
renderExpr(code, rangeList, relop.value().equals("="), decimalsZero);
} | [
"private",
"static",
"void",
"renderExpr",
"(",
"boolean",
"first",
",",
"CodeBlock",
".",
"Builder",
"code",
",",
"Node",
"<",
"PluralType",
">",
"expr",
")",
"{",
"Iterator",
"<",
"Node",
"<",
"PluralType",
">>",
"iter",
"=",
"expr",
".",
"asStruct",
"... | Render the header of a branch method. | [
"Render",
"the",
"header",
"of",
"a",
"branch",
"method",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L236-L281 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.renderExpr | private static void renderExpr(
CodeBlock.Builder code, List<Node<PluralType>> rangeList, boolean equal, boolean decimalsZero) {
int size = rangeList.size();
String r = "";
// Join the range list expressions with the OR operator.
for (int i = 0; i < size; i++) {
if (i > 0) {
r += " || ";
}
r += renderRange("zz", rangeList.get(i));
}
// Wrap the expression in an IF.
String fmt = "if (";
if (decimalsZero) {
fmt += "o.nd() != 0 || ";
}
if (equal) {
fmt += size == 1 ? "!$L" : "!($L)";
} else {
fmt += "($L)";
}
fmt += ")";
// Wrap the IF as a block.
code.beginControlFlow(fmt, r);
code.addStatement("return false");
code.endControlFlow();
} | java | private static void renderExpr(
CodeBlock.Builder code, List<Node<PluralType>> rangeList, boolean equal, boolean decimalsZero) {
int size = rangeList.size();
String r = "";
// Join the range list expressions with the OR operator.
for (int i = 0; i < size; i++) {
if (i > 0) {
r += " || ";
}
r += renderRange("zz", rangeList.get(i));
}
// Wrap the expression in an IF.
String fmt = "if (";
if (decimalsZero) {
fmt += "o.nd() != 0 || ";
}
if (equal) {
fmt += size == 1 ? "!$L" : "!($L)";
} else {
fmt += "($L)";
}
fmt += ")";
// Wrap the IF as a block.
code.beginControlFlow(fmt, r);
code.addStatement("return false");
code.endControlFlow();
} | [
"private",
"static",
"void",
"renderExpr",
"(",
"CodeBlock",
".",
"Builder",
"code",
",",
"List",
"<",
"Node",
"<",
"PluralType",
">",
">",
"rangeList",
",",
"boolean",
"equal",
",",
"boolean",
"decimalsZero",
")",
"{",
"int",
"size",
"=",
"rangeList",
"."... | Render the expression body of a branch method. | [
"Render",
"the",
"expression",
"body",
"of",
"a",
"branch",
"method",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L286-L318 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java | PluralCodeGenerator.renderRange | private static String renderRange(String name, Node<PluralType> node) {
if (node.type() == PluralType.RANGE) {
Struct<PluralType> range = node.asStruct();
int start = (Integer) range.nodes().get(0).asAtom().value();
int end = (Integer) range.nodes().get(1).asAtom().value();
return String.format("(%s >= %d && %s <= %d)", name, start, name, end);
}
return String.format("(%s == %s)", name, node.asAtom().value());
} | java | private static String renderRange(String name, Node<PluralType> node) {
if (node.type() == PluralType.RANGE) {
Struct<PluralType> range = node.asStruct();
int start = (Integer) range.nodes().get(0).asAtom().value();
int end = (Integer) range.nodes().get(1).asAtom().value();
return String.format("(%s >= %d && %s <= %d)", name, start, name, end);
}
return String.format("(%s == %s)", name, node.asAtom().value());
} | [
"private",
"static",
"String",
"renderRange",
"(",
"String",
"name",
",",
"Node",
"<",
"PluralType",
">",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"(",
")",
"==",
"PluralType",
".",
"RANGE",
")",
"{",
"Struct",
"<",
"PluralType",
">",
"range",... | Render a the range segment of an expression. | [
"Render",
"a",
"the",
"range",
"segment",
"of",
"an",
"expression",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/PluralCodeGenerator.java#L323-L331 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java | PluralRulePrinter.print | public static String print(Node<PluralType> node) {
StringBuilder buf = new StringBuilder();
print(buf, node);
return buf.toString();
} | java | public static String print(Node<PluralType> node) {
StringBuilder buf = new StringBuilder();
print(buf, node);
return buf.toString();
} | [
"public",
"static",
"String",
"print",
"(",
"Node",
"<",
"PluralType",
">",
"node",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"print",
"(",
"buf",
",",
"node",
")",
";",
"return",
"buf",
".",
"toString",
"(",
")",
... | Return a recursive representation of the given pluralization node or tree. | [
"Return",
"a",
"recursive",
"representation",
"of",
"the",
"given",
"pluralization",
"node",
"or",
"tree",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java#L17-L21 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java | PluralRulePrinter.print | private static void print(StringBuilder buf, Node<PluralType> node) {
switch (node.type()) {
case RULE:
join(buf, node, " ");
break;
case AND_CONDITION:
join(buf, node, " and ");
break;
case OR_CONDITION:
join(buf, node, " or ");
break;
case RANGELIST:
join(buf, node, ",");
break;
case RANGE:
join(buf, node, "..");
break;
case EXPR:
join(buf, node, " ");
break;
case MODOP:
buf.append("% ").append(node.asAtom().value());
break;
case INTEGER:
case OPERAND:
case RELOP:
case SAMPLE:
buf.append(node.asAtom().value());
break;
}
} | java | private static void print(StringBuilder buf, Node<PluralType> node) {
switch (node.type()) {
case RULE:
join(buf, node, " ");
break;
case AND_CONDITION:
join(buf, node, " and ");
break;
case OR_CONDITION:
join(buf, node, " or ");
break;
case RANGELIST:
join(buf, node, ",");
break;
case RANGE:
join(buf, node, "..");
break;
case EXPR:
join(buf, node, " ");
break;
case MODOP:
buf.append("% ").append(node.asAtom().value());
break;
case INTEGER:
case OPERAND:
case RELOP:
case SAMPLE:
buf.append(node.asAtom().value());
break;
}
} | [
"private",
"static",
"void",
"print",
"(",
"StringBuilder",
"buf",
",",
"Node",
"<",
"PluralType",
">",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
"(",
")",
")",
"{",
"case",
"RULE",
":",
"join",
"(",
"buf",
",",
"node",
",",
"\" \"",
")... | Recursively visit the structs and atoms in the pluralization node or tree,
appending the representations to a string buffer. | [
"Recursively",
"visit",
"the",
"structs",
"and",
"atoms",
"in",
"the",
"pluralization",
"node",
"or",
"tree",
"appending",
"the",
"representations",
"to",
"a",
"string",
"buffer",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java#L27-L64 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java | PluralRulePrinter.join | private static void join(StringBuilder buf, Node<PluralType> parent, String delimiter) {
List<Node<PluralType>> nodes = parent.asStruct().nodes();
int size = nodes.size();
for (int i = 0; i < size; i++) {
if (i > 0) {
buf.append(delimiter);
}
print(buf, nodes.get(i));
}
} | java | private static void join(StringBuilder buf, Node<PluralType> parent, String delimiter) {
List<Node<PluralType>> nodes = parent.asStruct().nodes();
int size = nodes.size();
for (int i = 0; i < size; i++) {
if (i > 0) {
buf.append(delimiter);
}
print(buf, nodes.get(i));
}
} | [
"private",
"static",
"void",
"join",
"(",
"StringBuilder",
"buf",
",",
"Node",
"<",
"PluralType",
">",
"parent",
",",
"String",
"delimiter",
")",
"{",
"List",
"<",
"Node",
"<",
"PluralType",
">>",
"nodes",
"=",
"parent",
".",
"asStruct",
"(",
")",
".",
... | Print each child node of a struct, joining them together with a
delimiter string. | [
"Print",
"each",
"child",
"node",
"of",
"a",
"struct",
"joining",
"them",
"together",
"with",
"a",
"delimiter",
"string",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/parse/PluralRulePrinter.java#L70-L79 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.format | @Override
public void format(ZonedDateTime datetime, CalendarFormatOptions options, StringBuilder buffer) {
String dateSkeleton = options.dateSkeleton() == null ? null : options.dateSkeleton().skeleton();
String timeSkeleton = options.timeSkeleton() == null ? null : options.timeSkeleton().skeleton();
CalendarFormat wrapperFormat = options.wrapperFormat();
CalendarFormat dateFormat = options.dateFormat();
CalendarFormat timeFormat = options.timeFormat();
if (wrapperFormat != null) {
// If wrapper is set it implies we want to output both a date and a time. If either is unset
// we need to set it to the wrapper's format, unless a skeleton is defined.
dateFormat = dateFormat != null ? dateFormat : (dateSkeleton == null ? wrapperFormat : null);
timeFormat = timeFormat != null ? timeFormat : (timeSkeleton == null ? wrapperFormat : null);
} else {
// If wrapper is null, attempt to default it using the date's format or SHORT.
if ((dateFormat != null || dateSkeleton != null) && (timeFormat != null || timeSkeleton != null)) {
wrapperFormat = dateFormat != null ? dateFormat : CalendarFormat.SHORT;
}
}
if (wrapperFormat != null) {
formatWrapped(wrapperFormat, dateFormat, timeFormat, dateSkeleton, timeSkeleton, datetime, buffer);
} else if (options.dateFormat() != null) {
formatDate(options.dateFormat(), datetime, buffer);
} else if (options.timeFormat() != null) {
formatTime(options.timeFormat(), datetime, buffer);
} else {
String skeleton = dateSkeleton != null ? dateSkeleton : timeSkeleton;
// If every property is null, fall back to this default "yMd"
if (skeleton == null) {
skeleton = CalendarSkeleton.yMd.skeleton();
}
formatSkeleton(skeleton, datetime, buffer);
}
} | java | @Override
public void format(ZonedDateTime datetime, CalendarFormatOptions options, StringBuilder buffer) {
String dateSkeleton = options.dateSkeleton() == null ? null : options.dateSkeleton().skeleton();
String timeSkeleton = options.timeSkeleton() == null ? null : options.timeSkeleton().skeleton();
CalendarFormat wrapperFormat = options.wrapperFormat();
CalendarFormat dateFormat = options.dateFormat();
CalendarFormat timeFormat = options.timeFormat();
if (wrapperFormat != null) {
// If wrapper is set it implies we want to output both a date and a time. If either is unset
// we need to set it to the wrapper's format, unless a skeleton is defined.
dateFormat = dateFormat != null ? dateFormat : (dateSkeleton == null ? wrapperFormat : null);
timeFormat = timeFormat != null ? timeFormat : (timeSkeleton == null ? wrapperFormat : null);
} else {
// If wrapper is null, attempt to default it using the date's format or SHORT.
if ((dateFormat != null || dateSkeleton != null) && (timeFormat != null || timeSkeleton != null)) {
wrapperFormat = dateFormat != null ? dateFormat : CalendarFormat.SHORT;
}
}
if (wrapperFormat != null) {
formatWrapped(wrapperFormat, dateFormat, timeFormat, dateSkeleton, timeSkeleton, datetime, buffer);
} else if (options.dateFormat() != null) {
formatDate(options.dateFormat(), datetime, buffer);
} else if (options.timeFormat() != null) {
formatTime(options.timeFormat(), datetime, buffer);
} else {
String skeleton = dateSkeleton != null ? dateSkeleton : timeSkeleton;
// If every property is null, fall back to this default "yMd"
if (skeleton == null) {
skeleton = CalendarSkeleton.yMd.skeleton();
}
formatSkeleton(skeleton, datetime, buffer);
}
} | [
"@",
"Override",
"public",
"void",
"format",
"(",
"ZonedDateTime",
"datetime",
",",
"CalendarFormatOptions",
"options",
",",
"StringBuilder",
"buffer",
")",
"{",
"String",
"dateSkeleton",
"=",
"options",
".",
"dateSkeleton",
"(",
")",
"==",
"null",
"?",
"null",
... | Main entry point for date time formatting. | [
"Main",
"entry",
"point",
"for",
"date",
"time",
"formatting",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L137-L175 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.format | @Override
public void format(
ZonedDateTime start, ZonedDateTime end, DateTimeIntervalSkeleton skeleton, StringBuilder buffer) {
DateTimeField field = CalendarFormattingUtils.greatestDifference(start, end);
if (skeleton == null) {
switch (field) {
case YEAR:
case MONTH:
case DAY:
skeleton = DateTimeIntervalSkeleton.yMMMd;
break;
default:
skeleton = DateTimeIntervalSkeleton.hmv;
break;
}
}
formatInterval(start, end, skeleton.skeleton(), field, buffer);
} | java | @Override
public void format(
ZonedDateTime start, ZonedDateTime end, DateTimeIntervalSkeleton skeleton, StringBuilder buffer) {
DateTimeField field = CalendarFormattingUtils.greatestDifference(start, end);
if (skeleton == null) {
switch (field) {
case YEAR:
case MONTH:
case DAY:
skeleton = DateTimeIntervalSkeleton.yMMMd;
break;
default:
skeleton = DateTimeIntervalSkeleton.hmv;
break;
}
}
formatInterval(start, end, skeleton.skeleton(), field, buffer);
} | [
"@",
"Override",
"public",
"void",
"format",
"(",
"ZonedDateTime",
"start",
",",
"ZonedDateTime",
"end",
",",
"DateTimeIntervalSkeleton",
"skeleton",
",",
"StringBuilder",
"buffer",
")",
"{",
"DateTimeField",
"field",
"=",
"CalendarFormattingUtils",
".",
"greatestDiff... | Format a date time interval, guessing at the best skeleton to use based on the field
of greatest difference between the start and end date-time. If the end date-time has
a different time zone than the start, this is corrected for comparison. If the
skeleton is null, one is selected automatically using the field of greatest difference.
Greatest difference is calculated by comparing fields in the following order:
year, month, date, day-of-week, am-pm, hour, hour-of-day, minute, and second | [
"Format",
"a",
"date",
"time",
"interval",
"guessing",
"at",
"the",
"best",
"skeleton",
"to",
"use",
"based",
"on",
"the",
"field",
"of",
"greatest",
"difference",
"between",
"the",
"start",
"and",
"end",
"date",
"-",
"time",
".",
"If",
"the",
"end",
"da... | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L187-L206 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.resolveTimeZoneId | public String resolveTimeZoneId(String zoneId) {
String alias = _CalendarUtils.getTimeZoneAlias(zoneId);
if (alias != null) {
zoneId = alias;
}
alias = TimeZoneAliases.getAlias(zoneId);
if (alias != null) {
zoneId = alias;
}
return zoneId;
} | java | public String resolveTimeZoneId(String zoneId) {
String alias = _CalendarUtils.getTimeZoneAlias(zoneId);
if (alias != null) {
zoneId = alias;
}
alias = TimeZoneAliases.getAlias(zoneId);
if (alias != null) {
zoneId = alias;
}
return zoneId;
} | [
"public",
"String",
"resolveTimeZoneId",
"(",
"String",
"zoneId",
")",
"{",
"String",
"alias",
"=",
"_CalendarUtils",
".",
"getTimeZoneAlias",
"(",
"zoneId",
")",
";",
"if",
"(",
"alias",
"!=",
"null",
")",
"{",
"zoneId",
"=",
"alias",
";",
"}",
"alias",
... | Check if the zoneId has an alias in the CLDR data. | [
"Check",
"if",
"the",
"zoneId",
"has",
"an",
"alias",
"in",
"the",
"CLDR",
"data",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L219-L229 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatField | public void formatField(ZonedDateTime datetime, String pattern, StringBuilder buffer) {
int length = pattern.length();
if (length == 0) {
return;
}
// Current position in pattern
int i = 0;
// Skip over prefix indicating we want to format a single field.
if (pattern.charAt(i) == '+') {
if (length == 1) {
return;
}
i++;
}
int width = 0;
char field = pattern.charAt(i);
while (i < length) {
if (pattern.charAt(i) != field) {
break;
}
width++;
i++;
}
formatField(datetime, field, width, buffer);
} | java | public void formatField(ZonedDateTime datetime, String pattern, StringBuilder buffer) {
int length = pattern.length();
if (length == 0) {
return;
}
// Current position in pattern
int i = 0;
// Skip over prefix indicating we want to format a single field.
if (pattern.charAt(i) == '+') {
if (length == 1) {
return;
}
i++;
}
int width = 0;
char field = pattern.charAt(i);
while (i < length) {
if (pattern.charAt(i) != field) {
break;
}
width++;
i++;
}
formatField(datetime, field, width, buffer);
} | [
"public",
"void",
"formatField",
"(",
"ZonedDateTime",
"datetime",
",",
"String",
"pattern",
",",
"StringBuilder",
"buffer",
")",
"{",
"int",
"length",
"=",
"pattern",
".",
"length",
"(",
")",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
";",... | Formats a single field, based on the first character in the pattern string,
with repeated characters indicating the field width. | [
"Formats",
"a",
"single",
"field",
"based",
"on",
"the",
"first",
"character",
"in",
"the",
"pattern",
"string",
"with",
"repeated",
"characters",
"indicating",
"the",
"field",
"width",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L255-L283 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatField | public void formatField(ZonedDateTime datetime, char field, int width, StringBuilder buffer) {
switch (field) {
case 'G':
formatEra(buffer, datetime, width, eras);
break;
case 'y':
formatYear(buffer, datetime, width);
break;
case 'Y':
formatISOYearWeekOfYear(buffer, datetime, width);
break;
case 'u':
case 'U':
case 'r':
// Only used for non-Gregorian calendars
break;
case 'Q':
formatQuarter(buffer, datetime, width, quartersFormat);
break;
case 'q':
formatQuarter(buffer, datetime, width, quartersStandalone);
break;
case 'M':
formatMonth(buffer, datetime, width, monthsFormat);
break;
case 'L':
formatMonth(buffer, datetime, width, monthsStandalone);
break;
case 'l':
// deprecated, ignore
break;
case 'w':
formatISOWeekOfYear(buffer, datetime, width);
break;
case 'W':
formatWeekOfMonth(buffer, datetime, width);
break;
case 'd':
formatDayOfMonth(buffer, datetime, width);
break;
case 'D':
formatDayOfYear(buffer, datetime, width);
break;
case 'F':
formatDayOfWeekInMonth(buffer, datetime, width);
break;
case 'g':
// modified julian day
break;
case 'E':
formatWeekday(buffer, datetime, width, weekdaysFormat);
break;
case 'e':
formatLocalWeekday(buffer, datetime, width, weekdaysFormat, firstDay);
break;
case 'c':
formatLocalWeekdayStandalone(buffer, datetime, width, weekdaysStandalone, firstDay);
break;
case 'a':
formatDayPeriod(buffer, datetime, width, dayPeriodsFormat);
break;
case 'b':
// Not yet in use.
// TODO: day periods: am, pm, noon, midnight
break;
case 'B':
// Not yet in use.
// TODO: flexible day periods: "at night"
break;
case 'h':
formatHours(buffer, datetime, width, true);
break;
case 'H':
formatHours(buffer, datetime, width, false);
break;
case 'K':
formatHoursAlt(buffer, datetime, width, true);
break;
case 'k':
formatHoursAlt(buffer, datetime, width, false);
break;
case 'j':
case 'J':
case 'C':
// Input skeleton symbols, not implemented.
break;
case 'm':
formatMinutes(buffer, datetime, width);
break;
case 's':
formatSeconds(buffer, datetime, width);
break;
case 'S':
formatFractionalSeconds(buffer, datetime, width);
break;
case 'A':
// not implemented
break;
case 'z':
formatTimeZone_z(buffer, datetime, width);
break;
case 'Z':
formatTimeZone_Z(buffer, datetime, width);
break;
case 'O':
formatTimeZone_O(buffer, datetime, width);
break;
case 'v':
formatTimeZone_v(buffer, datetime, width);
break;
case 'V':
formatTimeZone_V(buffer, datetime, width);
break;
case 'X':
case 'x':
formatTimeZone_X(buffer, datetime, width, field);
break;
}
} | java | public void formatField(ZonedDateTime datetime, char field, int width, StringBuilder buffer) {
switch (field) {
case 'G':
formatEra(buffer, datetime, width, eras);
break;
case 'y':
formatYear(buffer, datetime, width);
break;
case 'Y':
formatISOYearWeekOfYear(buffer, datetime, width);
break;
case 'u':
case 'U':
case 'r':
// Only used for non-Gregorian calendars
break;
case 'Q':
formatQuarter(buffer, datetime, width, quartersFormat);
break;
case 'q':
formatQuarter(buffer, datetime, width, quartersStandalone);
break;
case 'M':
formatMonth(buffer, datetime, width, monthsFormat);
break;
case 'L':
formatMonth(buffer, datetime, width, monthsStandalone);
break;
case 'l':
// deprecated, ignore
break;
case 'w':
formatISOWeekOfYear(buffer, datetime, width);
break;
case 'W':
formatWeekOfMonth(buffer, datetime, width);
break;
case 'd':
formatDayOfMonth(buffer, datetime, width);
break;
case 'D':
formatDayOfYear(buffer, datetime, width);
break;
case 'F':
formatDayOfWeekInMonth(buffer, datetime, width);
break;
case 'g':
// modified julian day
break;
case 'E':
formatWeekday(buffer, datetime, width, weekdaysFormat);
break;
case 'e':
formatLocalWeekday(buffer, datetime, width, weekdaysFormat, firstDay);
break;
case 'c':
formatLocalWeekdayStandalone(buffer, datetime, width, weekdaysStandalone, firstDay);
break;
case 'a':
formatDayPeriod(buffer, datetime, width, dayPeriodsFormat);
break;
case 'b':
// Not yet in use.
// TODO: day periods: am, pm, noon, midnight
break;
case 'B':
// Not yet in use.
// TODO: flexible day periods: "at night"
break;
case 'h':
formatHours(buffer, datetime, width, true);
break;
case 'H':
formatHours(buffer, datetime, width, false);
break;
case 'K':
formatHoursAlt(buffer, datetime, width, true);
break;
case 'k':
formatHoursAlt(buffer, datetime, width, false);
break;
case 'j':
case 'J':
case 'C':
// Input skeleton symbols, not implemented.
break;
case 'm':
formatMinutes(buffer, datetime, width);
break;
case 's':
formatSeconds(buffer, datetime, width);
break;
case 'S':
formatFractionalSeconds(buffer, datetime, width);
break;
case 'A':
// not implemented
break;
case 'z':
formatTimeZone_z(buffer, datetime, width);
break;
case 'Z':
formatTimeZone_Z(buffer, datetime, width);
break;
case 'O':
formatTimeZone_O(buffer, datetime, width);
break;
case 'v':
formatTimeZone_v(buffer, datetime, width);
break;
case 'V':
formatTimeZone_V(buffer, datetime, width);
break;
case 'X':
case 'x':
formatTimeZone_X(buffer, datetime, width, field);
break;
}
} | [
"public",
"void",
"formatField",
"(",
"ZonedDateTime",
"datetime",
",",
"char",
"field",
",",
"int",
"width",
",",
"StringBuilder",
"buffer",
")",
"{",
"switch",
"(",
"field",
")",
"{",
"case",
"'",
"'",
":",
"formatEra",
"(",
"buffer",
",",
"datetime",
... | Format a single field of a given width. | [
"Format",
"a",
"single",
"field",
"of",
"a",
"given",
"width",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L288-L441 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatEra | void formatEra(StringBuilder b, ZonedDateTime d, int width, FieldVariants eras) {
int year = d.getYear();
int index = year < 0 ? 0 : 1;
switch (width) {
case 5:
b.append(eras.narrow[index]);
break;
case 4:
b.append(eras.wide[index]);
break;
case 3:
case 2:
case 1:
b.append(eras.abbreviated[index]);
break;
}
} | java | void formatEra(StringBuilder b, ZonedDateTime d, int width, FieldVariants eras) {
int year = d.getYear();
int index = year < 0 ? 0 : 1;
switch (width) {
case 5:
b.append(eras.narrow[index]);
break;
case 4:
b.append(eras.wide[index]);
break;
case 3:
case 2:
case 1:
b.append(eras.abbreviated[index]);
break;
}
} | [
"void",
"formatEra",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"eras",
")",
"{",
"int",
"year",
"=",
"d",
".",
"getYear",
"(",
")",
";",
"int",
"index",
"=",
"year",
"<",
"0",
"?",
"0",
":",
"1... | Format the era based on the year. | [
"Format",
"the",
"era",
"based",
"on",
"the",
"year",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L446-L464 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatYear | void formatYear(StringBuilder b, ZonedDateTime d, int width) {
int year = d.getYear();
_formatYearValue(b, year, width);
} | java | void formatYear(StringBuilder b, ZonedDateTime d, int width) {
int year = d.getYear();
_formatYearValue(b, year, width);
} | [
"void",
"formatYear",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"year",
"=",
"d",
".",
"getYear",
"(",
")",
";",
"_formatYearValue",
"(",
"b",
",",
"year",
",",
"width",
")",
";",
"}"
] | Format the numeric year, zero padding as necessary. | [
"Format",
"the",
"numeric",
"year",
"zero",
"padding",
"as",
"necessary",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L469-L472 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatISOYearWeekOfYear | void formatISOYearWeekOfYear(StringBuilder b, ZonedDateTime d, int width) {
int year = d.get(IsoFields.WEEK_BASED_YEAR);
_formatYearValue(b, year, width);
} | java | void formatISOYearWeekOfYear(StringBuilder b, ZonedDateTime d, int width) {
int year = d.get(IsoFields.WEEK_BASED_YEAR);
_formatYearValue(b, year, width);
} | [
"void",
"formatISOYearWeekOfYear",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"year",
"=",
"d",
".",
"get",
"(",
"IsoFields",
".",
"WEEK_BASED_YEAR",
")",
";",
"_formatYearValue",
"(",
"b",
",",
"year",
",",... | Formats the year according to ISO week-year. | [
"Formats",
"the",
"year",
"according",
"to",
"ISO",
"week",
"-",
"year",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L477-L480 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatQuarter | void formatQuarter(StringBuilder b, ZonedDateTime d, int width, FieldVariants quarters) {
int quarter = (d.getMonth().getValue() - 1) / 3;
switch (width) {
case 5:
b.append(quarters.narrow[quarter]);
break;
case 4:
b.append(quarters.wide[quarter]);
break;
case 3:
b.append(quarters.abbreviated[quarter]);
break;
case 2:
b.append('0');
// fall through
case 1:
b.append(quarter + 1);
break;
}
} | java | void formatQuarter(StringBuilder b, ZonedDateTime d, int width, FieldVariants quarters) {
int quarter = (d.getMonth().getValue() - 1) / 3;
switch (width) {
case 5:
b.append(quarters.narrow[quarter]);
break;
case 4:
b.append(quarters.wide[quarter]);
break;
case 3:
b.append(quarters.abbreviated[quarter]);
break;
case 2:
b.append('0');
// fall through
case 1:
b.append(quarter + 1);
break;
}
} | [
"void",
"formatQuarter",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"quarters",
")",
"{",
"int",
"quarter",
"=",
"(",
"d",
".",
"getMonth",
"(",
")",
".",
"getValue",
"(",
")",
"-",
"1",
")",
"/",
... | Format the quarter based on the month. | [
"Format",
"the",
"quarter",
"based",
"on",
"the",
"month",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L503-L526 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatMonth | void formatMonth(StringBuilder b, ZonedDateTime d, int width, FieldVariants months) {
int month = d.getMonth().getValue();
switch (width) {
case 5:
b.append(months.narrow[month-1]);
break;
case 4:
b.append(months.wide[month-1]);
break;
case 3:
b.append(months.abbreviated[month-1]);
break;
case 2:
if (month < 10) {
b.append('0');
}
// fall through
case 1:
b.append(month);
break;
}
} | java | void formatMonth(StringBuilder b, ZonedDateTime d, int width, FieldVariants months) {
int month = d.getMonth().getValue();
switch (width) {
case 5:
b.append(months.narrow[month-1]);
break;
case 4:
b.append(months.wide[month-1]);
break;
case 3:
b.append(months.abbreviated[month-1]);
break;
case 2:
if (month < 10) {
b.append('0');
}
// fall through
case 1:
b.append(month);
break;
}
} | [
"void",
"formatMonth",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"months",
")",
"{",
"int",
"month",
"=",
"d",
".",
"getMonth",
"(",
")",
".",
"getValue",
"(",
")",
";",
"switch",
"(",
"width",
")"... | Format the month, numeric or a string name variant. | [
"Format",
"the",
"month",
"numeric",
"or",
"a",
"string",
"name",
"variant",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L531-L556 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatWeekOfMonth | void formatWeekOfMonth(StringBuilder b, ZonedDateTime d, int width) {
int w = d.get(ChronoField.ALIGNED_WEEK_OF_MONTH);
if (width == 1) {
b.append(w);
}
} | java | void formatWeekOfMonth(StringBuilder b, ZonedDateTime d, int width) {
int w = d.get(ChronoField.ALIGNED_WEEK_OF_MONTH);
if (width == 1) {
b.append(w);
}
} | [
"void",
"formatWeekOfMonth",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"w",
"=",
"d",
".",
"get",
"(",
"ChronoField",
".",
"ALIGNED_WEEK_OF_MONTH",
")",
";",
"if",
"(",
"width",
"==",
"1",
")",
"{",
"b"... | Format the week number of the month. | [
"Format",
"the",
"week",
"number",
"of",
"the",
"month",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L561-L566 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatISOWeekOfYear | void formatISOWeekOfYear(StringBuilder b, ZonedDateTime d, int width) {
int w = d.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
switch (width) {
case 2:
zeroPad2(b, w, 2);
break;
case 1:
b.append(w);
break;
}
} | java | void formatISOWeekOfYear(StringBuilder b, ZonedDateTime d, int width) {
int w = d.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
switch (width) {
case 2:
zeroPad2(b, w, 2);
break;
case 1:
b.append(w);
break;
}
} | [
"void",
"formatISOWeekOfYear",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"w",
"=",
"d",
".",
"get",
"(",
"IsoFields",
".",
"WEEK_OF_WEEK_BASED_YEAR",
")",
";",
"switch",
"(",
"width",
")",
"{",
"case",
"2... | Format the week number of the year. | [
"Format",
"the",
"week",
"number",
"of",
"the",
"year",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L571-L582 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatWeekday | void formatWeekday(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays) {
int weekday = d.getDayOfWeek().getValue() % 7;
switch (width) {
case 6:
b.append(weekdays.short_[weekday]);
break;
case 5:
b.append(weekdays.narrow[weekday]);
break;
case 4:
b.append(weekdays.wide[weekday]);
break;
case 3:
case 2:
case 1:
b.append(weekdays.abbreviated[weekday]);
break;
}
} | java | void formatWeekday(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays) {
int weekday = d.getDayOfWeek().getValue() % 7;
switch (width) {
case 6:
b.append(weekdays.short_[weekday]);
break;
case 5:
b.append(weekdays.narrow[weekday]);
break;
case 4:
b.append(weekdays.wide[weekday]);
break;
case 3:
case 2:
case 1:
b.append(weekdays.abbreviated[weekday]);
break;
}
} | [
"void",
"formatWeekday",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"weekdays",
")",
"{",
"int",
"weekday",
"=",
"d",
".",
"getDayOfWeek",
"(",
")",
".",
"getValue",
"(",
")",
"%",
"7",
";",
"switch",... | Format the weekday name. | [
"Format",
"the",
"weekday",
"name",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L587-L608 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatLocalWeekday | void formatLocalWeekday(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays, int firstDay) {
if (width > 2) {
formatWeekday(b, d, width, weekdays);
return;
}
if (width == 2) {
b.append('0');
}
formatWeekdayNumeric(b, d, firstDay);
} | java | void formatLocalWeekday(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays, int firstDay) {
if (width > 2) {
formatWeekday(b, d, width, weekdays);
return;
}
if (width == 2) {
b.append('0');
}
formatWeekdayNumeric(b, d, firstDay);
} | [
"void",
"formatLocalWeekday",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"weekdays",
",",
"int",
"firstDay",
")",
"{",
"if",
"(",
"width",
">",
"2",
")",
"{",
"formatWeekday",
"(",
"b",
",",
"d",
",",... | Format the numeric weekday, or the format name variant. | [
"Format",
"the",
"numeric",
"weekday",
"or",
"the",
"format",
"name",
"variant",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L613-L622 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatLocalWeekdayStandalone | void formatLocalWeekdayStandalone(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays, int firstDay) {
if (width > 2) {
formatWeekday(b, d, width, weekdays);
return;
}
formatWeekdayNumeric(b, d, firstDay);
} | java | void formatLocalWeekdayStandalone(StringBuilder b, ZonedDateTime d, int width, FieldVariants weekdays, int firstDay) {
if (width > 2) {
formatWeekday(b, d, width, weekdays);
return;
}
formatWeekdayNumeric(b, d, firstDay);
} | [
"void",
"formatLocalWeekdayStandalone",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"weekdays",
",",
"int",
"firstDay",
")",
"{",
"if",
"(",
"width",
">",
"2",
")",
"{",
"formatWeekday",
"(",
"b",
",",
"... | Format the numeric weekday, or the stand-alone name variant. | [
"Format",
"the",
"numeric",
"weekday",
"or",
"the",
"stand",
"-",
"alone",
"name",
"variant",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L627-L633 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatWeekdayNumeric | private void formatWeekdayNumeric(StringBuilder b, ZonedDateTime d, int firstDay) {
// Java returns ISO-8601 where Monday = 1 and Sunday = 7.
int weekday = d.getDayOfWeek().getValue();
// Adjust to the localized "first day of the week"
int w = (7 - firstDay + weekday) % 7 + 1;
b.append(w);
} | java | private void formatWeekdayNumeric(StringBuilder b, ZonedDateTime d, int firstDay) {
// Java returns ISO-8601 where Monday = 1 and Sunday = 7.
int weekday = d.getDayOfWeek().getValue();
// Adjust to the localized "first day of the week"
int w = (7 - firstDay + weekday) % 7 + 1;
b.append(w);
} | [
"private",
"void",
"formatWeekdayNumeric",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"firstDay",
")",
"{",
"// Java returns ISO-8601 where Monday = 1 and Sunday = 7.",
"int",
"weekday",
"=",
"d",
".",
"getDayOfWeek",
"(",
")",
".",
"getValue",
... | Convert from Java's ISO-8601 week number, where Monday = 1 and Sunday = 7.
We need to adjust this according to the locale's "first day of the week" which
in the US is Sunday = 0.
In the US, Tuesday will produce '3' or the 3rd day of the week:
weekday = 2 (ISO-8601 Tuesday == 2)
int w = (7 - 0 + weekday) % 7 + 1
w == 3
In the US, Saturday will produce '7', ending the week:
weekday = 6 (ISO-8601 Saturday == 6)
int w = (7 - 0 + weekday) % 7 + 1
w == 7 | [
"Convert",
"from",
"Java",
"s",
"ISO",
"-",
"8601",
"week",
"number",
"where",
"Monday",
"=",
"1",
"and",
"Sunday",
"=",
"7",
".",
"We",
"need",
"to",
"adjust",
"this",
"according",
"to",
"the",
"locale",
"s",
"first",
"day",
"of",
"the",
"week",
"wh... | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L653-L660 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatDayOfMonth | void formatDayOfMonth(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfMonth();
zeroPad2(b, day, width);
} | java | void formatDayOfMonth(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfMonth();
zeroPad2(b, day, width);
} | [
"void",
"formatDayOfMonth",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"day",
"=",
"d",
".",
"getDayOfMonth",
"(",
")",
";",
"zeroPad2",
"(",
"b",
",",
"day",
",",
"width",
")",
";",
"}"
] | Format the day of the month, optionally zero-padded. | [
"Format",
"the",
"day",
"of",
"the",
"month",
"optionally",
"zero",
"-",
"padded",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L665-L668 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatDayOfYear | void formatDayOfYear(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfYear();
int digits = day < 10 ? 1 : day < 100 ? 2 : 3;
switch (digits) {
case 1:
if (width > 1) {
b.append('0');
}
// fall through
case 2:
if (width > 2) {
b.append('0');
}
// fall through
case 3:
b.append(day);
break;
}
} | java | void formatDayOfYear(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfYear();
int digits = day < 10 ? 1 : day < 100 ? 2 : 3;
switch (digits) {
case 1:
if (width > 1) {
b.append('0');
}
// fall through
case 2:
if (width > 2) {
b.append('0');
}
// fall through
case 3:
b.append(day);
break;
}
} | [
"void",
"formatDayOfYear",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"day",
"=",
"d",
".",
"getDayOfYear",
"(",
")",
";",
"int",
"digits",
"=",
"day",
"<",
"10",
"?",
"1",
":",
"day",
"<",
"100",
"?... | Format the 3-digit day of the year, zero padded. | [
"Format",
"the",
"3",
"-",
"digit",
"day",
"of",
"the",
"year",
"zero",
"padded",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L673-L693 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatDayOfWeekInMonth | void formatDayOfWeekInMonth(StringBuilder b, ZonedDateTime d, int width) {
int day = ((d.getDayOfMonth() - 1) / 7) + 1;
b.append(day);
} | java | void formatDayOfWeekInMonth(StringBuilder b, ZonedDateTime d, int width) {
int day = ((d.getDayOfMonth() - 1) / 7) + 1;
b.append(day);
} | [
"void",
"formatDayOfWeekInMonth",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"day",
"=",
"(",
"(",
"d",
".",
"getDayOfMonth",
"(",
")",
"-",
"1",
")",
"/",
"7",
")",
"+",
"1",
";",
"b",
".",
"append"... | Numeric day of week in month, as in "2nd Wednesday in July". | [
"Numeric",
"day",
"of",
"week",
"in",
"month",
"as",
"in",
"2nd",
"Wednesday",
"in",
"July",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L698-L701 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatDayPeriod | void formatDayPeriod(StringBuilder b, ZonedDateTime d, int width, FieldVariants dayPeriods) {
int hours = d.getHour();
int index = hours < 12 ? 0 : 1;
switch (width) {
case 5:
b.append(dayPeriods.narrow[index]);
break;
case 4:
b.append(dayPeriods.wide[index]);
break;
case 3:
case 2:
case 1:
b.append(dayPeriods.abbreviated[index]);
break;
}
} | java | void formatDayPeriod(StringBuilder b, ZonedDateTime d, int width, FieldVariants dayPeriods) {
int hours = d.getHour();
int index = hours < 12 ? 0 : 1;
switch (width) {
case 5:
b.append(dayPeriods.narrow[index]);
break;
case 4:
b.append(dayPeriods.wide[index]);
break;
case 3:
case 2:
case 1:
b.append(dayPeriods.abbreviated[index]);
break;
}
} | [
"void",
"formatDayPeriod",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"FieldVariants",
"dayPeriods",
")",
"{",
"int",
"hours",
"=",
"d",
".",
"getHour",
"(",
")",
";",
"int",
"index",
"=",
"hours",
"<",
"12",
"?",
"... | Format the day period variant. | [
"Format",
"the",
"day",
"period",
"variant",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L706-L724 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatHours | void formatHours(StringBuilder b, ZonedDateTime d, int width, boolean twelveHour) {
int hours = d.getHour();
if (twelveHour && hours > 12) {
hours = hours - 12;
}
if (twelveHour && hours == 0) {
hours = 12;
}
zeroPad2(b, hours, width);
} | java | void formatHours(StringBuilder b, ZonedDateTime d, int width, boolean twelveHour) {
int hours = d.getHour();
if (twelveHour && hours > 12) {
hours = hours - 12;
}
if (twelveHour && hours == 0) {
hours = 12;
}
zeroPad2(b, hours, width);
} | [
"void",
"formatHours",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"boolean",
"twelveHour",
")",
"{",
"int",
"hours",
"=",
"d",
".",
"getHour",
"(",
")",
";",
"if",
"(",
"twelveHour",
"&&",
"hours",
">",
"12",
")",
... | Format the hours in 12- or 24-hour format, optionally zero-padded. | [
"Format",
"the",
"hours",
"in",
"12",
"-",
"or",
"24",
"-",
"hour",
"format",
"optionally",
"zero",
"-",
"padded",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L729-L738 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatMinutes | void formatMinutes(StringBuilder b, ZonedDateTime d, int width) {
zeroPad2(b, d.getMinute(), width);
} | java | void formatMinutes(StringBuilder b, ZonedDateTime d, int width) {
zeroPad2(b, d.getMinute(), width);
} | [
"void",
"formatMinutes",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"zeroPad2",
"(",
"b",
",",
"d",
".",
"getMinute",
"(",
")",
",",
"width",
")",
";",
"}"
] | Format the minutes, optionally zero-padded. | [
"Format",
"the",
"minutes",
"optionally",
"zero",
"-",
"padded",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L758-L760 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatSeconds | void formatSeconds(StringBuilder b, ZonedDateTime d, int width) {
zeroPad2(b, d.getSecond(), width);
} | java | void formatSeconds(StringBuilder b, ZonedDateTime d, int width) {
zeroPad2(b, d.getSecond(), width);
} | [
"void",
"formatSeconds",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"zeroPad2",
"(",
"b",
",",
"d",
".",
"getSecond",
"(",
")",
",",
"width",
")",
";",
"}"
] | Format the seconds, optionally zero-padded. | [
"Format",
"the",
"seconds",
"optionally",
"zero",
"-",
"padded",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L765-L767 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatFractionalSeconds | void formatFractionalSeconds(StringBuilder b, ZonedDateTime d, int width) {
// format up to 9 digits at nanosecond resolution.
int nano = d.getNano();
int f = 100000000;
while (width > 0 && f > 0) {
int digit = nano / f;
nano -= (digit * f);
f /= 10;
b.append(digit);
width--;
}
// fill out any trailing zeros if any are requested
while (width > 0) {
b.append('0');
width--;
}
} | java | void formatFractionalSeconds(StringBuilder b, ZonedDateTime d, int width) {
// format up to 9 digits at nanosecond resolution.
int nano = d.getNano();
int f = 100000000;
while (width > 0 && f > 0) {
int digit = nano / f;
nano -= (digit * f);
f /= 10;
b.append(digit);
width--;
}
// fill out any trailing zeros if any are requested
while (width > 0) {
b.append('0');
width--;
}
} | [
"void",
"formatFractionalSeconds",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"// format up to 9 digits at nanosecond resolution.",
"int",
"nano",
"=",
"d",
".",
"getNano",
"(",
")",
";",
"int",
"f",
"=",
"100000000",
";... | Format fractional seconds up to N digits. | [
"Format",
"fractional",
"seconds",
"up",
"to",
"N",
"digits",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L772-L789 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatTimeZone_O | void formatTimeZone_O(StringBuilder b, ZonedDateTime d, int width) {
int[] tz = getTzComponents(d);
switch (width) {
case 1:
wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], true);
break;
case 4:
wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], false);
break;
}
} | java | void formatTimeZone_O(StringBuilder b, ZonedDateTime d, int width) {
int[] tz = getTzComponents(d);
switch (width) {
case 1:
wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], true);
break;
case 4:
wrapTimeZoneGMT(b, tz[TZNEG] == -1, tz[TZHOURS], tz[TZMINS], false);
break;
}
} | [
"void",
"formatTimeZone_O",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"int",
"[",
"]",
"tz",
"=",
"getTzComponents",
"(",
"d",
")",
";",
"switch",
"(",
"width",
")",
"{",
"case",
"1",
":",
"wrapTimeZoneGMT",
"... | Format timezone in localized GMT format for field 'O'. | [
"Format",
"timezone",
"in",
"localized",
"GMT",
"format",
"for",
"field",
"O",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L795-L806 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatTimeZone_z | void formatTimeZone_z(StringBuilder b, ZonedDateTime d, int width) {
if (width > 4) {
return;
}
ZoneId zone = d.getZone();
ZoneRules zoneRules = null;
try {
zoneRules = zone.getRules();
} catch (ZoneRulesException e) {
// not expected, but catching for safety
return;
}
boolean daylight = zoneRules.isDaylightSavings(d.toInstant());
// Select long or short name variants and select the standard or daylight name.
Name variants = getTimeZoneName(zone.getId(), d, width == 4);
String name = variants == null ? null : (daylight ? variants.daylight() : variants.standard());
switch (width) {
case 4:
{
if (name != null) {
b.append(name);
} else {
// Falls back to 'OOOO'
formatTimeZone_O(b, d, 4);
}
break;
}
case 3:
case 2:
case 1:
{
if (name != null) {
b.append(name);
} else {
// Falls back to 'O'
formatTimeZone_O(b, d, 1);
}
break;
}
}
} | java | void formatTimeZone_z(StringBuilder b, ZonedDateTime d, int width) {
if (width > 4) {
return;
}
ZoneId zone = d.getZone();
ZoneRules zoneRules = null;
try {
zoneRules = zone.getRules();
} catch (ZoneRulesException e) {
// not expected, but catching for safety
return;
}
boolean daylight = zoneRules.isDaylightSavings(d.toInstant());
// Select long or short name variants and select the standard or daylight name.
Name variants = getTimeZoneName(zone.getId(), d, width == 4);
String name = variants == null ? null : (daylight ? variants.daylight() : variants.standard());
switch (width) {
case 4:
{
if (name != null) {
b.append(name);
} else {
// Falls back to 'OOOO'
formatTimeZone_O(b, d, 4);
}
break;
}
case 3:
case 2:
case 1:
{
if (name != null) {
b.append(name);
} else {
// Falls back to 'O'
formatTimeZone_O(b, d, 1);
}
break;
}
}
} | [
"void",
"formatTimeZone_z",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
")",
"{",
"if",
"(",
"width",
">",
"4",
")",
"{",
"return",
";",
"}",
"ZoneId",
"zone",
"=",
"d",
".",
"getZone",
"(",
")",
";",
"ZoneRules",
"zone... | Format a time zone using a non-location format. | [
"Format",
"a",
"time",
"zone",
"using",
"a",
"non",
"-",
"location",
"format",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L916-L961 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.getTzComponents | private int[] getTzComponents(ZonedDateTime d) {
ZoneOffset offset = d.getOffset();
int secs = offset.getTotalSeconds();
boolean negative = secs < 0;
if (negative) {
secs = -secs;
}
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
return new int[] { negative ? -1 : 1, secs, hours, mins };
} | java | private int[] getTzComponents(ZonedDateTime d) {
ZoneOffset offset = d.getOffset();
int secs = offset.getTotalSeconds();
boolean negative = secs < 0;
if (negative) {
secs = -secs;
}
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
return new int[] { negative ? -1 : 1, secs, hours, mins };
} | [
"private",
"int",
"[",
"]",
"getTzComponents",
"(",
"ZonedDateTime",
"d",
")",
"{",
"ZoneOffset",
"offset",
"=",
"d",
".",
"getOffset",
"(",
")",
";",
"int",
"secs",
"=",
"offset",
".",
"getTotalSeconds",
"(",
")",
";",
"boolean",
"negative",
"=",
"secs"... | Decode some fields about a time zone. | [
"Decode",
"some",
"fields",
"about",
"a",
"time",
"zone",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L1013-L1023 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.zeroPad2 | void zeroPad2(StringBuilder b, int value, int width) {
switch (width) {
case 2:
if (value < 10) {
b.append('0');
}
// fall through
case 1:
b.append(value);
break;
}
} | java | void zeroPad2(StringBuilder b, int value, int width) {
switch (width) {
case 2:
if (value < 10) {
b.append('0');
}
// fall through
case 1:
b.append(value);
break;
}
} | [
"void",
"zeroPad2",
"(",
"StringBuilder",
"b",
",",
"int",
"value",
",",
"int",
"width",
")",
"{",
"switch",
"(",
"width",
")",
"{",
"case",
"2",
":",
"if",
"(",
"value",
"<",
"10",
")",
"{",
"b",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
... | Format 2-digit number with 0-padding. | [
"Format",
"2",
"-",
"digit",
"number",
"with",
"0",
"-",
"padding",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L1028-L1040 | train |
Squarespace/cldr | examples/src/main/java/com/squarespace/cldr/examples/NumberFormatterDemo.java | NumberFormatterDemo.decimal | private static void decimal(CLDR.Locale locale, String[] numbers, DecimalFormatOptions opts) {
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
StringBuilder buf = new StringBuilder(" ");
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
fmt.formatDecimal(n, buf, opts);
System.out.println(buf.toString());
}
} | java | private static void decimal(CLDR.Locale locale, String[] numbers, DecimalFormatOptions opts) {
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
StringBuilder buf = new StringBuilder(" ");
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
fmt.formatDecimal(n, buf, opts);
System.out.println(buf.toString());
}
} | [
"private",
"static",
"void",
"decimal",
"(",
"CLDR",
".",
"Locale",
"locale",
",",
"String",
"[",
"]",
"numbers",
",",
"DecimalFormatOptions",
"opts",
")",
"{",
"for",
"(",
"String",
"num",
":",
"numbers",
")",
"{",
"BigDecimal",
"n",
"=",
"new",
"BigDec... | Format decimal numbers in this locale. | [
"Format",
"decimal",
"numbers",
"in",
"this",
"locale",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/examples/src/main/java/com/squarespace/cldr/examples/NumberFormatterDemo.java#L111-L119 | train |
Squarespace/cldr | examples/src/main/java/com/squarespace/cldr/examples/NumberFormatterDemo.java | NumberFormatterDemo.money | private static void money(
CLDR.Locale locale, CLDR.Currency[] currencies, String[] numbers, CurrencyFormatOptions opts) {
for (CLDR.Currency currency : currencies) {
System.out.println("Currency " + currency);
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
StringBuilder buf = new StringBuilder(" ");
fmt.formatCurrency(n, currency, buf, opts);
System.out.println(buf.toString());
}
System.out.println();
}
System.out.println();
} | java | private static void money(
CLDR.Locale locale, CLDR.Currency[] currencies, String[] numbers, CurrencyFormatOptions opts) {
for (CLDR.Currency currency : currencies) {
System.out.println("Currency " + currency);
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
StringBuilder buf = new StringBuilder(" ");
fmt.formatCurrency(n, currency, buf, opts);
System.out.println(buf.toString());
}
System.out.println();
}
System.out.println();
} | [
"private",
"static",
"void",
"money",
"(",
"CLDR",
".",
"Locale",
"locale",
",",
"CLDR",
".",
"Currency",
"[",
"]",
"currencies",
",",
"String",
"[",
"]",
"numbers",
",",
"CurrencyFormatOptions",
"opts",
")",
"{",
"for",
"(",
"CLDR",
".",
"Currency",
"cu... | Format numbers in this locale for several currencies. | [
"Format",
"numbers",
"in",
"this",
"locale",
"for",
"several",
"currencies",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/examples/src/main/java/com/squarespace/cldr/examples/NumberFormatterDemo.java#L124-L139 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.getFactors | public List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units) {
List<UnitValue> result = new ArrayList<>();
for (int i = 0; i < units.length; i++) {
UnitFactor factor = resolve(units[i], base);
if (factor != null) {
BigDecimal n = factor.rational().compute(mode);
result.add(new UnitValue(n, units[i]));
}
}
return result;
} | java | public List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units) {
List<UnitValue> result = new ArrayList<>();
for (int i = 0; i < units.length; i++) {
UnitFactor factor = resolve(units[i], base);
if (factor != null) {
BigDecimal n = factor.rational().compute(mode);
result.add(new UnitValue(n, units[i]));
}
}
return result;
} | [
"public",
"List",
"<",
"UnitValue",
">",
"getFactors",
"(",
"Unit",
"base",
",",
"RoundingMode",
"mode",
",",
"Unit",
"...",
"units",
")",
"{",
"List",
"<",
"UnitValue",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
... | Return an array of factors to convert the array of units to the given base. | [
"Return",
"an",
"array",
"of",
"factors",
"to",
"convert",
"the",
"array",
"of",
"units",
"to",
"the",
"given",
"base",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L87-L97 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.add | protected UnitFactorMap add(Unit unit, String n, Unit base) {
check(unit);
check(base);
if (unit == base) {
throw new IllegalArgumentException("Attempt to define a unit " + unit + " in terms of itself.");
}
// Set the factor and its inverse if nothing already exists.
Rational rational = new Rational(n);
set(unit, rational, base, true);
return this;
} | java | protected UnitFactorMap add(Unit unit, String n, Unit base) {
check(unit);
check(base);
if (unit == base) {
throw new IllegalArgumentException("Attempt to define a unit " + unit + " in terms of itself.");
}
// Set the factor and its inverse if nothing already exists.
Rational rational = new Rational(n);
set(unit, rational, base, true);
return this;
} | [
"protected",
"UnitFactorMap",
"add",
"(",
"Unit",
"unit",
",",
"String",
"n",
",",
"Unit",
"base",
")",
"{",
"check",
"(",
"unit",
")",
";",
"check",
"(",
"base",
")",
";",
"if",
"(",
"unit",
"==",
"base",
")",
"{",
"throw",
"new",
"IllegalArgumentEx... | Set a factor to convert the unit into a given base. | [
"Set",
"a",
"factor",
"to",
"convert",
"the",
"unit",
"into",
"a",
"given",
"base",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L102-L113 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.complete | protected UnitFactorMap complete() {
Set<Unit> units = new LinkedHashSet<>();
// Add reverse mappings for all populated units.
for (Unit from : factors.keySet()) {
units.add(from);
for (Map.Entry<Unit, UnitFactor> entry : factors.get(from).entrySet()) {
Unit to = entry.getKey();
units.add(to);
UnitFactor factor = entry.getValue();
set(to, factor.rational().reciprocal(), from, false);
}
}
// For each pair of units that differ, resolve the best conversion path
// to produce a final conversion factor.
for (Unit from : units) {
for (Unit to : units) {
if (from == to) {
continue;
}
// If a direct conversion exists continue.
UnitFactor factor = get(from, to);
if (factor != null) {
continue;
}
// Get or create the mapping.
Map<Unit, UnitFactor> map = factors.get(from);
if (map == null) {
map = new EnumMap<>(Unit.class);
factors.put(from, map);
}
// Resolve the conversion factor using the best path.
factor = resolve(from, to);
// If a factor exists we overwrite it if we can set a factor with a lower total precision.
UnitFactor old = map.get(from);
// Add this conversion factor if none exists or if this factor's precision
// is lower than the existing conversion.
Rational rational = factor.rational();
if (old == null || totalPrecision(rational) < totalPrecision(old.rational())) {
set(from, rational, to, true);
}
}
}
// Finally, sort the units from largest to smallest, where possible.
List<Unit> unitList = new ArrayList<>(Unit.forCategory(category));
unitList.sort((a, b) -> {
UnitFactor f = get(a, b);
// Units in some categories cannot be compared so return an arbitrary order.
if (f == null) {
return -1;
}
BigDecimal r = f.rational().compute(RoundingMode.HALF_EVEN);
return BigDecimal.ONE.compareTo(r);
});
// Update the unit ordering map with the indices from the sorted list.
for (int i = 0; i < unitList.size(); i++) {
unitOrder.put(unitList.get(i), i);
}
return this;
} | java | protected UnitFactorMap complete() {
Set<Unit> units = new LinkedHashSet<>();
// Add reverse mappings for all populated units.
for (Unit from : factors.keySet()) {
units.add(from);
for (Map.Entry<Unit, UnitFactor> entry : factors.get(from).entrySet()) {
Unit to = entry.getKey();
units.add(to);
UnitFactor factor = entry.getValue();
set(to, factor.rational().reciprocal(), from, false);
}
}
// For each pair of units that differ, resolve the best conversion path
// to produce a final conversion factor.
for (Unit from : units) {
for (Unit to : units) {
if (from == to) {
continue;
}
// If a direct conversion exists continue.
UnitFactor factor = get(from, to);
if (factor != null) {
continue;
}
// Get or create the mapping.
Map<Unit, UnitFactor> map = factors.get(from);
if (map == null) {
map = new EnumMap<>(Unit.class);
factors.put(from, map);
}
// Resolve the conversion factor using the best path.
factor = resolve(from, to);
// If a factor exists we overwrite it if we can set a factor with a lower total precision.
UnitFactor old = map.get(from);
// Add this conversion factor if none exists or if this factor's precision
// is lower than the existing conversion.
Rational rational = factor.rational();
if (old == null || totalPrecision(rational) < totalPrecision(old.rational())) {
set(from, rational, to, true);
}
}
}
// Finally, sort the units from largest to smallest, where possible.
List<Unit> unitList = new ArrayList<>(Unit.forCategory(category));
unitList.sort((a, b) -> {
UnitFactor f = get(a, b);
// Units in some categories cannot be compared so return an arbitrary order.
if (f == null) {
return -1;
}
BigDecimal r = f.rational().compute(RoundingMode.HALF_EVEN);
return BigDecimal.ONE.compareTo(r);
});
// Update the unit ordering map with the indices from the sorted list.
for (int i = 0; i < unitList.size(); i++) {
unitOrder.put(unitList.get(i), i);
}
return this;
} | [
"protected",
"UnitFactorMap",
"complete",
"(",
")",
"{",
"Set",
"<",
"Unit",
">",
"units",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"// Add reverse mappings for all populated units.",
"for",
"(",
"Unit",
"from",
":",
"factors",
".",
"keySet",
"(",
")"... | Creates direct conversion factors between all units by resolving the
best conversion path and setting an explicit mapping if one does
not already exist. | [
"Creates",
"direct",
"conversion",
"factors",
"between",
"all",
"units",
"by",
"resolving",
"the",
"best",
"conversion",
"path",
"and",
"setting",
"an",
"explicit",
"mapping",
"if",
"one",
"does",
"not",
"already",
"exist",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L127-L195 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.resolve | protected UnitFactor resolve(Unit from, Unit to) {
if (from == to) {
return new UnitFactor(Rational.ONE, to);
}
List<UnitFactor> path = getPath(from, to);
if (path.isEmpty()) {
throw new IllegalStateException("Can't find a path to convert " + from + " units into " + to);
}
UnitFactor factor = path.get(0);
int size = path.size();
for (int i = 1; i < size; i++) {
factor = factor.multiply(path.get(i));
}
return factor;
} | java | protected UnitFactor resolve(Unit from, Unit to) {
if (from == to) {
return new UnitFactor(Rational.ONE, to);
}
List<UnitFactor> path = getPath(from, to);
if (path.isEmpty()) {
throw new IllegalStateException("Can't find a path to convert " + from + " units into " + to);
}
UnitFactor factor = path.get(0);
int size = path.size();
for (int i = 1; i < size; i++) {
factor = factor.multiply(path.get(i));
}
return factor;
} | [
"protected",
"UnitFactor",
"resolve",
"(",
"Unit",
"from",
",",
"Unit",
"to",
")",
"{",
"if",
"(",
"from",
"==",
"to",
")",
"{",
"return",
"new",
"UnitFactor",
"(",
"Rational",
".",
"ONE",
",",
"to",
")",
";",
"}",
"List",
"<",
"UnitFactor",
">",
"... | Find the best conversion factor path between the FROM and TO
units, multiply them together and return the resulting factor. | [
"Find",
"the",
"best",
"conversion",
"factor",
"path",
"between",
"the",
"FROM",
"and",
"TO",
"units",
"multiply",
"them",
"together",
"and",
"return",
"the",
"resulting",
"factor",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L201-L216 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.precisionSum | private int precisionSum(List<UnitFactor> factors) {
return factors.stream().map(f -> totalPrecision(f.rational())).reduce(0, Math::addExact);
} | java | private int precisionSum(List<UnitFactor> factors) {
return factors.stream().map(f -> totalPrecision(f.rational())).reduce(0, Math::addExact);
} | [
"private",
"int",
"precisionSum",
"(",
"List",
"<",
"UnitFactor",
">",
"factors",
")",
"{",
"return",
"factors",
".",
"stream",
"(",
")",
".",
"map",
"(",
"f",
"->",
"totalPrecision",
"(",
"f",
".",
"rational",
"(",
")",
")",
")",
".",
"reduce",
"(",... | Reduces the list of factors by adding together the precision
for all numerators and denominators. | [
"Reduces",
"the",
"list",
"of",
"factors",
"by",
"adding",
"together",
"the",
"precision",
"for",
"all",
"numerators",
"and",
"denominators",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L250-L252 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.get | public UnitFactor get(Unit from, Unit to) {
Map<Unit, UnitFactor> map = factors.get(from);
if (map != null) {
UnitFactor factor = map.get(to);
if (factor != null) {
return factor;
}
}
return null;
} | java | public UnitFactor get(Unit from, Unit to) {
Map<Unit, UnitFactor> map = factors.get(from);
if (map != null) {
UnitFactor factor = map.get(to);
if (factor != null) {
return factor;
}
}
return null;
} | [
"public",
"UnitFactor",
"get",
"(",
"Unit",
"from",
",",
"Unit",
"to",
")",
"{",
"Map",
"<",
"Unit",
",",
"UnitFactor",
">",
"map",
"=",
"factors",
".",
"get",
"(",
"from",
")",
";",
"if",
"(",
"map",
"!=",
"null",
")",
"{",
"UnitFactor",
"factor",... | Find an exact conversion factor between the from and to units, or return
null if none exists. | [
"Find",
"an",
"exact",
"conversion",
"factor",
"between",
"the",
"from",
"and",
"to",
"units",
"or",
"return",
"null",
"if",
"none",
"exists",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L305-L314 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.dump | public String dump(Unit unit) {
StringBuilder buf = new StringBuilder();
buf.append(unit).append(":\n");
Map<Unit, UnitFactor> map = factors.get(unit);
for (Unit base : map.keySet()) {
UnitFactor factor = map.get(base);
buf.append(" ").append(factor).append(" ");
buf.append(factor.rational().compute(RoundingMode.HALF_EVEN).toPlainString()).append('\n');
}
return buf.toString();
} | java | public String dump(Unit unit) {
StringBuilder buf = new StringBuilder();
buf.append(unit).append(":\n");
Map<Unit, UnitFactor> map = factors.get(unit);
for (Unit base : map.keySet()) {
UnitFactor factor = map.get(base);
buf.append(" ").append(factor).append(" ");
buf.append(factor.rational().compute(RoundingMode.HALF_EVEN).toPlainString()).append('\n');
}
return buf.toString();
} | [
"public",
"String",
"dump",
"(",
"Unit",
"unit",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buf",
".",
"append",
"(",
"unit",
")",
".",
"append",
"(",
"\":\\n\"",
")",
";",
"Map",
"<",
"Unit",
",",
"UnitFactor",
">... | Debugging conversion factors. | [
"Debugging",
"conversion",
"factors",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L319-L329 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.set | private void set(Unit unit, Rational rational, Unit base, boolean replace) {
Map<Unit, UnitFactor> map = factors.get(unit);
if (map == null) {
map = new EnumMap<>(Unit.class);
factors.put(unit, map);
}
if (replace || !map.containsKey(base)) {
map.put(base, new UnitFactor(rational, base));
}
} | java | private void set(Unit unit, Rational rational, Unit base, boolean replace) {
Map<Unit, UnitFactor> map = factors.get(unit);
if (map == null) {
map = new EnumMap<>(Unit.class);
factors.put(unit, map);
}
if (replace || !map.containsKey(base)) {
map.put(base, new UnitFactor(rational, base));
}
} | [
"private",
"void",
"set",
"(",
"Unit",
"unit",
",",
"Rational",
"rational",
",",
"Unit",
"base",
",",
"boolean",
"replace",
")",
"{",
"Map",
"<",
"Unit",
",",
"UnitFactor",
">",
"map",
"=",
"factors",
".",
"get",
"(",
"unit",
")",
";",
"if",
"(",
"... | Set a conversion factor that converts UNIT to BASE. If the replace
flag is true we always overwrite the mapping. | [
"Set",
"a",
"conversion",
"factor",
"that",
"converts",
"UNIT",
"to",
"BASE",
".",
"If",
"the",
"replace",
"flag",
"is",
"true",
"we",
"always",
"overwrite",
"the",
"mapping",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L335-L344 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.list | private List<UnitFactor> list(UnitFactor factor) {
List<UnitFactor> list = new ArrayList<>();
list.add(factor);
return list;
} | java | private List<UnitFactor> list(UnitFactor factor) {
List<UnitFactor> list = new ArrayList<>();
list.add(factor);
return list;
} | [
"private",
"List",
"<",
"UnitFactor",
">",
"list",
"(",
"UnitFactor",
"factor",
")",
"{",
"List",
"<",
"UnitFactor",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"list",
".",
"add",
"(",
"factor",
")",
";",
"return",
"list",
";",
"}"
] | Construct a list containing just this factor. | [
"Construct",
"a",
"list",
"containing",
"just",
"this",
"factor",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L349-L353 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java | UnitFactorMap.getBases | private List<Unit> getBases(Unit unit) {
Map<Unit, UnitFactor> map = factors.get(unit);
if (map != null) {
return map.values().stream().map(u -> u.unit()).collect(Collectors.toList());
}
return Collections.emptyList();
} | java | private List<Unit> getBases(Unit unit) {
Map<Unit, UnitFactor> map = factors.get(unit);
if (map != null) {
return map.values().stream().map(u -> u.unit()).collect(Collectors.toList());
}
return Collections.emptyList();
} | [
"private",
"List",
"<",
"Unit",
">",
"getBases",
"(",
"Unit",
"unit",
")",
"{",
"Map",
"<",
"Unit",
",",
"UnitFactor",
">",
"map",
"=",
"factors",
".",
"get",
"(",
"unit",
")",
";",
"if",
"(",
"map",
"!=",
"null",
")",
"{",
"return",
"map",
".",
... | Fetch all of the existing bases for the given unit. A base is a
conversion factor that was directly added, or the inverse of one that
was directly added. | [
"Fetch",
"all",
"of",
"the",
"existing",
"bases",
"for",
"the",
"given",
"unit",
".",
"A",
"base",
"is",
"a",
"conversion",
"factor",
"that",
"was",
"directly",
"added",
"or",
"the",
"inverse",
"of",
"one",
"that",
"was",
"directly",
"added",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L369-L375 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/DistanceMap.java | DistanceMap.hash | private static int hash(String k1, String k2) {
int h = (k1.hashCode() * 33) + k2.hashCode();
return h ^ (h >>> 16);
} | java | private static int hash(String k1, String k2) {
int h = (k1.hashCode() * 33) + k2.hashCode();
return h ^ (h >>> 16);
} | [
"private",
"static",
"int",
"hash",
"(",
"String",
"k1",
",",
"String",
"k2",
")",
"{",
"int",
"h",
"=",
"(",
"k1",
".",
"hashCode",
"(",
")",
"*",
"33",
")",
"+",
"k2",
".",
"hashCode",
"(",
")",
";",
"return",
"h",
"^",
"(",
"h",
">>>",
"16... | Combine the hash codes for the two keys, then mix. | [
"Combine",
"the",
"hash",
"codes",
"for",
"the",
"two",
"keys",
"then",
"mix",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/DistanceMap.java#L103-L106 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/numbers/NumberFormatContext.java | NumberFormatContext.setPattern | public void setPattern(NumberPattern pattern, int _maxSigDigits, int _minSigDigits) {
Format format = pattern.format();
minIntDigits = orDefault(options.minimumIntegerDigits(), format.minimumIntegerDigits());
maxFracDigits = currencyDigits == -1 ? format.maximumFractionDigits() : currencyDigits;
maxFracDigits = orDefault(options.maximumFractionDigits(), maxFracDigits);
minFracDigits = currencyDigits == -1 ? format.minimumFractionDigits() : currencyDigits;
minFracDigits = orDefault(options.minimumFractionDigits(), minFracDigits);
boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC;
if (useSignificant) {
maxSigDigits = orDefault(options.maximumSignificantDigits(), _maxSigDigits);
minSigDigits = orDefault(options.minimumSignificantDigits(), _minSigDigits);
} else {
maxSigDigits = -1;
minSigDigits = -1;
}
} | java | public void setPattern(NumberPattern pattern, int _maxSigDigits, int _minSigDigits) {
Format format = pattern.format();
minIntDigits = orDefault(options.minimumIntegerDigits(), format.minimumIntegerDigits());
maxFracDigits = currencyDigits == -1 ? format.maximumFractionDigits() : currencyDigits;
maxFracDigits = orDefault(options.maximumFractionDigits(), maxFracDigits);
minFracDigits = currencyDigits == -1 ? format.minimumFractionDigits() : currencyDigits;
minFracDigits = orDefault(options.minimumFractionDigits(), minFracDigits);
boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC;
if (useSignificant) {
maxSigDigits = orDefault(options.maximumSignificantDigits(), _maxSigDigits);
minSigDigits = orDefault(options.minimumSignificantDigits(), _minSigDigits);
} else {
maxSigDigits = -1;
minSigDigits = -1;
}
} | [
"public",
"void",
"setPattern",
"(",
"NumberPattern",
"pattern",
",",
"int",
"_maxSigDigits",
",",
"int",
"_minSigDigits",
")",
"{",
"Format",
"format",
"=",
"pattern",
".",
"format",
"(",
")",
";",
"minIntDigits",
"=",
"orDefault",
"(",
"options",
".",
"min... | Set the pattern and initialize parameters based on the arguments, pattern and options settings. | [
"Set",
"the",
"pattern",
"and",
"initialize",
"parameters",
"based",
"on",
"the",
"arguments",
"pattern",
"and",
"options",
"settings",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberFormatContext.java#L54-L72 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/numbers/NumberFormatContext.java | NumberFormatContext.adjust | public BigDecimal adjust(BigDecimal n) {
return NumberFormattingUtils.setup(n,
options.roundMode(), formatMode, minIntDigits, maxFracDigits, minFracDigits, maxSigDigits, minSigDigits);
} | java | public BigDecimal adjust(BigDecimal n) {
return NumberFormattingUtils.setup(n,
options.roundMode(), formatMode, minIntDigits, maxFracDigits, minFracDigits, maxSigDigits, minSigDigits);
} | [
"public",
"BigDecimal",
"adjust",
"(",
"BigDecimal",
"n",
")",
"{",
"return",
"NumberFormattingUtils",
".",
"setup",
"(",
"n",
",",
"options",
".",
"roundMode",
"(",
")",
",",
"formatMode",
",",
"minIntDigits",
",",
"maxFracDigits",
",",
"minFracDigits",
",",
... | Adjust the number using all of the options. | [
"Adjust",
"the",
"number",
"using",
"all",
"of",
"the",
"options",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberFormatContext.java#L77-L80 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java | DateTimePatternParser.splitIntervalPattern | public Pair<List<Node>, List<Node>> splitIntervalPattern(String raw) {
List<Node> pattern = parse(raw);
Set<Character> seen = new HashSet<>();
List<Node> fst = new ArrayList<>();
List<Node> snd = new ArrayList<>();
// Indicates we've seen a repeated field.
boolean boundary = false;
for (Node node : pattern) {
if (node instanceof Field) {
char ch = ((Field) node).ch();
if (seen.contains(ch)) {
boundary = true;
} else {
seen.add(ch);
}
}
if (boundary) {
snd.add(node);
} else {
fst.add(node);
}
}
return Pair.pair(fst, snd);
} | java | public Pair<List<Node>, List<Node>> splitIntervalPattern(String raw) {
List<Node> pattern = parse(raw);
Set<Character> seen = new HashSet<>();
List<Node> fst = new ArrayList<>();
List<Node> snd = new ArrayList<>();
// Indicates we've seen a repeated field.
boolean boundary = false;
for (Node node : pattern) {
if (node instanceof Field) {
char ch = ((Field) node).ch();
if (seen.contains(ch)) {
boundary = true;
} else {
seen.add(ch);
}
}
if (boundary) {
snd.add(node);
} else {
fst.add(node);
}
}
return Pair.pair(fst, snd);
} | [
"public",
"Pair",
"<",
"List",
"<",
"Node",
">",
",",
"List",
"<",
"Node",
">",
">",
"splitIntervalPattern",
"(",
"String",
"raw",
")",
"{",
"List",
"<",
"Node",
">",
"pattern",
"=",
"parse",
"(",
"raw",
")",
";",
"Set",
"<",
"Character",
">",
"see... | Looks for the first repeated field in the pattern, splitting it into
two parts on that boundary.
For example, the pattern "HH:mm - HH:mm v" will be split into two
patterns: "HH:mm - " and "HH:mm v" when we see the 'H' field for
the 2nd time. | [
"Looks",
"for",
"the",
"first",
"repeated",
"field",
"in",
"the",
"pattern",
"splitting",
"it",
"into",
"two",
"parts",
"on",
"that",
"boundary",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java#L27-L54 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java | DateTimePatternParser.render | public static String render(List<Node> nodes) {
StringBuilder buf = new StringBuilder();
for (Node node : nodes) {
if (node instanceof Text) {
String text = ((Text) node).text;
boolean inquote = false;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
switch (ch) {
case 'G':
case 'y':
case 'Y':
case 'u':
case 'U':
case 'r':
case 'Q':
case 'q':
case 'M':
case 'L':
case 'l':
case 'w':
case 'W':
case 'd':
case 'D':
case 'F':
case 'g':
case 'E':
case 'e':
case 'c':
case 'a':
case 'b':
case 'B':
case 'h':
case 'H':
case 'K':
case 'k':
case 'j':
case 'J':
case 'C':
case 'm':
case 's':
case 'S':
case 'A':
case 'z':
case 'Z':
case 'O':
case 'v':
case 'V':
case 'X':
case 'x':
if (!inquote) {
buf.append('\'');
}
buf.append(ch);
break;
default:
if (inquote) {
buf.append('\'');
}
buf.append(ch);
break;
}
}
} else if (node instanceof Field) {
Field field = (Field) node;
for (int i = 0; i < field.width; i++) {
buf.append(field.ch);
}
}
}
return buf.toString();
} | java | public static String render(List<Node> nodes) {
StringBuilder buf = new StringBuilder();
for (Node node : nodes) {
if (node instanceof Text) {
String text = ((Text) node).text;
boolean inquote = false;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
switch (ch) {
case 'G':
case 'y':
case 'Y':
case 'u':
case 'U':
case 'r':
case 'Q':
case 'q':
case 'M':
case 'L':
case 'l':
case 'w':
case 'W':
case 'd':
case 'D':
case 'F':
case 'g':
case 'E':
case 'e':
case 'c':
case 'a':
case 'b':
case 'B':
case 'h':
case 'H':
case 'K':
case 'k':
case 'j':
case 'J':
case 'C':
case 'm':
case 's':
case 'S':
case 'A':
case 'z':
case 'Z':
case 'O':
case 'v':
case 'V':
case 'X':
case 'x':
if (!inquote) {
buf.append('\'');
}
buf.append(ch);
break;
default:
if (inquote) {
buf.append('\'');
}
buf.append(ch);
break;
}
}
} else if (node instanceof Field) {
Field field = (Field) node;
for (int i = 0; i < field.width; i++) {
buf.append(field.ch);
}
}
}
return buf.toString();
} | [
"public",
"static",
"String",
"render",
"(",
"List",
"<",
"Node",
">",
"nodes",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Node",
"node",
":",
"nodes",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Text",
... | Render the compiled pattern back into string form. | [
"Render",
"the",
"compiled",
"pattern",
"back",
"into",
"string",
"form",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java#L59-L131 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java | DateTimePatternParser.parse | public List<Node> parse(String raw) {
// holds literal text as we parse
StringBuilder buf = new StringBuilder();
// current field character, \0 if none
char field = '\0';
// current field width
int width = 0;
// flag indicating we're inside a literal string
boolean inquote = false;
// length of input pattern
int length = raw.length();
// current input pattern index
int i = 0;
List<Node> nodes = new ArrayList<>();
while (i < length) {
char ch = raw.charAt(i);
// Handle appending / terminating the single-quote delimited sequence.
if (inquote) {
if (ch == '\'') {
inquote = false;
field = '\0';
} else {
buf.append(ch);
}
i++;
continue;
}
switch (ch) {
// Date pattern field characters.
case 'G':
case 'y':
case 'Y':
case 'u':
case 'U':
case 'r':
case 'Q':
case 'q':
case 'M':
case 'L':
case 'l':
case 'w':
case 'W':
case 'd':
case 'D':
case 'F':
case 'g':
case 'E':
case 'e':
case 'c':
case 'a':
case 'b':
case 'B':
case 'h':
case 'H':
case 'K':
case 'k':
case 'j':
case 'J':
case 'C':
case 'm':
case 's':
case 'S':
case 'A':
case 'z':
case 'Z':
case 'O':
case 'v':
case 'V':
case 'X':
case 'x':
// Before we start this field, check if we have text to push.
if (buf.length() > 0) {
nodes.add(new Text(buf.toString()));
buf.setLength(0);
}
// A change in character indicates we're starting a new field;
// otherwise we're widening an existing field.
if (ch != field) {
// If we have a field defined, add it.
if (field != '\0') {
nodes.add(new Field(field, width));
}
// Start a new field.
field = ch;
width = 1;
} else {
// Widen the current field.
width++;
}
// Indicate we've started a new field.
break;
default:
// If we have a current field, add it.
if (field != '\0') {
nodes.add(new Field(field, width));
}
// Clear the field.
field = '\0';
// Single quotes escape literal characters used for field patterns.
if (ch == '\'') {
inquote = true;
} else {
// Append a character
buf.append(ch);
}
break;
}
i++;
}
if (width > 0 && field != '\0') {
nodes.add(new Field(field, width));
} else if (buf.length() > 0) {
nodes.add(new Text(buf.toString()));
}
return nodes;
} | java | public List<Node> parse(String raw) {
// holds literal text as we parse
StringBuilder buf = new StringBuilder();
// current field character, \0 if none
char field = '\0';
// current field width
int width = 0;
// flag indicating we're inside a literal string
boolean inquote = false;
// length of input pattern
int length = raw.length();
// current input pattern index
int i = 0;
List<Node> nodes = new ArrayList<>();
while (i < length) {
char ch = raw.charAt(i);
// Handle appending / terminating the single-quote delimited sequence.
if (inquote) {
if (ch == '\'') {
inquote = false;
field = '\0';
} else {
buf.append(ch);
}
i++;
continue;
}
switch (ch) {
// Date pattern field characters.
case 'G':
case 'y':
case 'Y':
case 'u':
case 'U':
case 'r':
case 'Q':
case 'q':
case 'M':
case 'L':
case 'l':
case 'w':
case 'W':
case 'd':
case 'D':
case 'F':
case 'g':
case 'E':
case 'e':
case 'c':
case 'a':
case 'b':
case 'B':
case 'h':
case 'H':
case 'K':
case 'k':
case 'j':
case 'J':
case 'C':
case 'm':
case 's':
case 'S':
case 'A':
case 'z':
case 'Z':
case 'O':
case 'v':
case 'V':
case 'X':
case 'x':
// Before we start this field, check if we have text to push.
if (buf.length() > 0) {
nodes.add(new Text(buf.toString()));
buf.setLength(0);
}
// A change in character indicates we're starting a new field;
// otherwise we're widening an existing field.
if (ch != field) {
// If we have a field defined, add it.
if (field != '\0') {
nodes.add(new Field(field, width));
}
// Start a new field.
field = ch;
width = 1;
} else {
// Widen the current field.
width++;
}
// Indicate we've started a new field.
break;
default:
// If we have a current field, add it.
if (field != '\0') {
nodes.add(new Field(field, width));
}
// Clear the field.
field = '\0';
// Single quotes escape literal characters used for field patterns.
if (ch == '\'') {
inquote = true;
} else {
// Append a character
buf.append(ch);
}
break;
}
i++;
}
if (width > 0 && field != '\0') {
nodes.add(new Field(field, width));
} else if (buf.length() > 0) {
nodes.add(new Text(buf.toString()));
}
return nodes;
} | [
"public",
"List",
"<",
"Node",
">",
"parse",
"(",
"String",
"raw",
")",
"{",
"// holds literal text as we parse",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"// current field character, \\0 if none",
"char",
"field",
"=",
"'",
"'",
";",
... | Parses a CLDR date-time pattern into a series of Text and Field nodes. | [
"Parses",
"a",
"CLDR",
"date",
"-",
"time",
"pattern",
"into",
"a",
"series",
"of",
"Text",
"and",
"Field",
"nodes",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/parse/DateTimePatternParser.java#L136-L272 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.generate | public static void generate(Path outputDir) throws IOException {
DataReader reader = DataReader.get();
CalendarCodeGenerator datetimeGenerator = new CalendarCodeGenerator();
Map<LocaleID, ClassName> dateClasses = datetimeGenerator.generate(outputDir, reader);
PluralCodeGenerator pluralGenerator = new PluralCodeGenerator();
pluralGenerator.generate(outputDir, reader);
NumberCodeGenerator numberGenerator = new NumberCodeGenerator();
Map<LocaleID, ClassName> numberClasses = numberGenerator.generate(outputDir, reader);
LanguageCodeGenerator languageGenerator = new LanguageCodeGenerator();
languageGenerator.generate(outputDir, reader);
MethodSpec registerCalendars = indexFormatters("registerCalendars", "registerCalendarFormatter", dateClasses);
MethodSpec registerNumbers = indexFormatters("registerNumbers", "registerNumberFormatter", numberClasses);
MethodSpec constructor = MethodSpec.constructorBuilder()
.addModifiers(PRIVATE)
.build();
FieldSpec instance = FieldSpec.builder(CLDR, "instance", PRIVATE, STATIC, FINAL)
.build();
MethodSpec getter = MethodSpec.methodBuilder("get")
.addModifiers(PUBLIC, STATIC)
.returns(CLDR)
.addStatement("return instance")
.build();
TypeSpec.Builder type = TypeSpec.classBuilder("CLDR")
.addModifiers(PUBLIC)
.superclass(CLDR_BASE)
.addMethod(constructor)
.addMethod(getter)
.addMethod(registerCalendars)
.addMethod(registerNumbers);
Set<LocaleID> availableLocales = reader.availableLocales()
.stream()
.map(s -> LocaleID.parse(s))
.collect(Collectors.toSet());
createLocales(type, reader.defaultContent(), availableLocales);
createLanguageAliases(type, reader.languageAliases());
createTerritoryAliases(type, reader.territoryAliases());
createLikelySubtags(type, reader.likelySubtags());
createCurrencies(type, numberGenerator.getCurrencies(reader));
addPluralRules(type);
// Initialize all static maps.
type.addStaticBlock(CodeBlock.builder()
.addStatement("registerCalendars()")
.addStatement("registerNumbers()")
.addStatement("registerDefaultContent()")
.addStatement("registerLanguageAliases()")
.addStatement("registerTerritoryAliases()")
.addStatement("registerLikelySubtags()")
.addStatement("instance = new CLDR()").build());
type.addField(instance);
saveClass(outputDir, PACKAGE_CLDR, "CLDR", type.build());
} | java | public static void generate(Path outputDir) throws IOException {
DataReader reader = DataReader.get();
CalendarCodeGenerator datetimeGenerator = new CalendarCodeGenerator();
Map<LocaleID, ClassName> dateClasses = datetimeGenerator.generate(outputDir, reader);
PluralCodeGenerator pluralGenerator = new PluralCodeGenerator();
pluralGenerator.generate(outputDir, reader);
NumberCodeGenerator numberGenerator = new NumberCodeGenerator();
Map<LocaleID, ClassName> numberClasses = numberGenerator.generate(outputDir, reader);
LanguageCodeGenerator languageGenerator = new LanguageCodeGenerator();
languageGenerator.generate(outputDir, reader);
MethodSpec registerCalendars = indexFormatters("registerCalendars", "registerCalendarFormatter", dateClasses);
MethodSpec registerNumbers = indexFormatters("registerNumbers", "registerNumberFormatter", numberClasses);
MethodSpec constructor = MethodSpec.constructorBuilder()
.addModifiers(PRIVATE)
.build();
FieldSpec instance = FieldSpec.builder(CLDR, "instance", PRIVATE, STATIC, FINAL)
.build();
MethodSpec getter = MethodSpec.methodBuilder("get")
.addModifiers(PUBLIC, STATIC)
.returns(CLDR)
.addStatement("return instance")
.build();
TypeSpec.Builder type = TypeSpec.classBuilder("CLDR")
.addModifiers(PUBLIC)
.superclass(CLDR_BASE)
.addMethod(constructor)
.addMethod(getter)
.addMethod(registerCalendars)
.addMethod(registerNumbers);
Set<LocaleID> availableLocales = reader.availableLocales()
.stream()
.map(s -> LocaleID.parse(s))
.collect(Collectors.toSet());
createLocales(type, reader.defaultContent(), availableLocales);
createLanguageAliases(type, reader.languageAliases());
createTerritoryAliases(type, reader.territoryAliases());
createLikelySubtags(type, reader.likelySubtags());
createCurrencies(type, numberGenerator.getCurrencies(reader));
addPluralRules(type);
// Initialize all static maps.
type.addStaticBlock(CodeBlock.builder()
.addStatement("registerCalendars()")
.addStatement("registerNumbers()")
.addStatement("registerDefaultContent()")
.addStatement("registerLanguageAliases()")
.addStatement("registerTerritoryAliases()")
.addStatement("registerLikelySubtags()")
.addStatement("instance = new CLDR()").build());
type.addField(instance);
saveClass(outputDir, PACKAGE_CLDR, "CLDR", type.build());
} | [
"public",
"static",
"void",
"generate",
"(",
"Path",
"outputDir",
")",
"throws",
"IOException",
"{",
"DataReader",
"reader",
"=",
"DataReader",
".",
"get",
"(",
")",
";",
"CalendarCodeGenerator",
"datetimeGenerator",
"=",
"new",
"CalendarCodeGenerator",
"(",
")",
... | Loads all CLDR data and invokes the code generators for each data type. Output
is a series of Java classes under the outputDir. | [
"Loads",
"all",
"CLDR",
"data",
"and",
"invokes",
"the",
"code",
"generators",
"for",
"each",
"data",
"type",
".",
"Output",
"is",
"a",
"series",
"of",
"Java",
"classes",
"under",
"the",
"outputDir",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L59-L123 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.saveClass | public static void saveClass(Path rootDir, String packageName, String className, TypeSpec type)
throws IOException {
List<String> packagePath = Splitter.on('.').splitToList(packageName);
Path classPath = Paths.get(rootDir.toString(), packagePath.toArray(EMPTY));
Path outputFile = classPath.resolve(className + ".java");
JavaFile javaFile = JavaFile.builder(packageName, type)
.addFileComment("\n\nAUTO-GENERATED CLASS - DO NOT EDIT\n\n")
// TODO: build timestamp and version info
.build();
System.out.println("saving " + outputFile);
Files.createParentDirs(outputFile.toFile());
CharSink sink = Files.asCharSink(outputFile.toFile(), Charsets.UTF_8);
sink.write(javaFile.toString());
} | java | public static void saveClass(Path rootDir, String packageName, String className, TypeSpec type)
throws IOException {
List<String> packagePath = Splitter.on('.').splitToList(packageName);
Path classPath = Paths.get(rootDir.toString(), packagePath.toArray(EMPTY));
Path outputFile = classPath.resolve(className + ".java");
JavaFile javaFile = JavaFile.builder(packageName, type)
.addFileComment("\n\nAUTO-GENERATED CLASS - DO NOT EDIT\n\n")
// TODO: build timestamp and version info
.build();
System.out.println("saving " + outputFile);
Files.createParentDirs(outputFile.toFile());
CharSink sink = Files.asCharSink(outputFile.toFile(), Charsets.UTF_8);
sink.write(javaFile.toString());
} | [
"public",
"static",
"void",
"saveClass",
"(",
"Path",
"rootDir",
",",
"String",
"packageName",
",",
"String",
"className",
",",
"TypeSpec",
"type",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"packagePath",
"=",
"Splitter",
".",
"on",
"(",... | Saves a Java class file to a path for the given package, rooted in rootDir. | [
"Saves",
"a",
"Java",
"class",
"file",
"to",
"a",
"path",
"for",
"the",
"given",
"package",
"rooted",
"in",
"rootDir",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L128-L144 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.addPluralRules | private static void addPluralRules(TypeSpec.Builder type) {
FieldSpec field = FieldSpec.builder(PLURAL_RULES, "pluralRules", PRIVATE, STATIC, FINAL)
.initializer("new $T()", PLURAL_RULES)
.build();
MethodSpec method = MethodSpec.methodBuilder("getPluralRules")
.addModifiers(PUBLIC)
.returns(PLURAL_RULES)
.addStatement("return pluralRules")
.build();
type.addField(field);
type.addMethod(method);
} | java | private static void addPluralRules(TypeSpec.Builder type) {
FieldSpec field = FieldSpec.builder(PLURAL_RULES, "pluralRules", PRIVATE, STATIC, FINAL)
.initializer("new $T()", PLURAL_RULES)
.build();
MethodSpec method = MethodSpec.methodBuilder("getPluralRules")
.addModifiers(PUBLIC)
.returns(PLURAL_RULES)
.addStatement("return pluralRules")
.build();
type.addField(field);
type.addMethod(method);
} | [
"private",
"static",
"void",
"addPluralRules",
"(",
"TypeSpec",
".",
"Builder",
"type",
")",
"{",
"FieldSpec",
"field",
"=",
"FieldSpec",
".",
"builder",
"(",
"PLURAL_RULES",
",",
"\"pluralRules\"",
",",
"PRIVATE",
",",
"STATIC",
",",
"FINAL",
")",
".",
"ini... | Add static instance of plural rules and accessor method. | [
"Add",
"static",
"instance",
"of",
"plural",
"rules",
"and",
"accessor",
"method",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L149-L162 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.indexFormatters | private static MethodSpec indexFormatters(
String methodName, String registerMethodName, Map<LocaleID, ClassName> dateClasses) {
MethodSpec.Builder method = MethodSpec.methodBuilder(methodName)
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<LocaleID, ClassName> entry : dateClasses.entrySet()) {
LocaleID localeId = entry.getKey();
ClassName className = entry.getValue();
method.addStatement("$T.$L(Locale.$L, $L.class)", CLDR_BASE,
registerMethodName, localeId.safe, className);
}
return method.build();
} | java | private static MethodSpec indexFormatters(
String methodName, String registerMethodName, Map<LocaleID, ClassName> dateClasses) {
MethodSpec.Builder method = MethodSpec.methodBuilder(methodName)
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<LocaleID, ClassName> entry : dateClasses.entrySet()) {
LocaleID localeId = entry.getKey();
ClassName className = entry.getValue();
method.addStatement("$T.$L(Locale.$L, $L.class)", CLDR_BASE,
registerMethodName, localeId.safe, className);
}
return method.build();
} | [
"private",
"static",
"MethodSpec",
"indexFormatters",
"(",
"String",
"methodName",
",",
"String",
"registerMethodName",
",",
"Map",
"<",
"LocaleID",
",",
"ClassName",
">",
"dateClasses",
")",
"{",
"MethodSpec",
".",
"Builder",
"method",
"=",
"MethodSpec",
".",
"... | Generates a static code block that populates the formatter map. | [
"Generates",
"a",
"static",
"code",
"block",
"that",
"populates",
"the",
"formatter",
"map",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L167-L180 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.addLocaleField | private static void addLocaleField(TypeSpec.Builder type, String name, LocaleID locale) {
FieldSpec.Builder field = FieldSpec.builder(CLDR_LOCALE_IF, name, PUBLIC, STATIC, FINAL)
.initializer("new $T($S, $S, $S, $S)",
META_LOCALE,
strOrNull(locale.language),
strOrNull(locale.script),
strOrNull(locale.territory),
strOrNull(locale.variant));
type.addField(field.build());
} | java | private static void addLocaleField(TypeSpec.Builder type, String name, LocaleID locale) {
FieldSpec.Builder field = FieldSpec.builder(CLDR_LOCALE_IF, name, PUBLIC, STATIC, FINAL)
.initializer("new $T($S, $S, $S, $S)",
META_LOCALE,
strOrNull(locale.language),
strOrNull(locale.script),
strOrNull(locale.territory),
strOrNull(locale.variant));
type.addField(field.build());
} | [
"private",
"static",
"void",
"addLocaleField",
"(",
"TypeSpec",
".",
"Builder",
"type",
",",
"String",
"name",
",",
"LocaleID",
"locale",
")",
"{",
"FieldSpec",
".",
"Builder",
"field",
"=",
"FieldSpec",
".",
"builder",
"(",
"CLDR_LOCALE_IF",
",",
"name",
",... | Create a public locale field. | [
"Create",
"a",
"public",
"locale",
"field",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L297-L306 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.createLanguageAliases | private static void createLanguageAliases(TypeSpec.Builder type, Map<String, String> languageAliases) {
MethodSpec.Builder method = MethodSpec.methodBuilder("registerLanguageAliases")
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<String, String> entry : languageAliases.entrySet()) {
method.addStatement("addLanguageAlias($S, $S)",
entry.getKey(), entry.getValue());
}
type.addMethod(method.build());
} | java | private static void createLanguageAliases(TypeSpec.Builder type, Map<String, String> languageAliases) {
MethodSpec.Builder method = MethodSpec.methodBuilder("registerLanguageAliases")
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<String, String> entry : languageAliases.entrySet()) {
method.addStatement("addLanguageAlias($S, $S)",
entry.getKey(), entry.getValue());
}
type.addMethod(method.build());
} | [
"private",
"static",
"void",
"createLanguageAliases",
"(",
"TypeSpec",
".",
"Builder",
"type",
",",
"Map",
"<",
"String",
",",
"String",
">",
"languageAliases",
")",
"{",
"MethodSpec",
".",
"Builder",
"method",
"=",
"MethodSpec",
".",
"methodBuilder",
"(",
"\"... | Create language alias mapping. | [
"Create",
"language",
"alias",
"mapping",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L311-L321 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.createLikelySubtags | private static void createLikelySubtags(TypeSpec.Builder type, Map<String, String> likelySubtags) {
MethodSpec.Builder method = MethodSpec.methodBuilder("registerLikelySubtags")
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<String, String> entry : likelySubtags.entrySet()) {
method.addStatement("LIKELY_SUBTAGS_MAP.put($T.parse($S), $T.parse($S))",
META_LOCALE, entry.getKey(), META_LOCALE, entry.getValue());
}
type.addMethod(method.build());
} | java | private static void createLikelySubtags(TypeSpec.Builder type, Map<String, String> likelySubtags) {
MethodSpec.Builder method = MethodSpec.methodBuilder("registerLikelySubtags")
.addModifiers(PRIVATE, STATIC);
for (Map.Entry<String, String> entry : likelySubtags.entrySet()) {
method.addStatement("LIKELY_SUBTAGS_MAP.put($T.parse($S), $T.parse($S))",
META_LOCALE, entry.getKey(), META_LOCALE, entry.getValue());
}
type.addMethod(method.build());
} | [
"private",
"static",
"void",
"createLikelySubtags",
"(",
"TypeSpec",
".",
"Builder",
"type",
",",
"Map",
"<",
"String",
",",
"String",
">",
"likelySubtags",
")",
"{",
"MethodSpec",
".",
"Builder",
"method",
"=",
"MethodSpec",
".",
"methodBuilder",
"(",
"\"regi... | Create likely subtags mapping. | [
"Create",
"likely",
"subtags",
"mapping",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L338-L348 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java | CodeGenerator.createCurrencies | private static void createCurrencies(TypeSpec.Builder type, List<String> currencies) {
TypeSpec.Builder currencyType = TypeSpec.enumBuilder("Currency")
.addModifiers(PUBLIC, STATIC);
List<String> codes = new ArrayList<>();
codes.addAll(currencies);
Collections.sort(codes);
StringBuilder buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < codes.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
currencyType.addEnumConstant(codes.get(i));
buf.append(" Currency.$L");
}
buf.append("))");
// Add a safe string mapping that returns null instead of throwing.
MethodSpec.Builder method = MethodSpec.methodBuilder("fromString")
.addModifiers(PUBLIC, STATIC)
.addParameter(STRING, "code")
.returns(Types.CLDR_CURRENCY_ENUM);
method.beginControlFlow("if (code != null)");
method.beginControlFlow("switch (code)");
for (int i = 0; i < codes.size(); i++) {
method.addStatement("case $S: return $L", codes.get(i), codes.get(i));
}
method.addStatement("default: break");
method.endControlFlow();
method.endControlFlow();
method.addStatement("return null");
currencyType.addMethod(method.build());
type.addType(currencyType.build());
// Initialize field containing all currencies
List<Object> arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(codes);
} | java | private static void createCurrencies(TypeSpec.Builder type, List<String> currencies) {
TypeSpec.Builder currencyType = TypeSpec.enumBuilder("Currency")
.addModifiers(PUBLIC, STATIC);
List<String> codes = new ArrayList<>();
codes.addAll(currencies);
Collections.sort(codes);
StringBuilder buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < codes.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
currencyType.addEnumConstant(codes.get(i));
buf.append(" Currency.$L");
}
buf.append("))");
// Add a safe string mapping that returns null instead of throwing.
MethodSpec.Builder method = MethodSpec.methodBuilder("fromString")
.addModifiers(PUBLIC, STATIC)
.addParameter(STRING, "code")
.returns(Types.CLDR_CURRENCY_ENUM);
method.beginControlFlow("if (code != null)");
method.beginControlFlow("switch (code)");
for (int i = 0; i < codes.size(); i++) {
method.addStatement("case $S: return $L", codes.get(i), codes.get(i));
}
method.addStatement("default: break");
method.endControlFlow();
method.endControlFlow();
method.addStatement("return null");
currencyType.addMethod(method.build());
type.addType(currencyType.build());
// Initialize field containing all currencies
List<Object> arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(codes);
} | [
"private",
"static",
"void",
"createCurrencies",
"(",
"TypeSpec",
".",
"Builder",
"type",
",",
"List",
"<",
"String",
">",
"currencies",
")",
"{",
"TypeSpec",
".",
"Builder",
"currencyType",
"=",
"TypeSpec",
".",
"enumBuilder",
"(",
"\"Currency\"",
")",
".",
... | Create top-level container to hold currency constants. | [
"Create",
"top",
"-",
"level",
"container",
"to",
"hold",
"currency",
"constants",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CodeGenerator.java#L357-L400 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java | MessageArgsUnitParser.selectExactUnit | protected static Unit selectExactUnit(String compact, UnitConverter converter) {
if (compact != null) {
switch (compact) {
case "consumption":
return converter.consumptionUnit();
case "light":
return Unit.LUX;
case "speed":
return converter.speedUnit();
case "temp":
case "temperature":
return converter.temperatureUnit();
default:
break;
}
}
return null;
} | java | protected static Unit selectExactUnit(String compact, UnitConverter converter) {
if (compact != null) {
switch (compact) {
case "consumption":
return converter.consumptionUnit();
case "light":
return Unit.LUX;
case "speed":
return converter.speedUnit();
case "temp":
case "temperature":
return converter.temperatureUnit();
default:
break;
}
}
return null;
} | [
"protected",
"static",
"Unit",
"selectExactUnit",
"(",
"String",
"compact",
",",
"UnitConverter",
"converter",
")",
"{",
"if",
"(",
"compact",
"!=",
"null",
")",
"{",
"switch",
"(",
"compact",
")",
"{",
"case",
"\"consumption\"",
":",
"return",
"converter",
... | Some categories only have a single possible unit depending the locale. | [
"Some",
"categories",
"only",
"have",
"a",
"single",
"possible",
"unit",
"depending",
"the",
"locale",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java#L93-L110 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java | MessageArgsUnitParser.inputFromExactUnit | protected static Unit inputFromExactUnit(Unit exact, UnitConverter converter) {
switch (exact) {
case TERABIT:
case GIGABIT:
case MEGABIT:
case KILOBIT:
case BIT:
return Unit.BIT;
case TERABYTE:
case GIGABYTE:
case MEGABYTE:
case KILOBYTE:
case BYTE:
return Unit.BYTE;
default:
break;
}
UnitCategory category = exact.category();
switch (category) {
case CONSUMPTION:
return converter.consumptionUnit();
case ELECTRIC:
return Unit.AMPERE;
case FREQUENCY:
return Unit.HERTZ;
case LIGHT:
return Unit.LUX;
case PRESSURE:
return Unit.MILLIBAR;
case SPEED:
return converter.speedUnit();
case TEMPERATURE:
return converter.temperatureUnit();
default:
UnitFactorSet factorSet = getDefaultFactorSet(category, converter);
if (factorSet != null) {
return factorSet.base();
}
break;
}
return null;
} | java | protected static Unit inputFromExactUnit(Unit exact, UnitConverter converter) {
switch (exact) {
case TERABIT:
case GIGABIT:
case MEGABIT:
case KILOBIT:
case BIT:
return Unit.BIT;
case TERABYTE:
case GIGABYTE:
case MEGABYTE:
case KILOBYTE:
case BYTE:
return Unit.BYTE;
default:
break;
}
UnitCategory category = exact.category();
switch (category) {
case CONSUMPTION:
return converter.consumptionUnit();
case ELECTRIC:
return Unit.AMPERE;
case FREQUENCY:
return Unit.HERTZ;
case LIGHT:
return Unit.LUX;
case PRESSURE:
return Unit.MILLIBAR;
case SPEED:
return converter.speedUnit();
case TEMPERATURE:
return converter.temperatureUnit();
default:
UnitFactorSet factorSet = getDefaultFactorSet(category, converter);
if (factorSet != null) {
return factorSet.base();
}
break;
}
return null;
} | [
"protected",
"static",
"Unit",
"inputFromExactUnit",
"(",
"Unit",
"exact",
",",
"UnitConverter",
"converter",
")",
"{",
"switch",
"(",
"exact",
")",
"{",
"case",
"TERABIT",
":",
"case",
"GIGABIT",
":",
"case",
"MEGABIT",
":",
"case",
"KILOBIT",
":",
"case",
... | Based on the unit we're converting to, guess the input unit. For example, if we're
converting to MEGABIT and no input unit was specified, assume BIT. | [
"Based",
"on",
"the",
"unit",
"we",
"re",
"converting",
"to",
"guess",
"the",
"input",
"unit",
".",
"For",
"example",
"if",
"we",
"re",
"converting",
"to",
"MEGABIT",
"and",
"no",
"input",
"unit",
"was",
"specified",
"assume",
"BIT",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java#L164-L209 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java | MessageArgsUnitParser.getDefaultFactorSet | protected static UnitFactorSet getDefaultFactorSet(UnitCategory category, UnitConverter converter) {
switch (category) {
case ANGLE:
return UnitFactorSets.ANGLE;
case AREA:
return converter.areaFactors();
case DURATION:
return UnitFactorSets.DURATION;
case ELECTRIC:
return UnitFactorSets.ELECTRIC;
case ENERGY:
return converter.energyFactors();
case FREQUENCY:
return UnitFactorSets.FREQUENCY;
case LENGTH:
return converter.lengthFactors();
case MASS:
return converter.massFactors();
case POWER:
return UnitFactorSets.POWER;
case VOLUME:
return converter.volumeFactors();
default:
break;
}
return null;
} | java | protected static UnitFactorSet getDefaultFactorSet(UnitCategory category, UnitConverter converter) {
switch (category) {
case ANGLE:
return UnitFactorSets.ANGLE;
case AREA:
return converter.areaFactors();
case DURATION:
return UnitFactorSets.DURATION;
case ELECTRIC:
return UnitFactorSets.ELECTRIC;
case ENERGY:
return converter.energyFactors();
case FREQUENCY:
return UnitFactorSets.FREQUENCY;
case LENGTH:
return converter.lengthFactors();
case MASS:
return converter.massFactors();
case POWER:
return UnitFactorSets.POWER;
case VOLUME:
return converter.volumeFactors();
default:
break;
}
return null;
} | [
"protected",
"static",
"UnitFactorSet",
"getDefaultFactorSet",
"(",
"UnitCategory",
"category",
",",
"UnitConverter",
"converter",
")",
"{",
"switch",
"(",
"category",
")",
"{",
"case",
"ANGLE",
":",
"return",
"UnitFactorSets",
".",
"ANGLE",
";",
"case",
"AREA",
... | Default conversion factors for each category. Some of these differ based on the locale
of the converter. | [
"Default",
"conversion",
"factors",
"for",
"each",
"category",
".",
"Some",
"of",
"these",
"differ",
"based",
"on",
"the",
"locale",
"of",
"the",
"converter",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java#L215-L241 | train |
Squarespace/cldr | core/src/main/java/com/squarespace/cldr/numbers/NumberPattern.java | NumberPattern.render | public String render() {
StringBuilder buf = new StringBuilder();
for (Node node : parsed) {
if (node instanceof Symbol) {
switch ((Symbol)node) {
case MINUS:
buf.append('-');
break;
case CURRENCY:
buf.append(CURRENCY_SYM);
break;
case PERCENT:
buf.append('%');
break;
}
} else if (node instanceof Text) {
String text = ((Text)node).text;
int len = text.length();
for (int i = 0; i < len; i++) {
char ch = text.charAt(i);
switch (ch) {
case '.':
case '#':
case ',':
case '-':
buf.append('\'').append(ch).append('\'');
break;
default:
buf.append(ch);
break;
}
}
} else if (node instanceof Format) {
Format format = (Format) node;
format.render(buf);
}
}
return buf.toString();
} | java | public String render() {
StringBuilder buf = new StringBuilder();
for (Node node : parsed) {
if (node instanceof Symbol) {
switch ((Symbol)node) {
case MINUS:
buf.append('-');
break;
case CURRENCY:
buf.append(CURRENCY_SYM);
break;
case PERCENT:
buf.append('%');
break;
}
} else if (node instanceof Text) {
String text = ((Text)node).text;
int len = text.length();
for (int i = 0; i < len; i++) {
char ch = text.charAt(i);
switch (ch) {
case '.':
case '#':
case ',':
case '-':
buf.append('\'').append(ch).append('\'');
break;
default:
buf.append(ch);
break;
}
}
} else if (node instanceof Format) {
Format format = (Format) node;
format.render(buf);
}
}
return buf.toString();
} | [
"public",
"String",
"render",
"(",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Node",
"node",
":",
"parsed",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Symbol",
")",
"{",
"switch",
"(",
"(",
"Symbol",
"... | Render a parseable representation of this pattern. | [
"Render",
"a",
"parseable",
"representation",
"of",
"this",
"pattern",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/numbers/NumberPattern.java#L38-L81 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java | BundleMatcher.dump | public String dump() {
StringBuilder buf = new StringBuilder();
buf.append(" LOCALE MATCHED BUNDLE\n");
buf.append(" ====== ==============\n");
List<MetaLocale> keys = availableBundlesMap.keySet().stream()
.map(k -> (MetaLocale)k).collect(Collectors.toList());
Collections.sort(keys);
for (CLDR.Locale key : keys) {
buf.append(String.format("%20s -> %s\n", key, availableBundlesMap.get(key)));
}
return buf.toString();
} | java | public String dump() {
StringBuilder buf = new StringBuilder();
buf.append(" LOCALE MATCHED BUNDLE\n");
buf.append(" ====== ==============\n");
List<MetaLocale> keys = availableBundlesMap.keySet().stream()
.map(k -> (MetaLocale)k).collect(Collectors.toList());
Collections.sort(keys);
for (CLDR.Locale key : keys) {
buf.append(String.format("%20s -> %s\n", key, availableBundlesMap.get(key)));
}
return buf.toString();
} | [
"public",
"String",
"dump",
"(",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buf",
".",
"append",
"(",
"\" LOCALE MATCHED BUNDLE\\n\"",
")",
";",
"buf",
".",
"append",
"(",
"\" ====== ===========... | Inspect the mapping between permutations of locale fields and bundle identifiers. | [
"Inspect",
"the",
"mapping",
"between",
"permutations",
"of",
"locale",
"fields",
"and",
"bundle",
"identifiers",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java#L80-L91 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java | BundleMatcher.buildMap | private void buildMap(List<CLDR.Locale> availableBundles) {
// Index all bundles by their original bundle identifier and the maximum
// bundle identifier.
List<MetaLocale> maxBundleIds = new ArrayList<>();
for (CLDR.Locale locale : availableBundles) {
MetaLocale source = (MetaLocale) locale;
if (source.isRoot()) {
continue;
}
MetaLocale maxBundleId = languageResolver.addLikelySubtags(source);
maxBundleIds.add(maxBundleId);
availableBundlesMap.put(source.copy(), source);
if (!source.equals(maxBundleId)) {
availableBundlesMap.putIfAbsent(maxBundleId.copy(), source);
}
}
// Iterate over the maximum bundle identifiers, indexing the permutations
// generated by our matching order.
for (MetaLocale bundleId : maxBundleIds) {
indexPermutations(bundleId);
}
} | java | private void buildMap(List<CLDR.Locale> availableBundles) {
// Index all bundles by their original bundle identifier and the maximum
// bundle identifier.
List<MetaLocale> maxBundleIds = new ArrayList<>();
for (CLDR.Locale locale : availableBundles) {
MetaLocale source = (MetaLocale) locale;
if (source.isRoot()) {
continue;
}
MetaLocale maxBundleId = languageResolver.addLikelySubtags(source);
maxBundleIds.add(maxBundleId);
availableBundlesMap.put(source.copy(), source);
if (!source.equals(maxBundleId)) {
availableBundlesMap.putIfAbsent(maxBundleId.copy(), source);
}
}
// Iterate over the maximum bundle identifiers, indexing the permutations
// generated by our matching order.
for (MetaLocale bundleId : maxBundleIds) {
indexPermutations(bundleId);
}
} | [
"private",
"void",
"buildMap",
"(",
"List",
"<",
"CLDR",
".",
"Locale",
">",
"availableBundles",
")",
"{",
"// Index all bundles by their original bundle identifier and the maximum",
"// bundle identifier.",
"List",
"<",
"MetaLocale",
">",
"maxBundleIds",
"=",
"new",
"Arr... | Iterate over the available bundle identifiers, expand them and index all
permutations to enable a fast direct lookup. | [
"Iterate",
"over",
"the",
"available",
"bundle",
"identifiers",
"expand",
"them",
"and",
"index",
"all",
"permutations",
"to",
"enable",
"a",
"fast",
"direct",
"lookup",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java#L97-L120 | train |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java | BundleMatcher.indexPermutations | private void indexPermutations(MetaLocale bundleId) {
MetaLocale key = bundleId.copy();
for (int flags : LanguageResolver.MATCH_ORDER) {
LanguageResolver.set(bundleId, key, flags);
MetaLocale maxBundleId = languageResolver.addLikelySubtags(key);
MetaLocale source = availableBundlesMap.get(maxBundleId);
if (source != null) {
availableBundlesMap.putIfAbsent(key.copy(), source);
} else if (maxBundleId.hasVariant()) {
maxBundleId.setVariant(null);
source = availableBundlesMap.get(maxBundleId);
if (source != null) {
availableBundlesMap.putIfAbsent(key.copy(), source);
}
}
}
} | java | private void indexPermutations(MetaLocale bundleId) {
MetaLocale key = bundleId.copy();
for (int flags : LanguageResolver.MATCH_ORDER) {
LanguageResolver.set(bundleId, key, flags);
MetaLocale maxBundleId = languageResolver.addLikelySubtags(key);
MetaLocale source = availableBundlesMap.get(maxBundleId);
if (source != null) {
availableBundlesMap.putIfAbsent(key.copy(), source);
} else if (maxBundleId.hasVariant()) {
maxBundleId.setVariant(null);
source = availableBundlesMap.get(maxBundleId);
if (source != null) {
availableBundlesMap.putIfAbsent(key.copy(), source);
}
}
}
} | [
"private",
"void",
"indexPermutations",
"(",
"MetaLocale",
"bundleId",
")",
"{",
"MetaLocale",
"key",
"=",
"bundleId",
".",
"copy",
"(",
")",
";",
"for",
"(",
"int",
"flags",
":",
"LanguageResolver",
".",
"MATCH_ORDER",
")",
"{",
"LanguageResolver",
".",
"se... | Index permutations of the given bundle identifier. We iterate over the field
permutations and expand each to the maximum bundle identifier, then query
to see if that max bundle identifier matches a bundle. Then we index the
permutation to that bundle. This creates a static mapping mimicking a dynamic lookup. | [
"Index",
"permutations",
"of",
"the",
"given",
"bundle",
"identifier",
".",
"We",
"iterate",
"over",
"the",
"field",
"permutations",
"and",
"expand",
"each",
"to",
"the",
"maximum",
"bundle",
"identifier",
"then",
"query",
"to",
"see",
"if",
"that",
"max",
"... | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/BundleMatcher.java#L128-L144 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java | CalendarCodeGenerator.generate | public Map<LocaleID, ClassName> generate(Path outputDir, DataReader reader)
throws IOException {
Map<LocaleID, ClassName> dateClasses = new TreeMap<>();
List<DateTimeData> dateTimeDataList = new ArrayList<>();
for (Map.Entry<LocaleID, DateTimeData> entry : reader.calendars().entrySet()) {
DateTimeData dateTimeData = entry.getValue();
LocaleID localeId = entry.getKey();
String className = "_CalendarFormatter_" + localeId.safe;
TimeZoneData timeZoneData = reader.timezones().get(localeId);
TypeSpec type = createFormatter(dateTimeData, timeZoneData, className);
CodeGenerator.saveClass(outputDir, Types.PACKAGE_CLDR_DATES, className, type);
ClassName cls = ClassName.get(Types.PACKAGE_CLDR_DATES, className);
dateClasses.put(localeId, cls);
dateTimeDataList.add(dateTimeData);
}
String className = "_CalendarUtils";
TypeSpec.Builder utilsType = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC);
addSkeletonClassifierMethod(utilsType, dateTimeDataList);
addMetaZones(utilsType, reader.metazones());
buildTimeZoneAliases(utilsType, reader.timezoneAliases());
CodeGenerator.saveClass(outputDir, Types.PACKAGE_CLDR_DATES, "_CalendarUtils", utilsType.build());
return dateClasses;
} | java | public Map<LocaleID, ClassName> generate(Path outputDir, DataReader reader)
throws IOException {
Map<LocaleID, ClassName> dateClasses = new TreeMap<>();
List<DateTimeData> dateTimeDataList = new ArrayList<>();
for (Map.Entry<LocaleID, DateTimeData> entry : reader.calendars().entrySet()) {
DateTimeData dateTimeData = entry.getValue();
LocaleID localeId = entry.getKey();
String className = "_CalendarFormatter_" + localeId.safe;
TimeZoneData timeZoneData = reader.timezones().get(localeId);
TypeSpec type = createFormatter(dateTimeData, timeZoneData, className);
CodeGenerator.saveClass(outputDir, Types.PACKAGE_CLDR_DATES, className, type);
ClassName cls = ClassName.get(Types.PACKAGE_CLDR_DATES, className);
dateClasses.put(localeId, cls);
dateTimeDataList.add(dateTimeData);
}
String className = "_CalendarUtils";
TypeSpec.Builder utilsType = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC);
addSkeletonClassifierMethod(utilsType, dateTimeDataList);
addMetaZones(utilsType, reader.metazones());
buildTimeZoneAliases(utilsType, reader.timezoneAliases());
CodeGenerator.saveClass(outputDir, Types.PACKAGE_CLDR_DATES, "_CalendarUtils", utilsType.build());
return dateClasses;
} | [
"public",
"Map",
"<",
"LocaleID",
",",
"ClassName",
">",
"generate",
"(",
"Path",
"outputDir",
",",
"DataReader",
"reader",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"LocaleID",
",",
"ClassName",
">",
"dateClasses",
"=",
"new",
"TreeMap",
"<>",
"(",
"... | Generates the date-time classes into the given output directory. | [
"Generates",
"the",
"date",
"-",
"time",
"classes",
"into",
"the",
"given",
"output",
"directory",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L75-L108 | train |
Squarespace/cldr | compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java | CalendarCodeGenerator.addSkeletonClassifierMethod | private void addSkeletonClassifierMethod(TypeSpec.Builder type, List<DateTimeData> dataList) {
Set<String> dates = new LinkedHashSet<>();
Set<String> times = new LinkedHashSet<>();
for (DateTimeData data : dataList) {
for (Skeleton skeleton : data.dateTimeSkeletons) {
if (isDateSkeleton(skeleton.skeleton)) {
dates.add(skeleton.skeleton);
} else {
times.add(skeleton.skeleton);
}
}
}
MethodSpec.Builder method = buildSkeletonType(dates, times);
type.addMethod(method.build());
} | java | private void addSkeletonClassifierMethod(TypeSpec.Builder type, List<DateTimeData> dataList) {
Set<String> dates = new LinkedHashSet<>();
Set<String> times = new LinkedHashSet<>();
for (DateTimeData data : dataList) {
for (Skeleton skeleton : data.dateTimeSkeletons) {
if (isDateSkeleton(skeleton.skeleton)) {
dates.add(skeleton.skeleton);
} else {
times.add(skeleton.skeleton);
}
}
}
MethodSpec.Builder method = buildSkeletonType(dates, times);
type.addMethod(method.build());
} | [
"private",
"void",
"addSkeletonClassifierMethod",
"(",
"TypeSpec",
".",
"Builder",
"type",
",",
"List",
"<",
"DateTimeData",
">",
"dataList",
")",
"{",
"Set",
"<",
"String",
">",
"dates",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"Set",
"<",
"Strin... | Create a helper class to classify skeletons as either DATE or TIME. | [
"Create",
"a",
"helper",
"class",
"to",
"classify",
"skeletons",
"as",
"either",
"DATE",
"or",
"TIME",
"."
] | 54b752d4ec2457df56e98461618f9c0eec41e1e1 | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L113-L128 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.