_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16500 | SqlExporter.buildCreateTableQuery | train | private String buildCreateTableQuery(final IClassContainer container,
final String primaryKeyField) {
final StringBuilder builder = new StringBuilder("CREATE TABLE IF NOT EXISTS ")
.append(container.getExportClassName().toLowerCase())
.append("(\n");
final String resultValues = container.getFormatSupported(Format.SQL).entrySet().stream()
.map(e -> "\t" + buildInsertNameTypeQuery(e.getValue().getExportName(), container))
.collect(Collectors.joining(",\n"));
builder.append(resultValues);
// Write primary key constraint
return builder.append(",\n")
.append("\tPRIMARY KEY (")
.append(primaryKeyField)
.append(")\n);\n")
.toString();
} | java | {
"resource": ""
} |
q16501 | SqlExporter.buildInsertNameTypeQuery | train | private String buildInsertNameTypeQuery(final String finalFieldName,
final IClassContainer container) {
final Class<?> exportFieldType = container.getField(finalFieldName).getType();
switch (container.getContainer(finalFieldName).getType()) {
case ARRAY:
case COLLECTION:
final Class<?> type = exportFieldType.getComponentType();
return finalFieldName + "\t" + translateJavaTypeToSqlType(type) + "[]";
case ARRAY_2D:
final Class<?> type2D = exportFieldType.getComponentType().getComponentType();
return finalFieldName + "\t" + translateJavaTypeToSqlType(type2D) + "[][]";
default:
return finalFieldName + "\t" + translateJavaTypeToSqlType(exportFieldType);
}
} | java | {
"resource": ""
} |
q16502 | SqlExporter.buildInsertQuery | train | private <T> String buildInsertQuery(final T t,
final IClassContainer container) {
final List<ExportContainer> exportContainers = extractExportContainers(t, container);
final StringBuilder builder = new StringBuilder("INSERT INTO ")
.append(container.getExportClassName().toLowerCase())
.append(" (");
final String names = exportContainers.stream()
.map(ExportContainer::getExportName)
.collect(Collectors.joining(", "));
return builder.append(names)
.append(") ")
.append("VALUES\n")
.toString();
} | java | {
"resource": ""
} |
q16503 | SqlExporter.format | train | private <T> String format(final T t,
final IClassContainer container) {
final List<ExportContainer> exportContainers = extractExportContainers(t, container);
final String resultValues = exportContainers.stream()
.map(c -> convertFieldValue(container.getField(c.getExportName()), c))
.collect(Collectors.joining(", "));
return "(" + resultValues + ")";
} | java | {
"resource": ""
} |
q16504 | SqlExporter.isTypeTimestampConvertible | train | private boolean isTypeTimestampConvertible(final Field field) {
return dataTypes.entrySet().stream()
.anyMatch(e -> e.getValue().equals("TIMESTAMP") && e.getKey().equals(field.getType()));
} | java | {
"resource": ""
} |
q16505 | SqlExporter.convertFieldValue | train | private String convertFieldValue(final Field field,
final ExportContainer container) {
final boolean isArray2D = (container.getType() == FieldContainer.Type.ARRAY_2D);
if (field.getType().equals(String.class)) {
return wrapWithComma(container.getExportValue());
} else if (isTypeTimestampConvertible(field)) {
return wrapWithComma(String.valueOf(convertFieldValueToTimestamp(field, container)));
} else if (container.getType() == FieldContainer.Type.ARRAY
|| isArray2D
|| container.getType() == FieldContainer.Type.COLLECTION) {
final Class<?> componentType = extractType(container.getType(), field);
final String sqlType = dataTypes.getOrDefault(componentType, "VARCHAR");
final String result = (sqlType.equals("VARCHAR") || sqlType.equals("CHAR"))
? container.getExportValue().replace("[", "{\"").replace("]", "\"}").replace(",", "\",\"").replace(" ", "")
: container.getExportValue().replace("[", "{").replace("]", "}");
return wrapWithComma(result);
}
return container.getExportValue();
} | java | {
"resource": ""
} |
q16506 | SqlExporter.convertFieldValueToTimestamp | train | private Timestamp convertFieldValueToTimestamp(final Field field,
final ExportContainer exportContainer) {
if (field.getType().equals(LocalDateTime.class)) {
return convertToTimestamp(parseDateTime(exportContainer.getExportValue()));
} else if (field.getType().equals(LocalDate.class)) {
return convertToTimestamp(parseDate(exportContainer.getExportValue()));
} else if (field.getType().equals(LocalTime.class)) {
return convertToTimestamp(parseTime(exportContainer.getExportValue()));
} else if (field.getType().equals(Date.class)) {
return convertToTimestamp(parseSimpleDateLong(exportContainer.getExportValue()));
} else if (field.getType().equals(Timestamp.class)) {
return Timestamp.valueOf(exportContainer.getExportValue());
}
return null;
} | java | {
"resource": ""
} |
q16507 | VariableNumMap.getDiscreteVariables | train | public final List<DiscreteVariable> getDiscreteVariables() {
List<DiscreteVariable> discreteVars = new ArrayList<DiscreteVariable>();
for (int i = 0; i < vars.length; i++) {
if (vars[i] instanceof DiscreteVariable) {
discreteVars.add((DiscreteVariable) vars[i]);
}
}
return discreteVars;
} | java | {
"resource": ""
} |
q16508 | VariableNumMap.checkCompatibility | train | private final void checkCompatibility(VariableNumMap other) {
int i = 0, j = 0;
int[] otherNums = other.nums;
String[] otherNames = other.names;
Variable[] otherVars = other.vars;
while (i < nums.length && j < otherNums.length) {
if (nums[i] < otherNums[j]) {
i++;
} else if (nums[i] > otherNums[j]) {
j++;
} else {
// Equal
Preconditions.checkArgument(names[i].equals(otherNames[j]));
Preconditions.checkArgument(vars[i].getName().equals(otherVars[j].getName()));
i++; j++;
}
}
} | java | {
"resource": ""
} |
q16509 | VariableNumMap.outcomeToAssignment | train | public Assignment outcomeToAssignment(Object[] outcome) {
Preconditions.checkArgument(outcome.length == nums.length,
"outcome %s cannot be assigned to %s (wrong number of values)", outcome, this);
return Assignment.fromSortedArrays(nums, outcome);
} | java | {
"resource": ""
} |
q16510 | VariableNumMap.unionAll | train | public static VariableNumMap unionAll(Collection<VariableNumMap> varNumMaps) {
VariableNumMap curMap = EMPTY;
for (VariableNumMap varNumMap : varNumMaps) {
curMap = curMap.union(varNumMap);
}
return curMap;
} | java | {
"resource": ""
} |
q16511 | DaoUtils.getUserByEmail | train | public static Credentials getUserByEmail(DAO serverDao, String email) throws DAO.DAOException {
Query query = new QueryBuilder()
.select()
.from(Credentials.class)
.where(Credentials.EMAIL_KEY, OPERAND.EQ,email)
.build();
TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query));
if(to==null){
return null;
} else {
return to(Credentials.class, to);
}
} | java | {
"resource": ""
} |
q16512 | DaoUtils.getUserById | train | public static Credentials getUserById(DAO serverDao, String userId) throws DAO.DAOException {
Query query = new QueryBuilder()
.select()
.from(Credentials.class)
.where(Credentials.OWNER_ID_KEY,OPERAND.EQ,userId)
.build();
TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query));
if(to==null){
return null;
} else {
return to(Credentials.class,to);
}
} | java | {
"resource": ""
} |
q16513 | Password.getSalt | train | private static String getSalt(byte[] value) {
byte[] salt = new byte[Generate.SALT_BYTES];
System.arraycopy(value, 0, salt, 0, salt.length);
return ByteArray.toBase64(salt);
} | java | {
"resource": ""
} |
q16514 | Password.getHash | train | private static byte[] getHash(byte[] value) {
byte[] hash = new byte[value.length - Generate.SALT_BYTES];
System.arraycopy(value, Generate.SALT_BYTES, hash, 0, hash.length);
return hash;
} | java | {
"resource": ""
} |
q16515 | ParametricCcgParser.getNewSufficientStatistics | train | @Override
public SufficientStatistics getNewSufficientStatistics() {
List<SufficientStatistics> lexiconParameterList = Lists.newArrayList();
List<String> lexiconParameterNames = Lists.newArrayList();
for (int i = 0; i < lexiconFamilies.size(); i++) {
ParametricCcgLexicon lexiconFamily = lexiconFamilies.get(i);
lexiconParameterList.add(lexiconFamily.getNewSufficientStatistics());
lexiconParameterNames.add(Integer.toString(i));
}
SufficientStatistics lexiconParameters = new ListSufficientStatistics(
lexiconParameterNames, lexiconParameterList);
List<SufficientStatistics> lexiconScorerParameterList = Lists.newArrayList();
List<String> lexiconScorerParameterNames = Lists.newArrayList();
for (int i = 0; i < lexiconScorerFamilies.size(); i++) {
ParametricLexiconScorer lexiconScorerFamily = lexiconScorerFamilies.get(i);
lexiconScorerParameterList.add(lexiconScorerFamily.getNewSufficientStatistics());
lexiconScorerParameterNames.add(Integer.toString(i));
}
SufficientStatistics lexiconScorerParameters = new ListSufficientStatistics(
lexiconScorerParameterNames, lexiconScorerParameterList);
SufficientStatistics wordSkipParameters = ListSufficientStatistics.empty();
if (wordSkipFamily != null) {
wordSkipParameters = wordSkipFamily.getNewSufficientStatistics();
}
SufficientStatistics dependencyParameters = dependencyFamily.getNewSufficientStatistics();
SufficientStatistics wordDistanceParameters = wordDistanceFamily.getNewSufficientStatistics();
SufficientStatistics puncDistanceParameters = puncDistanceFamily.getNewSufficientStatistics();
SufficientStatistics verbDistanceParameters = verbDistanceFamily.getNewSufficientStatistics();
SufficientStatistics syntaxParameters = syntaxFamily.getNewSufficientStatistics();
SufficientStatistics unaryRuleParameters = unaryRuleFamily.getNewSufficientStatistics();
SufficientStatistics headedBinaryRuleParameters = headedBinaryRuleFamily.getNewSufficientStatistics();
SufficientStatistics rootSyntaxParameters = rootSyntaxFamily.getNewSufficientStatistics();
SufficientStatistics headedRootSyntaxParameters = headedRootSyntaxFamily.getNewSufficientStatistics();
return new ListSufficientStatistics(STATISTIC_NAME_LIST,
Arrays.asList(lexiconParameters, lexiconScorerParameters, wordSkipParameters,
dependencyParameters, wordDistanceParameters, puncDistanceParameters,
verbDistanceParameters, syntaxParameters, unaryRuleParameters,
headedBinaryRuleParameters, rootSyntaxParameters, headedRootSyntaxParameters));
} | java | {
"resource": ""
} |
q16516 | Backend.init | train | public static synchronized <BackendType extends Backend> BackendType init(Config<BackendType> config) {
// if(initialized) throw new RuntimeException("Backend already initialized!");
logger.debug("Initializing... " + config);
Guice.createInjector(config.getModule());
return injector.getInstance(config.getModuleType());
} | java | {
"resource": ""
} |
q16517 | BasicCastUtils.getGenericType | train | public static Type getGenericType(final Type type,
final int paramNumber) {
try {
final ParameterizedType parameterizedType = ((ParameterizedType) type);
return (parameterizedType.getActualTypeArguments().length < paramNumber)
? Object.class
: parameterizedType.getActualTypeArguments()[paramNumber];
} catch (Exception e) {
return Object.class;
}
} | java | {
"resource": ""
} |
q16518 | BasicCastUtils.areEquals | train | public static boolean areEquals(final Class<?> firstClass,
final Class<?> secondClass) {
final boolean isFirstShort = firstClass.isAssignableFrom(Short.class);
final boolean isSecondShort = secondClass.isAssignableFrom(Short.class);
if (isFirstShort && isSecondShort
|| isFirstShort && secondClass.equals(short.class)
|| firstClass.equals(short.class) && isSecondShort)
return true;
final boolean isFirstByte = firstClass.isAssignableFrom(Byte.class);
final boolean isSecondByte = secondClass.isAssignableFrom(Byte.class);
if (isFirstByte && isSecondByte
|| isFirstByte && secondClass.equals(byte.class)
|| firstClass.equals(byte.class) && isSecondByte)
return true;
final boolean isFirstInt = firstClass.isAssignableFrom(Integer.class);
final boolean isSecondInt = secondClass.isAssignableFrom(Integer.class);
if (isFirstInt && isSecondInt
|| isFirstInt && secondClass.equals(int.class)
|| firstClass.equals(int.class) && isSecondInt)
return true;
final boolean isFirstLong = firstClass.isAssignableFrom(Long.class);
final boolean isSecondLong = secondClass.isAssignableFrom(Long.class);
if (isFirstLong && isSecondLong
|| isFirstLong && secondClass.equals(long.class)
|| firstClass.equals(long.class) && isSecondLong)
return true;
final boolean isFirstDouble = firstClass.isAssignableFrom(Double.class);
final boolean isSecondDouble = secondClass.isAssignableFrom(Double.class);
if (isFirstDouble && isSecondDouble
|| isFirstDouble && secondClass.equals(double.class)
|| firstClass.equals(double.class) && isSecondDouble)
return true;
final boolean isFirstFloat = firstClass.isAssignableFrom(Float.class);
final boolean isSecondFloat = secondClass.isAssignableFrom(Float.class);
if (isFirstFloat && isSecondFloat
|| isFirstFloat && secondClass.equals(float.class)
|| firstClass.equals(float.class) && isSecondFloat)
return true;
final boolean isFirstChar = firstClass.isAssignableFrom(Character.class);
final boolean isSecondChar = secondClass.isAssignableFrom(Character.class);
if (isFirstChar && isSecondChar
|| isFirstChar && secondClass.equals(char.class)
|| firstClass.equals(char.class) && isSecondChar)
return true;
final boolean isFirstBool = firstClass.isAssignableFrom(Boolean.class);
final boolean isSecondBool = secondClass.isAssignableFrom(Boolean.class);
if (isFirstBool && isSecondBool
|| isFirstChar && secondClass.equals(boolean.class)
|| firstClass.equals(boolean.class) && isSecondChar)
return true;
return firstClass.equals(secondClass);
} | java | {
"resource": ""
} |
q16519 | SynchronousEntityManager.insert | train | @Override
public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys) throws DatabaseException{
ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName());
if(excludePrimaryKeys){
dao.add_IgnoreColumn( model.getPrimaryAttributes());
}
return insertRecord(dao, model, true);
} | java | {
"resource": ""
} |
q16520 | SynchronousEntityManager.insertNoChangeLog | train | @Override
public <T extends DAO> T insertNoChangeLog(DAO dao, ModelDef model) throws DatabaseException{
DAO ret = db.insert(dao, null, model, null);
Class<? extends DAO> clazz = getDaoClass(dao.getModelName());
return cast(clazz, ret);
} | java | {
"resource": ""
} |
q16521 | MappingFixture.addObjects | train | @Override
public Fixture addObjects(Object... objectsToAdd) {
if (0 < objectsToAdd.length) {
Collections.addAll(objects, objectsToAdd);
}
return this;
} | java | {
"resource": ""
} |
q16522 | HashMac.digest | train | public String digest(String message) {
try {
Mac mac = Mac.getInstance(algorithm);
SecretKeySpec macKey = new SecretKeySpec(key, algorithm);
mac.init(macKey);
byte[] digest = mac.doFinal(ByteArray.fromString(message));
return ByteArray.toHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Algorithm unavailable: " + algorithm, e);
} catch (InvalidKeyException e) {
throw new IllegalArgumentException("Unable to construct key for " + algorithm
+ ". Please check the value passed in when this class was initialised.", e);
}
} | java | {
"resource": ""
} |
q16523 | CcgParser.reweightRootEntries | train | public void reweightRootEntries(CcgChart chart) {
int spanStart = 0;
int spanEnd = chart.size() - 1;
int numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd);
// Apply unary rules.
ChartEntry[] entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd),
numChartEntries);
double[] probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd),
numChartEntries);
chart.clearChartEntriesForSpan(spanStart, spanEnd);
for (int i = 0; i < entries.length; i++) {
chart.addChartEntryForSpan(entries[i], probs[i], spanStart, spanEnd, syntaxVarType);
applyUnaryRules(chart, entries[i], probs[i], spanStart, spanEnd);
}
chart.doneAddingChartEntriesForSpan(spanStart, spanEnd);
// Apply root factor.
numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd);
entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd),
numChartEntries);
probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd),
numChartEntries);
chart.clearChartEntriesForSpan(spanStart, spanEnd);
for (int i = 0; i < entries.length; i++) {
ChartEntry entry = entries[i];
double rootProb = scoreRootEntry(entry, chart);
chart.addChartEntryForSpan(entry, probs[i] * rootProb, spanStart, spanEnd,
syntaxVarType);
}
chart.doneAddingChartEntriesForSpan(spanStart, spanEnd);
} | java | {
"resource": ""
} |
q16524 | DataManager.send | train | public <B extends BackendObject> Observable<Void> send(final Collection<B> objects){
return getWebService().save(isLoggedIn(),objects)
.subscribeOn(config.subscribeOn()).observeOn(config.observeOn());
} | java | {
"resource": ""
} |
q16525 | DataManager.get | train | public <B extends BackendObject> Observable<Collection<B>> get(final Class<B> type, final Collection<String> objects){
return Observable.create(new Observable.OnSubscribe<Collection<B>>() {
@Override
public void call(Subscriber<? super Collection<B>> observer) {
try {
observer.onNext(convertRequest(getArrayType(type), getWebService().get(isLoggedIn(),Query.safeTable(type), objects)));
observer.onCompleted();
} catch (Exception e) {
observer.onError(e);
}
}
}).subscribeOn(config.subscribeOn()).observeOn(config.observeOn());
} | java | {
"resource": ""
} |
q16526 | DataManager.count | train | public <B extends BackendObject> Observable<Integer> count(final Class<B> type){
return getWebService().count(isLoggedIn(),Query.safeTable(type))
.subscribeOn(config.subscribeOn()).observeOn(config.observeOn());
} | java | {
"resource": ""
} |
q16527 | CcgGrammarUtils.getSyntacticCategoryClosure | train | public static Set<HeadedSyntacticCategory> getSyntacticCategoryClosure(
Collection<HeadedSyntacticCategory> syntacticCategories) {
Set<String> featureValues = Sets.newHashSet();
for (HeadedSyntacticCategory cat : syntacticCategories) {
getAllFeatureValues(cat.getSyntax(), featureValues);
}
// Compute the closure of syntactic categories, assuming the only
// operations are function application and feature assignment.
Queue<HeadedSyntacticCategory> unprocessed = new LinkedList<HeadedSyntacticCategory>();
unprocessed.addAll(syntacticCategories);
Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet();
while (unprocessed.size() > 0) {
HeadedSyntacticCategory cat = unprocessed.poll();
Preconditions.checkArgument(cat.isCanonicalForm());
allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues)));
if (!cat.isAtomic()) {
HeadedSyntacticCategory ret = cat.getReturnType().getCanonicalForm();
if (!allCategories.contains(ret) && !unprocessed.contains(ret)) {
unprocessed.offer(ret);
}
HeadedSyntacticCategory arg = cat.getArgumentType().getCanonicalForm();
if (!allCategories.contains(arg) && !unprocessed.contains(arg)) {
unprocessed.offer(arg);
}
}
}
// XXX: jayantk 1/8/2016 I think this loop does exactly the same thing as
// the previous one.
/*
Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet();
for (HeadedSyntacticCategory cat : syntacticCategories) {
Preconditions.checkArgument(cat.isCanonicalForm());
allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues)));
while (!cat.getSyntax().isAtomic()) {
allCategories.addAll(canonicalizeCategories(cat.getArgumentType().getCanonicalForm().getSubcategories(featureValues)));
allCategories.addAll(canonicalizeCategories(cat.getReturnType().getCanonicalForm().getSubcategories(featureValues)));
cat = cat.getReturnType();
}
}
*/
return allCategories;
} | java | {
"resource": ""
} |
q16528 | CcgGrammarUtils.buildUnrestrictedBinaryDistribution | train | public static DiscreteFactor buildUnrestrictedBinaryDistribution(DiscreteVariable syntaxType,
Iterable<CcgBinaryRule> rules, boolean allowComposition) {
List<HeadedSyntacticCategory> allCategories = syntaxType.getValuesWithCast(HeadedSyntacticCategory.class);
Set<List<Object>> validOutcomes = Sets.newHashSet();
Set<Combinator> combinators = Sets.newHashSet();
// Compute function application rules.
for (HeadedSyntacticCategory functionCat : allCategories) {
for (HeadedSyntacticCategory argumentCat : allCategories) {
appendApplicationRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators);
}
}
if (allowComposition) {
// Compute function composition rules.
for (HeadedSyntacticCategory functionCat : allCategories) {
for (HeadedSyntacticCategory argumentCat : allCategories) {
appendCompositionRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators);
}
}
}
appendBinaryRules(rules, syntaxType, validOutcomes, combinators);
return buildSyntaxDistribution(syntaxType, validOutcomes, combinators);
} | java | {
"resource": ""
} |
q16529 | BaseObjectFixture.getClassesToDelete | train | private LinkedList<Class> getClassesToDelete() {
LinkedHashSet<Class> classesToDelete = new LinkedHashSet<Class>();
for (Object object : getObjects()) {
classesToDelete.add(object.getClass());
}
return new LinkedList<Class>(classesToDelete);
} | java | {
"resource": ""
} |
q16530 | SparseTensor.diagonal | train | public static SparseTensor diagonal(int[] dimensionNumbers, int[] dimensionSizes, double value) {
int minDimensionSize = Ints.min(dimensionSizes);
double[] values = new double[minDimensionSize];
Arrays.fill(values, value);
return diagonal(dimensionNumbers, dimensionSizes, values);
} | java | {
"resource": ""
} |
q16531 | CcgCategory.fromSyntaxLf | train | public static CcgCategory fromSyntaxLf(HeadedSyntacticCategory cat, Expression2 lf) {
String head = lf.toString();
head = head.replaceAll(" ", "_");
List<String> subjects = Lists.newArrayList();
List<Integer> argumentNums = Lists.newArrayList();
List<Integer> objects = Lists.newArrayList();
List<HeadedSyntacticCategory> argumentCats = Lists.newArrayList(cat.getArgumentTypes());
Collections.reverse(argumentCats);
for (int i = 0; i < argumentCats.size(); i++) {
subjects.add(head);
argumentNums.add(i + 1);
objects.add(argumentCats.get(i).getHeadVariable());
}
List<Set<String>> assignments = Lists.newArrayList();
for (int i = 0; i < cat.getUniqueVariables().length; i++) {
assignments.add(Collections.<String>emptySet());
}
int headVar = cat.getHeadVariable();
assignments.set(headVar, Sets.newHashSet(head));
return new CcgCategory(cat, lf, subjects, argumentNums, objects, assignments);
} | java | {
"resource": ""
} |
q16532 | CcgCategory.getSemanticHeads | train | public List<String> getSemanticHeads() {
int headSemanticVariable = syntax.getHeadVariable();
int[] allSemanticVariables = getSemanticVariables();
for (int i = 0; i < allSemanticVariables.length; i++) {
if (allSemanticVariables[i] == headSemanticVariable) {
return Lists.newArrayList(variableAssignments.get(i));
}
}
return Collections.emptyList();
} | java | {
"resource": ""
} |
q16533 | ChartEntry.getDerivingCombinatorType | train | public Combinator.Type getDerivingCombinatorType() {
if (combinator == null) {
return Combinator.Type.OTHER;
} else {
return combinator.getType();
}
} | java | {
"resource": ""
} |
q16534 | Backpointers.getOldKeyIndicatorTensor | train | public SparseTensor getOldKeyIndicatorTensor() {
double[] values = new double[oldKeyNums.length];
Arrays.fill(values, 1.0);
return SparseTensor.fromUnorderedKeyValues(oldTensor.getDimensionNumbers(),
oldTensor.getDimensionSizes(), oldKeyNums, values);
} | java | {
"resource": ""
} |
q16535 | LispUtil.readProgram | train | public static SExpression readProgram(List<String> filenames, IndexedList<String> symbolTable) {
StringBuilder programBuilder = new StringBuilder();
programBuilder.append("(begin ");
for (String filename : filenames) {
for (String line : IoUtils.readLines(filename)) {
line = line.replaceAll("^[ \t]*;.*", "");
programBuilder.append(line);
programBuilder.append(" ");
}
}
programBuilder.append(" )");
String program = programBuilder.toString();
ExpressionParser<SExpression> parser = ExpressionParser.sExpression(symbolTable);
SExpression programExpression = parser.parse(program);
return programExpression;
} | java | {
"resource": ""
} |
q16536 | DNSLookup.hasRecords | train | public static boolean hasRecords(String hostName, String dnsType)
throws DNSLookupException {
return DNSLookup.doLookup(hostName, dnsType) > 0;
} | java | {
"resource": ""
} |
q16537 | DNSLookup.doLookup | train | public static int doLookup(String hostName, String dnsType)
throws DNSLookupException {
// JNDI cannot take two-byte chars, so we convert the hostname into Punycode
hostName = UniPunyCode.toPunycodeIfPossible(hostName);
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx;
try {
ictx = new InitialDirContext(env);
} catch (NamingException e) {
throw new DNSInitialContextException(e);
}
Attributes attrs;
try {
attrs = ictx.getAttributes(hostName, new String[] { dnsType });
} catch (NameNotFoundException e) {
// The hostname was not found or is invalid
return -1;
} catch (InvalidAttributeIdentifierException e) {
// The DNS type is invalid
throw new DNSInvalidTypeException(e);
} catch (NamingException e) {
// Unknown reason
throw new DNSLookupException(e);
}
Attribute attr = attrs.get(dnsType);
if (attr == null) {
return 0;
}
return attr.size();
} | java | {
"resource": ""
} |
q16538 | MetricsManager.shutdown | train | public static void shutdown() {
if (MetricsManager.executorService != null) {
MetricsManager.executorService.shutdown();
MetricsManager.executorService = null;
}
if (MetricsManager.instance != null) {
MetricsManager.instance = null;
MetricsManager.poolManager.shutdown();
MetricsManager.poolManager = null;
MetricsManager.httpClient = null;
MetricsManager.rootMetricsLogger = null;
}
} | java | {
"resource": ""
} |
q16539 | MetricsManager.getMetricsLogger | train | public static MetricsLogger getMetricsLogger(final String dimensions) {
if (MetricsManager.instance != null) {
final Map<String, String> dimensionsMap = DimensionsUtils.parseDimensions(dimensions);
if (!dimensionsMap.isEmpty()) {
dimensionsMap.put("service", MetricsManager.instance.serviceName);
if (MetricsManager.instance.env.length() > 0) {
dimensionsMap.put("env", MetricsManager.instance.env);
}
return MetricsManager.instance.metricsLoggers.computeIfAbsent(
DimensionsUtils.serializeDimensionsToString(dimensionsMap), key -> new MetricsLogger(dimensionsMap));
} else {
throw new IllegalArgumentException("Dimensions must be valid and non-empty");
}
}
return dummyLogger;
} | java | {
"resource": ""
} |
q16540 | MetricsManager.flushAll | train | public static void flushAll(long now) {
if (MetricsManager.instance != null) {
MetricsManager.instance.metricsLoggers.values().forEach(MetricsManager::flushMetricsLogger);
flushToServer(now);
}
} | java | {
"resource": ""
} |
q16541 | MetricsManager.flushToServer | train | static void flushToServer(long now) {
LOG.debug("Flush to BeeInstant Server");
Collection<String> readyToSubmit = new ArrayList<>();
metricsQueue.drainTo(readyToSubmit);
StringBuilder builder = new StringBuilder();
readyToSubmit.forEach(string -> {
builder.append(string);
builder.append("\n");
});
if (!readyToSubmit.isEmpty() && beeInstantHost != null) {
try {
final String body = builder.toString();
StringEntity entity = new StringEntity(body);
entity.setContentType("text/plain");
String uri = "/PutMetric";
final String signature = sign(entity);
if (!signature.isEmpty()) {
uri += "?signature=" + URLEncoder.encode(signature, "UTF-8");
uri += "&publicKey=" + URLEncoder.encode(publicKey, "UTF-8");
uri += "×tamp=" + now;
HttpPost putMetricCommand = new HttpPost(uri);
try {
putMetricCommand.setEntity(entity);
HttpResponse response = httpClient.execute(beeInstantHost, putMetricCommand);
LOG.info("Response: " + response.getStatusLine().getStatusCode());
} finally {
putMetricCommand.releaseConnection();
}
}
} catch (Throwable e) {
LOG.error("Fail to emit metrics", e);
}
}
} | java | {
"resource": ""
} |
q16542 | MetricsManager.reportError | train | static void reportError(final String errorMessage) {
if (MetricsManager.instance != null) {
MetricsManager.rootMetricsLogger.incCounter(METRIC_ERRORS, 1);
}
LOG.error(errorMessage);
} | java | {
"resource": ""
} |
q16543 | MetricsManager.flushMetricsLogger | train | static void flushMetricsLogger(final MetricsLogger metricsLogger) {
metricsLogger.flushToString(MetricsManager::queue);
MetricsManager.rootMetricsLogger.flushToString(MetricsManager::queue);
} | java | {
"resource": ""
} |
q16544 | Mappers.identity | train | public static <A> Mapper<A, A> identity() {
return new Mapper<A, A>() {
@Override
public A map(A item) {
return item;
}
};
} | java | {
"resource": ""
} |
q16545 | KeyWrapper.unwrapKeyPair | train | public KeyPair unwrapKeyPair(String wrappedPrivateKey, String encodedPublicKey) {
PrivateKey privateKey = unwrapPrivateKey(wrappedPrivateKey);
PublicKey publicKey = decodePublicKey(encodedPublicKey);
return new KeyPair(publicKey, privateKey);
} | java | {
"resource": ""
} |
q16546 | AbstractTensorBase.mergeDimensions | train | public static final DimensionSpec mergeDimensions(int[] firstDimensionNums, int[] firstDimensionSizes,
int[] secondDimensionNums, int[] secondDimensionSizes) {
SortedSet<Integer> first = Sets.newTreeSet(Ints.asList(firstDimensionNums));
SortedSet<Integer> second = Sets.newTreeSet(Ints.asList(secondDimensionNums));
SortedSet<Integer> all = Sets.newTreeSet(first);
all.addAll(second);
int[] resultDims = Ints.toArray(all);
int[] resultSizes = new int[resultDims.length];
for (int i = 0; i < resultDims.length; i++) {
int dim = resultDims[i];
if (first.contains(dim) && second.contains(dim)) {
int firstIndex = Ints.indexOf(firstDimensionNums, dim);
int secondIndex = Ints.indexOf(secondDimensionNums, dim);
int firstSize = firstDimensionSizes[firstIndex];
int secondSize = secondDimensionSizes[secondIndex];
Preconditions.checkArgument(firstSize == secondSize,
"Dimension sizes do not match: dim %s, sizes %s and %s.", dim, firstSize, secondSize);
resultSizes[i] = firstSize;
} else if (first.contains(dim)) {
int firstIndex = Ints.indexOf(firstDimensionNums, dim);
int firstSize = firstDimensionSizes[firstIndex];
resultSizes[i] = firstSize;
} else {
int secondIndex = Ints.indexOf(secondDimensionNums, dim);
int secondSize = secondDimensionSizes[secondIndex];
resultSizes[i] = secondSize;
}
}
return new DimensionSpec(resultDims, resultSizes);
} | java | {
"resource": ""
} |
q16547 | ListSequence.next | train | @Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException(toString() + " ended");
}
current = iterator.next();
return current();
} | java | {
"resource": ""
} |
q16548 | BasicExporter.buildClassContainer | train | <T> IClassContainer buildClassContainer(final List<T> list) {
return (BasicCollectionUtils.isNotEmpty(list))
? buildClassContainer(list.get(0))
: null;
} | java | {
"resource": ""
} |
q16549 | BasicExporter.buildWriter | train | IWriter buildWriter(final IClassContainer classContainer) {
try {
return new BufferedFileWriter(classContainer.getExportClassName(), path, format.getExtension());
} catch (IOException e) {
logger.warning(e.getMessage());
return null;
}
} | java | {
"resource": ""
} |
q16550 | BasicExporter.extractExportContainers | train | <T> List<ExportContainer> extractExportContainers(final T t,
final IClassContainer classContainer) {
final List<ExportContainer> exports = new ArrayList<>();
// Using only SIMPLE values containers
classContainer.getFormatSupported(format).forEach((k, v) -> {
try {
k.setAccessible(true);
final String exportFieldName = v.getExportName();
final Object exportFieldValue = k.get(t);
exports.add(buildContainer(exportFieldName, exportFieldValue, v.getType()));
k.setAccessible(false);
} catch (Exception ex) {
logger.warning(ex.getMessage());
}
});
return exports;
} | java | {
"resource": ""
} |
q16551 | BasicExporter.isExportEntityInvalid | train | <T> boolean isExportEntityInvalid(final List<T> t) {
return (BasicCollectionUtils.isEmpty(t) || isExportEntityInvalid(t.get(0)));
} | java | {
"resource": ""
} |
q16552 | ExpressionSimplifier.lambdaCalculus | train | public static ExpressionSimplifier lambdaCalculus() {
List<ExpressionReplacementRule> rules = Lists.newArrayList();
rules.add(new LambdaApplicationReplacementRule());
rules.add(new VariableCanonicalizationReplacementRule());
return new ExpressionSimplifier(rules);
} | java | {
"resource": ""
} |
q16553 | IsEMail.is_email | train | public static boolean is_email(String email, boolean checkDNS)
throws DNSLookupException {
return (is_email_verbose(email, checkDNS).getState() == GeneralState.OK);
} | java | {
"resource": ""
} |
q16554 | IsEMail.replaceCharAt | train | private static String replaceCharAt(String s, int pos, char c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
} | java | {
"resource": ""
} |
q16555 | CfgParseChart.updateOutsideEntry | train | public void updateOutsideEntry(int spanStart, int spanEnd, double[] values, Factor factor, VariableNumMap var) {
if (sumProduct) {
updateEntrySumProduct(outsideChart[spanStart][spanEnd],
values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum());
} else {
updateEntryMaxProduct(outsideChart[spanStart][spanEnd],
values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum());
}
} | java | {
"resource": ""
} |
q16556 | CfgParseChart.getInsideEntries | train | public Factor getInsideEntries(int spanStart, int spanEnd) {
Tensor entries = new DenseTensor(parentVar.getVariableNumsArray(),
parentVar.getVariableSizes(), insideChart[spanStart][spanEnd]);
return new TableFactor(parentVar, entries);
} | java | {
"resource": ""
} |
q16557 | CfgParseChart.getOutsideEntries | train | public Factor getOutsideEntries(int spanStart, int spanEnd) {
Tensor entries = new DenseTensor(parentVar.getVariableNumsArray(),
parentVar.getVariableSizes(), outsideChart[spanStart][spanEnd]);
return new TableFactor(parentVar, entries);
} | java | {
"resource": ""
} |
q16558 | CfgParseChart.getMarginalEntries | train | public Factor getMarginalEntries(int spanStart, int spanEnd) {
return getOutsideEntries(spanStart, spanEnd).product(getInsideEntries(spanStart, spanEnd));
} | java | {
"resource": ""
} |
q16559 | CfgParseChart.getBestParseTree | train | public CfgParseTree getBestParseTree() {
Factor rootMarginal = getMarginalEntries(0, chartSize() - 1);
Assignment bestAssignment = rootMarginal.getMostLikelyAssignments(1).get(0);
return getBestParseTree(bestAssignment.getOnlyValue());
} | java | {
"resource": ""
} |
q16560 | CfgParseChart.getBestParseTreeWithSpan | train | public CfgParseTree getBestParseTreeWithSpan(Object root, int spanStart,
int spanEnd) {
Preconditions.checkState(!sumProduct);
Assignment rootAssignment = parentVar.outcomeArrayToAssignment(root);
int rootNonterminalNum = parentVar.assignmentToIntArray(rootAssignment)[0];
double prob = insideChart[spanStart][spanEnd][rootNonterminalNum]
* outsideChart[spanStart][spanEnd][rootNonterminalNum];
if (prob == 0.0) {
return null;
}
int splitInd = splitBackpointers[spanStart][spanEnd][rootNonterminalNum];
if (splitInd < 0) {
long terminalKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int positiveSplitInd = (-1 * splitInd) - 1;
int terminalSpanStart = positiveSplitInd / numTerminals;
int terminalSpanEnd = positiveSplitInd % numTerminals;
// This is a really sucky way to transform the keys back to objects.
VariableNumMap vars = parentVar.union(ruleTypeVar);
int[] dimKey = TableFactor.zero(vars).getWeights().keyNumToDimKey(terminalKey);
Assignment a = vars.intArrayToAssignment(dimKey);
Object ruleType = a.getValue(ruleTypeVar.getOnlyVariableNum());
List<Object> terminalList = Lists.newArrayList();
terminalList.addAll(terminals.subList(terminalSpanStart, terminalSpanEnd + 1));
return new CfgParseTree(root, ruleType, terminalList, prob, spanStart, spanEnd);
} else {
long binaryRuleKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int[] binaryRuleComponents = binaryRuleDistribution.coerceToDiscrete()
.getWeights().keyNumToDimKey(binaryRuleKey);
Assignment best = binaryRuleDistribution.getVars().intArrayToAssignment(binaryRuleComponents);
Object leftRoot = best.getValue(leftVar.getOnlyVariableNum());
Object rightRoot = best.getValue(rightVar.getOnlyVariableNum());
Object ruleType = best.getValue(ruleTypeVar.getOnlyVariableNum());
Preconditions.checkArgument(spanStart + splitInd != spanEnd,
"CFG parse decoding error: %s %s %s", spanStart, spanEnd, splitInd);
CfgParseTree leftTree = getBestParseTreeWithSpan(leftRoot, spanStart, spanStart + splitInd);
CfgParseTree rightTree = getBestParseTreeWithSpan(rightRoot, spanStart + splitInd + 1, spanEnd);
Preconditions.checkState(leftTree != null);
Preconditions.checkState(rightTree != null);
return new CfgParseTree(root, ruleType, leftTree, rightTree, prob);
}
} | java | {
"resource": ""
} |
q16561 | LongIntVectorSlice.get | train | public int get(long idx) {
if (idx < 0 || idx >= size) {
return 0;
}
return elements[SafeCast.safeLongToInt(idx + start)];
} | java | {
"resource": ""
} |
q16562 | BaseXmlParser.findTag | train | protected Element findTag(String tagName, Element element) {
Node result = element.getFirstChild();
while (result != null) {
if (result instanceof Element
&& (tagName.equals(((Element) result).getNodeName()) || tagName
.equals(((Element) result).getLocalName()))) {
break;
}
result = result.getNextSibling();
}
return (Element) result;
} | java | {
"resource": ""
} |
q16563 | BaseXmlParser.getTagChildren | train | protected NodeList getTagChildren(String tagName, Element element) {
return element.getNamespaceURI() == null ? element.getElementsByTagName(tagName) : element.getElementsByTagNameNS(
element.getNamespaceURI(), tagName);
} | java | {
"resource": ""
} |
q16564 | BaseXmlParser.addProperties | train | protected void addProperties(Element element, BeanDefinitionBuilder builder) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
String attrName = getNodeName(node);
attrName = "class".equals(attrName) ? "clazz" : attrName;
builder.addPropertyValue(attrName, node.getNodeValue());
}
} | java | {
"resource": ""
} |
q16565 | BaseXmlParser.getNodeName | train | protected String getNodeName(Node node) {
String result = node.getLocalName();
return result == null ? node.getNodeName() : result;
} | java | {
"resource": ""
} |
q16566 | BaseXmlParser.fromXml | train | protected Object fromXml(String xml, String tagName) throws Exception {
Document document = XMLUtil.parseXMLFromString(xml);
NodeList nodeList = document.getElementsByTagName(tagName);
if (nodeList == null || nodeList.getLength() != 1) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Top level tag '" + tagName + "' was not found.");
}
Element element = (Element) nodeList.item(0);
Class<?> beanClass = getBeanClass(element);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
doParse(element, builder);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.setParentBeanFactory(SpringUtil.getAppContext());
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
factory.registerBeanDefinition(tagName, beanDefinition);
return factory.getBean(tagName);
} | java | {
"resource": ""
} |
q16567 | BaseXmlParser.getResourcePath | train | protected String getResourcePath(ParserContext parserContext) {
if (parserContext != null) {
try {
Resource resource = parserContext.getReaderContext().getResource();
return resource == null ? null : resource.getURL().getPath();
} catch (IOException e) {}
}
return null;
} | java | {
"resource": ""
} |
q16568 | ActionListener.removeAction | train | protected void removeAction() {
component.removeEventListener(eventName, this);
if (component.getAttribute(attrName) == this) {
component.removeAttribute(attrName);
}
} | java | {
"resource": ""
} |
q16569 | SourceLoader.isHelpSetFile | train | public boolean isHelpSetFile(String fileName) {
if (helpSetFilter == null) {
helpSetFilter = new WildcardFileFilter(helpSetPattern);
}
return helpSetFilter.accept(new File(fileName));
} | java | {
"resource": ""
} |
q16570 | SourceLoader.load | train | public IResourceIterator load(String archiveName) throws Exception {
File file = new File(archiveName);
if (file.isDirectory()) {
return new DirectoryIterator(file);
}
return iteratorClass.getConstructor(String.class).newInstance(archiveName);
} | java | {
"resource": ""
} |
q16571 | ElementFrame.setUrl | train | public void setUrl(String url) {
this.url = url;
if (child != null) {
child.destroy();
child = null;
}
if (url.startsWith("http") || !url.endsWith(".fsp")) {
child = new Iframe();
((Iframe) child).setSrc(url);
} else {
child = new Import();
((Import) child).setSrc(url);
}
fullSize(child);
root.addChild(child);
} | java | {
"resource": ""
} |
q16572 | ContextSerializerRegistry.get | train | @Override
public ISerializer<?> get(Class<?> clazz) {
ISerializer<?> contextSerializer = super.get(clazz);
if (contextSerializer != null) {
return contextSerializer;
}
for (ISerializer<?> item : this) {
if (item.getType().isAssignableFrom(clazz)) {
return item;
}
}
return null;
} | java | {
"resource": ""
} |
q16573 | Layout.materialize | train | public ElementUI materialize(ElementUI parent) {
boolean isDesktop = parent instanceof ElementDesktop;
if (isDesktop) {
parent.getDefinition().initElement(parent, root);
}
materializeChildren(parent, root, !isDesktop);
ElementUI element = parent.getLastVisibleChild();
if (element != null) {
element.getRoot().activate(true);
}
return element;
} | java | {
"resource": ""
} |
q16574 | Layout.materializeChildren | train | private void materializeChildren(ElementBase parent, LayoutElement node, boolean ignoreInternal) {
for (LayoutNode child : node.getChildren()) {
PluginDefinition def = child.getDefinition();
ElementBase element = ignoreInternal && def.isInternal() ? null : createElement(parent, child);
if (element != null) {
materializeChildren(element, (LayoutElement) child, false);
}
}
for (LayoutTrigger trigger : node.getTriggers()) {
ElementTrigger trg = new ElementTrigger();
trg.addTarget((ElementUI) parent);
createElement(trg, trigger.getChild(LayoutTriggerCondition.class));
createElement(trg, trigger.getChild(LayoutTriggerAction.class));
((ElementUI) parent).addTrigger(trg);
}
} | java | {
"resource": ""
} |
q16575 | Layout.setName | train | public void setName(String value) {
layoutName = value;
if (root != null) {
root.getAttributes().put("name", value);
}
} | java | {
"resource": ""
} |
q16576 | Layout.saveToProperty | train | public boolean saveToProperty(LayoutIdentifier layoutId) {
setName(layoutId.name);
try {
LayoutUtil.saveLayout(layoutId, toString());
} catch (Exception e) {
log.error("Error saving application layout.", e);
return false;
}
return true;
} | java | {
"resource": ""
} |
q16577 | Layout.getRootClass | train | public Class<? extends ElementBase> getRootClass() {
LayoutElement top = root == null ? null : root.getChild(LayoutElement.class);
return top == null ? null : top.getDefinition().getClazz();
} | java | {
"resource": ""
} |
q16578 | Layout.fromClipboard | train | @Override
public Layout fromClipboard(String data) {
init(LayoutParser.parseText(data).root);
return this;
} | java | {
"resource": ""
} |
q16579 | ProducerService.publish | train | public boolean publish(String channel, Message message, Recipient... recipients) {
boolean result = false;
prepare(channel, message, recipients);
for (IMessageProducer producer : producers) {
result |= producer.publish(channel, message);
}
return result;
} | java | {
"resource": ""
} |
q16580 | ProducerService.publish | train | private boolean publish(String channel, Message message, IMessageProducer producer, Recipient[] recipients) {
if (producer != null) {
prepare(channel, message, recipients);
return producer.publish(channel, message);
}
return false;
} | java | {
"resource": ""
} |
q16581 | ProducerService.findRegisteredProducer | train | private IMessageProducer findRegisteredProducer(Class<?> clazz) {
for (IMessageProducer producer : producers) {
if (clazz.isInstance(producer)) {
return producer;
}
}
return null;
} | java | {
"resource": ""
} |
q16582 | ProducerService.prepare | train | private Message prepare(String channel, Message message, Recipient[] recipients) {
message.setMetadata("cwf.pub.node", nodeId);
message.setMetadata("cwf.pub.channel", channel);
message.setMetadata("cwf.pub.event", UUID.randomUUID().toString());
message.setMetadata("cwf.pub.when", System.currentTimeMillis());
message.setMetadata("cwf.pub.recipients", recipients);
return message;
} | java | {
"resource": ""
} |
q16583 | DefaultSegmentedClient.replaceFinalComponent | train | protected Interest replaceFinalComponent(Interest interest, long segmentNumber, byte marker) {
Interest copied = new Interest(interest);
Component lastComponent = Component.fromNumberWithMarker(segmentNumber, marker);
Name newName = (SegmentationHelper.isSegmented(copied.getName(), marker))
? copied.getName().getPrefix(-1)
: new Name(copied.getName());
copied.setName(newName.append(lastComponent));
return copied;
} | java | {
"resource": ""
} |
q16584 | DateTimeUtil.setTime | train | public static void setTime(Datebox datebox, Timebox timebox, Date value) {
value = value == null ? new Date() : value;
datebox.setValue(DateUtil.stripTime(value));
timebox.setValue(value);
} | java | {
"resource": ""
} |
q16585 | ForLoopRepository.isFresh | train | private boolean isFresh(Record record) {
double period = record.data.getMetaInfo().getFreshnessPeriod();
return period < 0 || record.addedAt + (long) period > System.currentTimeMillis();
} | java | {
"resource": ""
} |
q16586 | HelpHistory.sameTopic | train | private boolean sameTopic(HelpTopic topic1, HelpTopic topic2) {
return topic1 == topic2 || (topic1 != null && topic2 != null && topic1.equals(topic2));
} | java | {
"resource": ""
} |
q16587 | ContextItems.lookupItemName | train | private String lookupItemName(String itemName, boolean autoAdd) {
String indexedName = index.get(itemName.toLowerCase());
if (indexedName == null && autoAdd) {
index.put(itemName.toLowerCase(), itemName);
}
return indexedName == null ? itemName : indexedName;
} | java | {
"resource": ""
} |
q16588 | ContextItems.lookupItemName | train | private String lookupItemName(String itemName, String suffix, boolean autoAdd) {
return lookupItemName(itemName + "." + suffix, autoAdd);
} | java | {
"resource": ""
} |
q16589 | ContextItems.removeSubject | train | public void removeSubject(String subject) {
String prefix = normalizePrefix(subject);
for (String suffix : getSuffixes(prefix).keySet()) {
setItem(prefix + suffix, null);
}
} | java | {
"resource": ""
} |
q16590 | ContextItems.getSuffixes | train | private Map<String, String> getSuffixes(String prefix, Boolean firstOnly) {
HashMap<String, String> matches = new HashMap<>();
prefix = normalizePrefix(prefix);
int i = prefix.length();
for (String itemName : index.keySet()) {
if (itemName.startsWith(prefix)) {
String suffix = lookupItemName(itemName, false).substring(i);
matches.put(suffix, getItem(itemName));
if (firstOnly) {
break;
}
}
}
return matches;
} | java | {
"resource": ""
} |
q16591 | ContextItems.getItem | train | public String getItem(String itemName, String suffix) {
return items.get(lookupItemName(itemName, suffix, false));
} | java | {
"resource": ""
} |
q16592 | ContextItems.getItem | train | @SuppressWarnings("unchecked")
public <T> T getItem(String itemName, Class<T> clazz) throws ContextException {
String item = getItem(itemName);
if (item == null || item.isEmpty()) {
return null;
}
ISerializer<?> contextSerializer = ContextSerializerRegistry.getInstance().get(clazz);
if (contextSerializer == null) {
throw new ContextException("No serializer found for type " + clazz.getName());
}
return (T) contextSerializer.deserialize(item);
} | java | {
"resource": ""
} |
q16593 | ContextItems.setItem | train | public void setItem(String itemName, String value, String suffix) {
itemName = lookupItemName(itemName, suffix, value != null);
items.put(itemName, value);
} | java | {
"resource": ""
} |
q16594 | ContextItems.setDate | train | public void setDate(String itemName, Date date) {
if (date == null) {
setItem(itemName, null);
} else {
setItem(itemName, DateUtil.toHL7(date));
}
} | java | {
"resource": ""
} |
q16595 | ContextItems.getDate | train | public Date getDate(String itemName) {
try {
return DateUtil.parseDate(getItem(itemName));
} catch (Exception e) {
return null;
}
} | java | {
"resource": ""
} |
q16596 | ContextItems.addItems | train | public void addItems(String values) throws Exception {
for (String line : values.split("[\\r\\n]")) {
String[] pcs = line.split("\\=", 2);
if (pcs.length == 2) {
setItem(pcs[0], pcs[1]);
}
}
} | java | {
"resource": ""
} |
q16597 | ContextItems.addItems | train | private void addItems(Map<String, String> values) {
for (String itemName : values.keySet()) {
setItem(itemName, values.get(itemName));
}
} | java | {
"resource": ""
} |
q16598 | BaseUtil.getLibraryPaths | train | public static String[] getLibraryPaths() {
String libraryPathString = System.getProperty("java.library.path");
String pathSeparator = System.getProperty("path.separator");
return libraryPathString.split(pathSeparator);
} | java | {
"resource": ""
} |
q16599 | IndexCommandImpl.put | train | public String put(final String key, final String Value) {
return parameters.put(key, Value);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.