_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7700 | Guestbook.addGreeting | train | private void addGreeting(String guestbookName, String user, String message)
throws DatastoreException {
Entity.Builder greeting = Entity.newBuilder();
greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));
greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());
greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());
greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());
Key greetingKey = insert(greeting.build());
System.out.println("greeting key is: " + greetingKey);
} | java | {
"resource": ""
} |
q7701 | Guestbook.listGreetings | train | private void listGreetings(String guestbookName) throws DatastoreException {
Query.Builder query = Query.newBuilder();
query.addKindBuilder().setName(GREETING_KIND);
query.setFilter(makeFilter(KEY_PROPERTY, PropertyFilter.Operator.HAS_ANCESTOR,
makeValue(makeKey(GUESTBOOK_KIND, guestbookName))));
query.addOrder(makeOrder(DATE_PROPERTY, PropertyOrder.Direction.DESCENDING));
List<Entity> greetings = runQuery(query.build());
if (greetings.size() == 0) {
System.out.println("no greetings in " + guestbookName);
}
for (Entity greeting : greetings) {
Map<String, Value> propertyMap = greeting.getProperties();
System.out.println(
DatastoreHelper.toDate(propertyMap.get(DATE_PROPERTY)) + ": " +
DatastoreHelper.getString(propertyMap.get(USER_PROPERTY)) + " says " +
DatastoreHelper.getString(propertyMap.get(MESSAGE_PROPERTY)));
}
} | java | {
"resource": ""
} |
q7702 | Guestbook.insert | train | private Key insert(Entity entity) throws DatastoreException {
CommitRequest req = CommitRequest.newBuilder()
.addMutations(Mutation.newBuilder()
.setInsert(entity))
.setMode(CommitRequest.Mode.NON_TRANSACTIONAL)
.build();
return datastore.commit(req).getMutationResults(0).getKey();
} | java | {
"resource": ""
} |
q7703 | Guestbook.runQuery | train | private List<Entity> runQuery(Query query) throws DatastoreException {
RunQueryRequest.Builder request = RunQueryRequest.newBuilder();
request.setQuery(query);
RunQueryResponse response = datastore.runQuery(request.build());
if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {
System.err.println("WARNING: partial results\n");
}
List<EntityResult> results = response.getBatch().getEntityResultsList();
List<Entity> entities = new ArrayList<Entity>(results.size());
for (EntityResult result : results) {
entities.add(result.getEntity());
}
return entities;
} | java | {
"resource": ""
} |
q7704 | QuerySplitterImpl.validateFilter | train | private void validateFilter(Filter filter) throws IllegalArgumentException {
switch (filter.getFilterTypeCase()) {
case COMPOSITE_FILTER:
for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {
validateFilter(subFilter);
}
break;
case PROPERTY_FILTER:
if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {
throw new IllegalArgumentException("Query cannot have any inequality filters.");
}
break;
default:
throw new IllegalArgumentException(
"Unsupported filter type: " + filter.getFilterTypeCase());
}
} | java | {
"resource": ""
} |
q7705 | QuerySplitterImpl.validateQuery | train | private void validateQuery(Query query) throws IllegalArgumentException {
if (query.getKindCount() != 1) {
throw new IllegalArgumentException("Query must have exactly one kind.");
}
if (query.getOrderCount() != 0) {
throw new IllegalArgumentException("Query cannot have any sort orders.");
}
if (query.hasFilter()) {
validateFilter(query.getFilter());
}
} | java | {
"resource": ""
} |
q7706 | QuerySplitterImpl.getScatterKeys | train | private List<Key> getScatterKeys(
int numSplits, Query query, PartitionId partition, Datastore datastore)
throws DatastoreException {
Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);
List<Key> keySplits = new ArrayList<Key>();
QueryResultBatch batch;
do {
RunQueryRequest scatterRequest =
RunQueryRequest.newBuilder()
.setPartitionId(partition)
.setQuery(scatterPointQuery)
.build();
batch = datastore.runQuery(scatterRequest).getBatch();
for (EntityResult result : batch.getEntityResultsList()) {
keySplits.add(result.getEntity().getKey());
}
scatterPointQuery.setStartCursor(batch.getEndCursor());
scatterPointQuery.getLimitBuilder().setValue(
scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());
} while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);
Collections.sort(keySplits, DatastoreHelper.getKeyComparator());
return keySplits;
} | java | {
"resource": ""
} |
q7707 | QuerySplitterImpl.createScatterQuery | train | private Query.Builder createScatterQuery(Query query, int numSplits) {
// TODO(pcostello): We can potentially support better splits with equality filters in our query
// if there exists a composite index on property, __scatter__, __key__. Until an API for
// metadata exists, this isn't possible. Note that ancestor and inequality queries fall into
// the same category.
Query.Builder scatterPointQuery = Query.newBuilder();
scatterPointQuery.addAllKind(query.getKindList());
scatterPointQuery.addOrder(DatastoreHelper.makeOrder(
DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));
// There is a split containing entities before and after each scatter entity:
// ||---*------*------*------*------*------*------*---|| = scatter entity
// If we represent each split as a region before a scatter entity, there is an extra region
// following the last scatter point. Thus, we do not need the scatter entities for the last
// region.
scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);
scatterPointQuery.addProjection(Projection.newBuilder().setProperty(
PropertyReference.newBuilder().setName("__key__")));
return scatterPointQuery;
} | java | {
"resource": ""
} |
q7708 | QuerySplitterImpl.getSplitKey | train | private Iterable<Key> getSplitKey(List<Key> keys, int numSplits) {
// If the number of keys is less than the number of splits, we are limited in the number of
// splits we can make.
if (keys.size() < numSplits - 1) {
return keys;
}
// Calculate the number of keys per split. This should be KEYS_PER_SPLIT, but may
// be less if there are not KEYS_PER_SPLIT * (numSplits - 1) scatter entities.
//
// Consider the following dataset, where - represents an entity and * represents an entity
// that is returned as a scatter entity:
// ||---*-----*----*-----*-----*------*----*----||
// If we want 4 splits in this data, the optimal split would look like:
// ||---*-----*----*-----*-----*------*----*----||
// | | |
// The scatter keys in the last region are not useful to us, so we never request them:
// ||---*-----*----*-----*-----*------*---------||
// | | |
// With 6 scatter keys we want to set scatter points at indexes: 1, 3, 5.
//
// We keep this as a double so that any "fractional" keys per split get distributed throughout
// the splits and don't make the last split significantly larger than the rest.
double numKeysPerSplit = Math.max(1.0, ((double) keys.size()) / (numSplits - 1));
List<Key> keysList = new ArrayList<Key>(numSplits - 1);
// Grab the last sample for each split, otherwise the first split will be too small.
for (int i = 1; i < numSplits; i++) {
int splitIndex = (int) Math.round(i * numKeysPerSplit) - 1;
keysList.add(keys.get(splitIndex));
}
return keysList;
} | java | {
"resource": ""
} |
q7709 | DatastoreFactory.makeClient | train | public HttpRequestFactory makeClient(DatastoreOptions options) {
Credential credential = options.getCredential();
HttpTransport transport = options.getTransport();
if (transport == null) {
transport = credential == null ? new NetHttpTransport() : credential.getTransport();
transport = transport == null ? new NetHttpTransport() : transport;
}
return transport.createRequestFactory(credential);
} | java | {
"resource": ""
} |
q7710 | DatastoreFactory.buildProjectEndpoint | train | String buildProjectEndpoint(DatastoreOptions options) {
if (options.getProjectEndpoint() != null) {
return options.getProjectEndpoint();
}
// DatastoreOptions ensures either project endpoint or project ID is set.
String projectId = checkNotNull(options.getProjectId());
if (options.getHost() != null) {
return validateUrl(String.format("https://%s/%s/projects/%s",
options.getHost(), VERSION, projectId));
} else if (options.getLocalHost() != null) {
return validateUrl(String.format("http://%s/%s/projects/%s",
options.getLocalHost(), VERSION, projectId));
}
return validateUrl(String.format("%s/%s/projects/%s",
DEFAULT_HOST, VERSION, projectId));
} | java | {
"resource": ""
} |
q7711 | DatastoreFactory.getStreamHandler | train | private static synchronized StreamHandler getStreamHandler() {
if (methodHandler == null) {
methodHandler = new ConsoleHandler();
methodHandler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return record.getMessage() + "\n";
}
});
methodHandler.setLevel(Level.FINE);
}
return methodHandler;
} | java | {
"resource": ""
} |
q7712 | DatastoreHelper.getServiceAccountCredential | train | public static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes)
throws GeneralSecurityException, IOException {
return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))
.build();
} | java | {
"resource": ""
} |
q7713 | DatastoreHelper.makeOrder | train | public static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction) {
return PropertyOrder.newBuilder()
.setProperty(makePropertyReference(property))
.setDirection(direction);
} | java | {
"resource": ""
} |
q7714 | DatastoreHelper.makeAncestorFilter | train | public static Filter.Builder makeAncestorFilter(Key ancestor) {
return makeFilter(
DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,
makeValue(ancestor));
} | java | {
"resource": ""
} |
q7715 | DatastoreHelper.makeAndFilter | train | public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {
return Filter.newBuilder()
.setCompositeFilter(CompositeFilter.newBuilder()
.addAllFilters(subfilters)
.setOp(CompositeFilter.Operator.AND));
} | java | {
"resource": ""
} |
q7716 | DatastoreHelper.makeValue | train | public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {
ArrayValue.Builder arrayValue = ArrayValue.newBuilder();
arrayValue.addValues(value1);
arrayValue.addValues(value2);
arrayValue.addAllValues(Arrays.asList(rest));
return Value.newBuilder().setArrayValue(arrayValue);
} | java | {
"resource": ""
} |
q7717 | DatastoreHelper.makeValue | train | public static Value.Builder makeValue(Date date) {
return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));
} | java | {
"resource": ""
} |
q7718 | ListExtensions.sortInplace | train | public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) {
Collections.sort(list);
return list;
} | java | {
"resource": ""
} |
q7719 | ListExtensions.sortInplaceBy | train | public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,
final Functions.Function1<? super T, C> key) {
if (key == null)
throw new NullPointerException("key");
Collections.sort(list, new KeyComparator<T, C>(key));
return list;
} | java | {
"resource": ""
} |
q7720 | ListExtensions.reverseView | train | @Pure
public static <T> List<T> reverseView(List<T> list) {
return Lists.reverse(list);
} | java | {
"resource": ""
} |
q7721 | ReflectExtensions.set | train | public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Preconditions.checkNotNull(receiver,"receiver");
Preconditions.checkNotNull(fieldName,"fieldName");
Class<? extends Object> clazz = receiver.getClass();
Field f = getDeclaredField(clazz, fieldName);
if (!f.isAccessible())
f.setAccessible(true);
f.set(receiver, value);
} | java | {
"resource": ""
} |
q7722 | ReflectExtensions.get | train | @SuppressWarnings("unchecked")
/* @Nullable */
public <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Preconditions.checkNotNull(receiver,"receiver");
Preconditions.checkNotNull(fieldName,"fieldName");
Class<? extends Object> clazz = receiver.getClass();
Field f = getDeclaredField(clazz, fieldName);
if (!f.isAccessible())
f.setAccessible(true);
return (T) f.get(receiver);
} | java | {
"resource": ""
} |
q7723 | StringConcatenation.append | train | public void append(Object object, String indentation) {
append(object, indentation, segments.size());
} | java | {
"resource": ""
} |
q7724 | StringConcatenation.append | train | public void append(String str, String indentation) {
if (indentation.isEmpty()) {
append(str);
} else if (str != null)
append(indentation, str, segments.size());
} | java | {
"resource": ""
} |
q7725 | StringConcatenation.append | train | protected void append(Object object, String indentation, int index) {
if (indentation.length() == 0) {
append(object, index);
return;
}
if (object == null)
return;
if (object instanceof String) {
append(indentation, (String)object, index);
} else if (object instanceof StringConcatenation) {
StringConcatenation other = (StringConcatenation) object;
List<String> otherSegments = other.getSignificantContent();
appendSegments(indentation, index, otherSegments, other.lineDelimiter);
} else if (object instanceof StringConcatenationClient) {
StringConcatenationClient other = (StringConcatenationClient) object;
other.appendTo(new IndentedTarget(this, indentation, index));
} else {
final String text = getStringRepresentation(object);
if (text != null) {
append(indentation, text, index);
}
}
} | java | {
"resource": ""
} |
q7726 | StringConcatenation.appendImmediate | train | public void appendImmediate(Object object, String indentation) {
for (int i = segments.size() - 1; i >= 0; i--) {
String segment = segments.get(i);
for (int j = 0; j < segment.length(); j++) {
if (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {
append(object, indentation, i + 1);
return;
}
}
}
append(object, indentation, 0);
} | java | {
"resource": ""
} |
q7727 | StringConcatenation.newLineIfNotEmpty | train | public void newLineIfNotEmpty() {
for (int i = segments.size() - 1; i >= 0; i--) {
String segment = segments.get(i);
if (lineDelimiter.equals(segment)) {
segments.subList(i + 1, segments.size()).clear();
cachedToString = null;
return;
}
for (int j = 0; j < segment.length(); j++) {
if (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {
newLine();
return;
}
}
}
segments.clear();
cachedToString = null;
} | java | {
"resource": ""
} |
q7728 | StringConcatenation.splitLinesAndNewLines | train | protected List<String> splitLinesAndNewLines(String text) {
if (text == null)
return Collections.emptyList();
int idx = initialSegmentSize(text);
if (idx == text.length()) {
return Collections.singletonList(text);
}
return continueSplitting(text, idx);
} | java | {
"resource": ""
} |
q7729 | Pair.of | train | @Pure
public static <K, V> Pair<K, V> of(K k, V v) {
return new Pair<K, V>(k, v);
} | java | {
"resource": ""
} |
q7730 | ProcedureExtensions.curry | train | @Pure
public static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure0() {
@Override
public void apply() {
procedure.apply(argument);
}
};
} | java | {
"resource": ""
} |
q7731 | ProcedureExtensions.curry | train | @Pure
public static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure1<P2>() {
@Override
public void apply(P2 p) {
procedure.apply(argument, p);
}
};
} | java | {
"resource": ""
} |
q7732 | ProcedureExtensions.curry | train | @Pure
public static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure2<P2, P3>() {
@Override
public void apply(P2 p2, P3 p3) {
procedure.apply(argument, p2, p3);
}
};
} | java | {
"resource": ""
} |
q7733 | ProcedureExtensions.curry | train | @Pure
public static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,
final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure4<P2, P3, P4, P5>() {
@Override
public void apply(P2 p2, P3 p3, P4 p4, P5 p5) {
procedure.apply(argument, p2, p3, p4, p5);
}
};
} | java | {
"resource": ""
} |
q7734 | Path.getParent | train | public Path getParent() {
if (!isAbsolute())
throw new IllegalStateException("path is not absolute: " + toString());
if (segments.isEmpty())
return null;
return new Path(segments.subList(0, segments.size()-1), true);
} | java | {
"resource": ""
} |
q7735 | Path.relativize | train | public Path relativize(Path other) {
if (other.isAbsolute() != isAbsolute())
throw new IllegalArgumentException("This path and the given path are not both absolute or both relative: " + toString() + " | " + other.toString());
if (startsWith(other)) {
return internalRelativize(this, other);
} else if (other.startsWith(this)) {
return internalRelativize(other, this);
}
return null;
} | java | {
"resource": ""
} |
q7736 | MapExtensions.operator_add | train | @Inline(value = "$1.put($2.getKey(), $2.getValue())", statementExpression = true)
public static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {
return map.put(entry.getKey(), entry.getValue());
} | java | {
"resource": ""
} |
q7737 | MapExtensions.operator_add | train | @Inline(value = "$1.putAll($2)", statementExpression = true)
public static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) {
outputMap.putAll(inputMap);
} | java | {
"resource": ""
} |
q7738 | MapExtensions.operator_plus | train | @Pure
@Inline(value = "$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))",
imported = { MapExtensions.class, Collections.class })
public static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {
return union(left, Collections.singletonMap(right.getKey(), right.getValue()));
} | java | {
"resource": ""
} |
q7739 | MapExtensions.operator_plus | train | @Pure
@Inline(value = "$3.union($1, $2)", imported = MapExtensions.class)
public static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {
return union(left, right);
} | java | {
"resource": ""
} |
q7740 | MapExtensions.operator_remove | train | @Inline(value = "$1.remove($2)", statementExpression = true)
public static <K, V> V operator_remove(Map<K, V> map, K key) {
return map.remove(key);
} | java | {
"resource": ""
} |
q7741 | MapExtensions.operator_remove | train | @Inline(value = "$1.remove($2.getKey(), $2.getValue())", statementExpression = true)
public static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {
//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());
final K key = entry.getKey();
final V storedValue = map.get(entry.getKey());
if (!Objects.equal(storedValue, entry.getValue())
|| (storedValue == null && !map.containsKey(key))) {
return false;
}
map.remove(key);
return true;
} | java | {
"resource": ""
} |
q7742 | MapExtensions.operator_remove | train | public static <K, V> void operator_remove(Map<K, V> map, Iterable<? super K> keysToRemove) {
for (final Object key : keysToRemove) {
map.remove(key);
}
} | java | {
"resource": ""
} |
q7743 | MapExtensions.operator_minus | train | @Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {
return Maps.filterEntries(left, new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
return !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());
}
});
} | java | {
"resource": ""
} |
q7744 | MapExtensions.operator_minus | train | @Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) {
return Maps.filterKeys(map, new Predicate<K>() {
@Override
public boolean apply(K input) {
return !Objects.equal(input, key);
}
});
} | java | {
"resource": ""
} |
q7745 | MapExtensions.operator_minus | train | @Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) {
return Maps.filterEntries(left, new Predicate<Entry<K, V>>() {
@Override
public boolean apply(Entry<K, V> input) {
final V value = right.get(input.getKey());
if (value == null) {
return input.getValue() == null && right.containsKey(input.getKey());
}
return !Objects.equal(input.getValue(), value);
}
});
} | java | {
"resource": ""
} |
q7746 | MapExtensions.operator_minus | train | @Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {
return Maps.filterKeys(map, new Predicate<K>() {
@Override
public boolean apply(K input) {
return !Iterables.contains(keys, input);
}
});
} | java | {
"resource": ""
} |
q7747 | MapExtensions.union | train | @Pure
@Inline(value = "(new $3<$5, $6>($1, $2))", imported = UnmodifiableMergingMapView.class, constantExpression = true)
public static <K, V> Map<K, V> union(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
return new UnmodifiableMergingMapView<K, V>(left, right);
} | java | {
"resource": ""
} |
q7748 | FunctionExtensions.curry | train | @Pure
public static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {
if (function == null)
throw new NullPointerException("function");
return new Function0<RESULT>() {
@Override
public RESULT apply() {
return function.apply(argument);
}
};
} | java | {
"resource": ""
} |
q7749 | FunctionExtensions.curry | train | @Pure
public static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function,
final P1 argument) {
if (function == null)
throw new NullPointerException("function");
return new Function1<P2, RESULT>() {
@Override
public RESULT apply(P2 p) {
return function.apply(argument, p);
}
};
} | java | {
"resource": ""
} |
q7750 | FunctionExtensions.curry | train | @Pure
public static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function,
final P1 argument) {
if (function == null)
throw new NullPointerException("function");
return new Function2<P2, P3, RESULT>() {
@Override
public RESULT apply(P2 p2, P3 p3) {
return function.apply(argument, p2, p3);
}
};
} | java | {
"resource": ""
} |
q7751 | FunctionExtensions.curry | train | @Pure
public static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(
final Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {
if (function == null)
throw new NullPointerException("function");
return new Function3<P2, P3, P4, RESULT>() {
@Override
public RESULT apply(P2 p2, P3 p3, P4 p4) {
return function.apply(argument, p2, p3, p4);
}
};
} | java | {
"resource": ""
} |
q7752 | IterableExtensions.filterNull | train | @Pure
public static <T> Iterable<T> filterNull(Iterable<T> unfiltered) {
return Iterables.filter(unfiltered, Predicates.notNull());
} | java | {
"resource": ""
} |
q7753 | IterableExtensions.sort | train | public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {
List<T> asList = Lists.newArrayList(iterable);
if (iterable instanceof SortedSet<?>) {
if (((SortedSet<T>) iterable).comparator() == null) {
return asList;
}
}
return ListExtensions.sortInplace(asList);
} | java | {
"resource": ""
} |
q7754 | IterableExtensions.sortWith | train | public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {
return ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);
} | java | {
"resource": ""
} |
q7755 | IterableExtensions.sortBy | train | public static <T, C extends Comparable<? super C>> List<T> sortBy(Iterable<T> iterable,
final Functions.Function1<? super T, C> key) {
return ListExtensions.sortInplaceBy(Lists.newArrayList(iterable), key);
} | java | {
"resource": ""
} |
q7756 | Conversions.checkComponentType | train | private static Object checkComponentType(Object array, Class<?> expectedComponentType) {
Class<?> actualComponentType = array.getClass().getComponentType();
if (!expectedComponentType.isAssignableFrom(actualComponentType)) {
throw new ArrayStoreException(
String.format("The expected component type %s is not assignable from the actual type %s",
expectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));
}
return array;
} | java | {
"resource": ""
} |
q7757 | ToStringBuilder.addDeclaredFields | train | @GwtIncompatible("Class.getDeclaredFields")
public ToStringBuilder addDeclaredFields() {
Field[] fields = instance.getClass().getDeclaredFields();
for(Field field : fields) {
addField(field);
}
return this;
} | java | {
"resource": ""
} |
q7758 | ToStringBuilder.addAllFields | train | @GwtIncompatible("Class.getDeclaredFields")
public ToStringBuilder addAllFields() {
List<Field> fields = getAllDeclaredFields(instance.getClass());
for(Field field : fields) {
addField(field);
}
return this;
} | java | {
"resource": ""
} |
q7759 | IteratorExtensions.filterNull | train | @Pure
public static <T> Iterator<T> filterNull(Iterator<T> unfiltered) {
return Iterators.filter(unfiltered, Predicates.notNull());
} | java | {
"resource": ""
} |
q7760 | IteratorExtensions.toList | train | public static <T> List<T> toList(Iterator<? extends T> iterator) {
return Lists.newArrayList(iterator);
} | java | {
"resource": ""
} |
q7761 | IteratorExtensions.toSet | train | public static <T> Set<T> toSet(Iterator<? extends T> iterator) {
return Sets.newLinkedHashSet(toIterable(iterator));
} | java | {
"resource": ""
} |
q7762 | HomekitServer.createBridge | train | public HomekitRoot createBridge(
HomekitAuthInfo authInfo,
String label,
String manufacturer,
String model,
String serialNumber)
throws IOException {
HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);
root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));
return root;
} | java | {
"resource": ""
} |
q7763 | BaseCharacteristic.makeBuilder | train | protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {
CompletableFuture<T> futureValue = getValue();
if (futureValue == null) {
logger.error("Could not retrieve value " + this.getClass().getName());
return null;
}
return futureValue
.exceptionally(
t -> {
logger.error("Could not retrieve value " + this.getClass().getName(), t);
return null;
})
.thenApply(
value -> {
JsonArrayBuilder perms = Json.createArrayBuilder();
if (isWritable) {
perms.add("pw");
}
if (isReadable) {
perms.add("pr");
}
if (isEventable) {
perms.add("ev");
}
JsonObjectBuilder builder =
Json.createObjectBuilder()
.add("iid", instanceId)
.add("type", shortType)
.add("perms", perms.build())
.add("format", format)
.add("ev", false)
.add("description", description);
setJsonValue(builder, value);
return builder;
});
} | java | {
"resource": ""
} |
q7764 | BaseCharacteristic.setJsonValue | train | protected void setJsonValue(JsonObjectBuilder builder, T value) {
// I don't like this - there should really be a way to construct a disconnected JSONValue...
if (value instanceof Boolean) {
builder.add("value", (Boolean) value);
} else if (value instanceof Double) {
builder.add("value", (Double) value);
} else if (value instanceof Integer) {
builder.add("value", (Integer) value);
} else if (value instanceof Long) {
builder.add("value", (Long) value);
} else if (value instanceof BigInteger) {
builder.add("value", (BigInteger) value);
} else if (value instanceof BigDecimal) {
builder.add("value", (BigDecimal) value);
} else if (value == null) {
builder.addNull("value");
} else {
builder.add("value", value.toString());
}
} | java | {
"resource": ""
} |
q7765 | SubscriptionManager.removeAll | train | public void removeAll() {
LOGGER.debug("Removing {} reverse connections from subscription manager", reverse.size());
Iterator<HomekitClientConnection> i = reverse.keySet().iterator();
while (i.hasNext()) {
HomekitClientConnection connection = i.next();
LOGGER.debug("Removing connection {}", connection.hashCode());
removeConnection(connection);
}
LOGGER.debug("Subscription sizes are {} and {}", reverse.size(), subscriptions.size());
} | java | {
"resource": ""
} |
q7766 | HomekitRoot.addAccessory | train | public void addAccessory(HomekitAccessory accessory) {
if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) {
throw new IndexOutOfBoundsException(
"The ID of an accessory used in a bridge must be greater than 1");
}
addAccessorySkipRangeCheck(accessory);
} | java | {
"resource": ""
} |
q7767 | HomekitRoot.removeAccessory | train | public void removeAccessory(HomekitAccessory accessory) {
this.registry.remove(accessory);
logger.info("Removed accessory " + accessory.getLabel());
if (started) {
registry.reset();
webHandler.resetConnections();
}
} | java | {
"resource": ""
} |
q7768 | ThinDownloadManager.add | train | @Override
public int add(DownloadRequest request) throws IllegalArgumentException {
checkReleased("add(...) called on a released ThinDownloadManager.");
if (request == null) {
throw new IllegalArgumentException("DownloadRequest cannot be null");
}
return mRequestQueue.add(request);
} | java | {
"resource": ""
} |
q7769 | DownloadRequest.addCustomHeader | train | public DownloadRequest addCustomHeader(String key, String value) {
mCustomHeader.put(key, value);
return this;
} | java | {
"resource": ""
} |
q7770 | DownloadDispatcher.cleanupDestination | train | private void cleanupDestination(DownloadRequest request, boolean forceClean) {
if (!request.isResumable() || forceClean) {
Log.d("cleanupDestination() deleting " + request.getDestinationURI().getPath());
File destinationFile = new File(request.getDestinationURI().getPath());
if (destinationFile.exists()) {
destinationFile.delete();
}
}
} | java | {
"resource": ""
} |
q7771 | DownloadRequestQueue.add | train | int add(DownloadRequest request) {
int downloadId = getDownloadId();
// Tag the request as belonging to this queue and add it to the set of current requests.
request.setDownloadRequestQueue(this);
synchronized (mCurrentRequests) {
mCurrentRequests.add(request);
}
// Process requests in the order they are added.
request.setDownloadId(downloadId);
mDownloadQueue.add(request);
return downloadId;
} | java | {
"resource": ""
} |
q7772 | DownloadRequestQueue.query | train | int query(int downloadId) {
synchronized (mCurrentRequests) {
for (DownloadRequest request : mCurrentRequests) {
if (request.getDownloadId() == downloadId) {
return request.getDownloadState();
}
}
}
return DownloadManager.STATUS_NOT_FOUND;
} | java | {
"resource": ""
} |
q7773 | DownloadRequestQueue.cancel | train | int cancel(int downloadId) {
synchronized (mCurrentRequests) {
for (DownloadRequest request : mCurrentRequests) {
if (request.getDownloadId() == downloadId) {
request.cancel();
return 1;
}
}
}
return 0;
} | java | {
"resource": ""
} |
q7774 | DownloadRequestQueue.release | train | void release() {
if (mCurrentRequests != null) {
synchronized (mCurrentRequests) {
mCurrentRequests.clear();
mCurrentRequests = null;
}
}
if (mDownloadQueue != null) {
mDownloadQueue = null;
}
if (mDownloadDispatchers != null) {
stop();
for (int i = 0; i < mDownloadDispatchers.length; i++) {
mDownloadDispatchers[i] = null;
}
mDownloadDispatchers = null;
}
} | java | {
"resource": ""
} |
q7775 | DownloadRequestQueue.initialize | train | private void initialize(Handler callbackHandler) {
int processors = Runtime.getRuntime().availableProcessors();
mDownloadDispatchers = new DownloadDispatcher[processors];
mDelivery = new CallBackDelivery(callbackHandler);
} | java | {
"resource": ""
} |
q7776 | DownloadRequestQueue.initialize | train | private void initialize(Handler callbackHandler, int threadPoolSize) {
mDownloadDispatchers = new DownloadDispatcher[threadPoolSize];
mDelivery = new CallBackDelivery(callbackHandler);
} | java | {
"resource": ""
} |
q7777 | DownloadRequestQueue.stop | train | private void stop() {
for (int i = 0; i < mDownloadDispatchers.length; i++) {
if (mDownloadDispatchers[i] != null) {
mDownloadDispatchers[i].quit();
}
}
} | java | {
"resource": ""
} |
q7778 | Field.getValueAsMap | train | @SuppressWarnings("unchecked")
public Map<String, Field> getValueAsMap() {
return (Map<String, Field>) type.convert(getValue(), Type.MAP);
} | java | {
"resource": ""
} |
q7779 | Field.getValueAsList | train | @SuppressWarnings("unchecked")
public List<Field> getValueAsList() {
return (List<Field>) type.convert(getValue(), Type.LIST);
} | java | {
"resource": ""
} |
q7780 | Field.getValueAsListMap | train | @SuppressWarnings("unchecked")
public LinkedHashMap<String, Field> getValueAsListMap() {
return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP);
} | java | {
"resource": ""
} |
q7781 | Field.getAttributeNames | train | public Set<String> getAttributeNames() {
if (attributes == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(attributes.keySet());
}
} | java | {
"resource": ""
} |
q7782 | Field.getAttributes | train | public Map<String, String> getAttributes() {
if (attributes == null) {
return null;
} else {
return Collections.unmodifiableMap(attributes);
}
} | java | {
"resource": ""
} |
q7783 | Utils.formatL | train | public static Object formatL(final String template, final Object... args) {
return new Object() {
@Override
public String toString() {
return format(template, args);
}
};
} | java | {
"resource": ""
} |
q7784 | BaseService.init | train | @Override
public List<ConfigIssue> init(Service.Context context) {
this.context = context;
return init();
} | java | {
"resource": ""
} |
q7785 | DClusterSourceOffsetCommitter.put | train | @Override
public Object put(List<Map.Entry> batch) throws InterruptedException {
if (initializeClusterSource()) {
return clusterSource.put(batch);
}
return null;
} | java | {
"resource": ""
} |
q7786 | ELEval.eval | train | public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException {
Utils.checkNotNull(vars, "vars");
Utils.checkNotNull(el, "expression");
Utils.checkNotNull(returnType, "returnType");
VARIABLES_IN_SCOPE_TL.set(vars);
try {
return evaluate(vars, el, returnType);
} finally {
VARIABLES_IN_SCOPE_TL.set(null);
}
} | java | {
"resource": ""
} |
q7787 | CTInboxMessageContent.getLinkCopyText | train | public String getLinkCopyText(JSONObject jsonObject){
if(jsonObject == null) return "";
try {
JSONObject copyObject = jsonObject.has("copyText") ? jsonObject.getJSONObject("copyText") : null;
if(copyObject != null){
return copyObject.has("text") ? copyObject.getString("text") : "";
}else{
return "";
}
} catch (JSONException e) {
Logger.v("Unable to get Link Text with JSON - "+e.getLocalizedMessage());
return "";
}
} | java | {
"resource": ""
} |
q7788 | CTInboxMessageContent.getLinkUrl | train | public String getLinkUrl(JSONObject jsonObject){
if(jsonObject == null) return null;
try {
JSONObject urlObject = jsonObject.has("url") ? jsonObject.getJSONObject("url") : null;
if(urlObject == null) return null;
JSONObject androidObject = urlObject.has("android") ? urlObject.getJSONObject("android") : null;
if(androidObject != null){
return androidObject.has("text") ? androidObject.getString("text") : "";
}else{
return "";
}
} catch (JSONException e) {
Logger.v("Unable to get Link URL with JSON - "+e.getLocalizedMessage());
return null;
}
} | java | {
"resource": ""
} |
q7789 | CTInboxMessageContent.getLinkColor | train | public String getLinkColor(JSONObject jsonObject){
if(jsonObject == null) return null;
try {
return jsonObject.has("color") ? jsonObject.getString("color") : "";
} catch (JSONException e) {
Logger.v("Unable to get Link Text Color with JSON - "+e.getLocalizedMessage());
return null;
}
} | java | {
"resource": ""
} |
q7790 | CleverTapAPI.onActivityCreated | train | static void onActivityCreated(Activity activity) {
// make sure we have at least the default instance created here.
if (instances == null) {
CleverTapAPI.createInstanceIfAvailable(activity, null);
}
if (instances == null) {
Logger.v("Instances is null in onActivityCreated!");
return;
}
boolean alreadyProcessedByCleverTap = false;
Bundle notification = null;
Uri deepLink = null;
String _accountId = null;
// check for launch deep link
try {
Intent intent = activity.getIntent();
deepLink = intent.getData();
if (deepLink != null) {
Bundle queryArgs = UriHelper.getAllKeyValuePairs(deepLink.toString(), true);
_accountId = queryArgs.getString(Constants.WZRK_ACCT_ID_KEY);
}
} catch (Throwable t) {
// Ignore
}
// check for launch via notification click
try {
notification = activity.getIntent().getExtras();
if (notification != null && !notification.isEmpty()) {
try {
alreadyProcessedByCleverTap = (notification.containsKey(Constants.WZRK_FROM_KEY) && Constants.WZRK_FROM.equals(notification.get(Constants.WZRK_FROM_KEY)));
if (alreadyProcessedByCleverTap){
Logger.v("ActivityLifecycleCallback: Notification Clicked already processed for "+ notification.toString() +", dropping duplicate.");
}
if (notification.containsKey(Constants.WZRK_ACCT_ID_KEY)) {
_accountId = (String) notification.get(Constants.WZRK_ACCT_ID_KEY);
}
} catch (Throwable t) {
// no-op
}
}
} catch (Throwable t) {
// Ignore
}
if (alreadyProcessedByCleverTap && deepLink == null) return;
for (String accountId: CleverTapAPI.instances.keySet()) {
CleverTapAPI instance = CleverTapAPI.instances.get(accountId);
boolean shouldProcess = false;
if (instance != null) {
shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);
}
if (shouldProcess) {
if (notification != null && !notification.isEmpty() && notification.containsKey(Constants.NOTIFICATION_TAG)) {
instance.pushNotificationClickedEvent(notification);
}
if (deepLink != null) {
try {
instance.pushDeepLink(deepLink);
} catch (Throwable t) {
// no-op
}
}
break;
}
}
} | java | {
"resource": ""
} |
q7791 | CleverTapAPI.handleNotificationClicked | train | static void handleNotificationClicked(Context context,Bundle notification) {
if (notification == null) return;
String _accountId = null;
try {
_accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);
} catch (Throwable t) {
// no-op
}
if (instances == null) {
CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);
if (instance != null) {
instance.pushNotificationClickedEvent(notification);
}
return;
}
for (String accountId: instances.keySet()) {
CleverTapAPI instance = CleverTapAPI.instances.get(accountId);
boolean shouldProcess = false;
if (instance != null) {
shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);
}
if (shouldProcess) {
instance.pushNotificationClickedEvent(notification);
break;
}
}
} | java | {
"resource": ""
} |
q7792 | CleverTapAPI.getInstance | train | public static @Nullable CleverTapAPI getInstance(Context context) throws CleverTapMetaDataNotFoundException, CleverTapPermissionsNotSatisfied {
// For Google Play Store/Android Studio tracking
sdkVersion = BuildConfig.SDK_VERSION_STRING;
return getDefaultInstance(context);
} | java | {
"resource": ""
} |
q7793 | CleverTapAPI.getDefaultInstance | train | @SuppressWarnings("WeakerAccess")
public static @Nullable CleverTapAPI getDefaultInstance(Context context) {
// For Google Play Store/Android Studio tracking
sdkVersion = BuildConfig.SDK_VERSION_STRING;
if (defaultConfig == null) {
ManifestInfo manifest = ManifestInfo.getInstance(context);
String accountId = manifest.getAccountId();
String accountToken = manifest.getAcountToken();
String accountRegion = manifest.getAccountRegion();
if(accountId == null || accountToken == null) {
Logger.i("Account ID or Account token is missing from AndroidManifest.xml, unable to create default instance");
return null;
}
if (accountRegion == null) {
Logger.i("Account Region not specified in the AndroidManifest - using default region");
}
defaultConfig = CleverTapInstanceConfig.createDefaultInstance(context, accountId, accountToken, accountRegion);
defaultConfig.setDebugLevel(getDebugLevel());
}
return instanceWithConfig(context, defaultConfig);
} | java | {
"resource": ""
} |
q7794 | CleverTapAPI.destroySession | train | private void destroySession() {
currentSessionId = 0;
setAppLaunchPushed(false);
getConfigLogger().verbose(getAccountId(),"Session destroyed; Session ID is now 0");
clearSource();
clearMedium();
clearCampaign();
clearWzrkParams();
} | java | {
"resource": ""
} |
q7795 | CleverTapAPI.FCMGetFreshToken | train | private String FCMGetFreshToken(final String senderID) {
String token = null;
try {
if(senderID != null){
getConfigLogger().verbose(getAccountId(), "FcmManager: Requesting a FCM token with Sender Id - "+senderID);
token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);
}else {
getConfigLogger().verbose(getAccountId(), "FcmManager: Requesting a FCM token");
token = FirebaseInstanceId.getInstance().getToken();
}
getConfigLogger().info(getAccountId(),"FCM token: "+token);
} catch (Throwable t) {
getConfigLogger().verbose(getAccountId(), "FcmManager: Error requesting FCM token", t);
}
return token;
} | java | {
"resource": ""
} |
q7796 | CleverTapAPI.GCMGetFreshToken | train | private String GCMGetFreshToken(final String senderID) {
getConfigLogger().verbose(getAccountId(), "GcmManager: Requesting a GCM token for Sender ID - " + senderID);
String token = null;
try {
token = InstanceID.getInstance(context)
.getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
getConfigLogger().info(getAccountId(), "GCM token : " + token);
} catch (Throwable t) {
getConfigLogger().verbose(getAccountId(), "GcmManager: Error requesting GCM token", t);
}
return token;
} | java | {
"resource": ""
} |
q7797 | CleverTapAPI.setOffline | train | @SuppressWarnings({"unused", "WeakerAccess"})
public void setOffline(boolean value){
offline = value;
if (offline) {
getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to offline, won't send events queue");
} else {
getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to online, sending events queue");
flush();
}
} | java | {
"resource": ""
} |
q7798 | CleverTapAPI.enableDeviceNetworkInfoReporting | train | @SuppressWarnings({"unused", "WeakerAccess"})
public void enableDeviceNetworkInfoReporting(boolean value){
enableNetworkInfoReporting = value;
StorageHelper.putBoolean(context,storageKeyWithSuffix(Constants.NETWORK_INFO),enableNetworkInfoReporting);
getConfigLogger().verbose(getAccountId(), "Device Network Information reporting set to " + enableNetworkInfoReporting);
} | java | {
"resource": ""
} |
q7799 | CleverTapAPI.getDevicePushToken | train | @SuppressWarnings("unused")
public String getDevicePushToken(final PushType type) {
switch (type) {
case GCM:
return getCachedGCMToken();
case FCM:
return getCachedFCMToken();
default:
return null;
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.