function_name
stringlengths 1
57
| function_code
stringlengths 20
4.99k
| documentation
stringlengths 50
2k
| language
stringclasses 5
values | file_path
stringlengths 8
166
| line_number
int32 4
16.7k
| parameters
listlengths 0
20
| return_type
stringlengths 0
131
| has_type_hints
bool 2
classes | complexity
int32 1
51
| quality_score
float32 6
9.68
| repo_name
stringclasses 34
values | repo_stars
int32 2.9k
242k
| docstring_style
stringclasses 7
values | is_async
bool 2
classes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
newLinkedHashSet
|
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<>((Collection<? extends E>) elements);
}
LinkedHashSet<E> set = new LinkedHashSet<>();
Iterables.addAll(set, elements);
return set;
}
|
Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order.
<p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
ImmutableSet#copyOf(Iterable)} instead.
<p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method.
Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of <a
href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
syntax</a>.
<p>Overall, this method is not very useful and will likely be deprecated in the future.
@param elements the elements that the set should contain, in order
@return a new {@code LinkedHashSet} containing those elements (minus duplicates)
|
java
|
android/guava/src/com/google/common/collect/Sets.java
| 337
|
[
"elements"
] | true
| 2
| 7.44
|
google/guava
| 51,352
|
javadoc
| false
|
|
containsOnly
|
public static boolean containsOnly(final CharSequence cs, final char... valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
|
Tests if the CharSequence contains only certain characters.
<p>
A {@code null} CharSequence will return {@code false}. A {@code null} valid character array will return {@code false}. An empty CharSequence (length()=0)
always returns {@code true}.
</p>
<pre>
StringUtils.containsOnly(null, *) = false
StringUtils.containsOnly(*, null) = false
StringUtils.containsOnly("", *) = true
StringUtils.containsOnly("ab", '') = false
StringUtils.containsOnly("abab", 'abc') = true
StringUtils.containsOnly("ab1", 'abc') = false
StringUtils.containsOnly("abz", 'abc') = false
</pre>
@param cs the String to check, may be null.
@param valid an array of valid chars, may be null.
@return true if it only contains valid chars and is non-null.
@since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 1,291
|
[
"cs"
] | true
| 5
| 7.92
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
split
|
public static String[] split(final String str) {
return split(str, null, -1);
}
|
Splits the provided text into an array, using whitespace as the separator. Whitespace is defined by {@link Character#isWhitespace(char)}.
<p>
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the
StrTokenizer class.
</p>
<p>
A {@code null} input String returns {@code null}.
</p>
<pre>
StringUtils.split(null) = null
StringUtils.split("") = []
StringUtils.split("abc def") = ["abc", "def"]
StringUtils.split("abc def") = ["abc", "def"]
StringUtils.split(" abc ") = ["abc"]
</pre>
@param str the String to parse, may be null.
@return an array of parsed Strings, {@code null} if null String input.
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 7,034
|
[
"str"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
renamer
|
def renamer(x, suffix: str | None):
"""
Rename the left and right indices.
If there is overlap, and suffix is not None, add
suffix, otherwise, leave it as-is.
Parameters
----------
x : original column name
suffix : str or None
Returns
-------
x : renamed column name
"""
if x in to_rename and suffix is not None:
return f"{x}{suffix}"
return x
|
Rename the left and right indices.
If there is overlap, and suffix is not None, add
suffix, otherwise, leave it as-is.
Parameters
----------
x : original column name
suffix : str or None
Returns
-------
x : renamed column name
|
python
|
pandas/core/reshape/merge.py
| 3,092
|
[
"x",
"suffix"
] | true
| 3
| 7.04
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
copyTo
|
@CanIgnoreReturnValue
public long copyTo(Appendable appendable) throws IOException {
checkNotNull(appendable);
Closer closer = Closer.create();
try {
Reader reader = closer.register(openStream());
return CharStreams.copy(reader, appendable);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
|
Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}).
Does not close {@code appendable} if it is {@code Closeable}.
@return the number of characters copied
@throws IOException if an I/O error occurs while reading from this source or writing to {@code
appendable}
|
java
|
android/guava/src/com/google/common/io/CharSource.java
| 249
|
[
"appendable"
] | true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
emplace_iterator_base
|
emplace_iterator_base(emplace_iterator_base&&) noexcept = default;
|
Special output operator for packed arguments. Unpacks args and performs
variadic call to container's emplace function.
|
cpp
|
folly/container/Iterator.h
| 380
|
[] | true
| 2
| 6.32
|
facebook/folly
| 30,157
|
doxygen
| false
|
|
create_auto_ml_job
|
def create_auto_ml_job(
self,
job_name: str,
s3_input: str,
target_attribute: str,
s3_output: str,
role_arn: str,
compressed_input: bool = False,
time_limit: int | None = None,
autodeploy_endpoint_name: str | None = None,
extras: dict | None = None,
wait_for_completion: bool = True,
check_interval: int = 30,
) -> dict | None:
"""
Create an auto ML job to predict the given column.
The learning input is based on data provided through S3 , and the output
is written to the specified S3 location.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.create_auto_ml_job`
:param job_name: Name of the job to create, needs to be unique within the account.
:param s3_input: The S3 location (folder or file) where to fetch the data.
By default, it expects csv with headers.
:param target_attribute: The name of the column containing the values to predict.
:param s3_output: The S3 folder where to write the model artifacts. Must be 128 characters or fewer.
:param role_arn: The ARN or the IAM role to use when interacting with S3.
Must have read access to the input, and write access to the output folder.
:param compressed_input: Set to True if the input is gzipped.
:param time_limit: The maximum amount of time in seconds to spend training the model(s).
:param autodeploy_endpoint_name: If specified, the best model will be deployed to an endpoint with
that name. No deployment made otherwise.
:param extras: Use this dictionary to set any variable input variable for job creation that is not
offered through the parameters of this function. The format is described in:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_auto_ml_job
:param wait_for_completion: Whether to wait for the job to finish before returning. Defaults to True.
:param check_interval: Interval in seconds between 2 status checks when waiting for completion.
:returns: Only if waiting for completion, a dictionary detailing the best model. The structure is that
of the "BestCandidate" key in:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.describe_auto_ml_job
"""
input_data = [
{
"DataSource": {"S3DataSource": {"S3DataType": "S3Prefix", "S3Uri": s3_input}},
"TargetAttributeName": target_attribute,
},
]
params_dict = {
"AutoMLJobName": job_name,
"InputDataConfig": input_data,
"OutputDataConfig": {"S3OutputPath": s3_output},
"RoleArn": role_arn,
}
if compressed_input:
input_data[0]["CompressionType"] = "Gzip"
if time_limit:
params_dict.update(
{"AutoMLJobConfig": {"CompletionCriteria": {"MaxAutoMLJobRuntimeInSeconds": time_limit}}}
)
if autodeploy_endpoint_name:
params_dict.update({"ModelDeployConfig": {"EndpointName": autodeploy_endpoint_name}})
if extras:
params_dict.update(extras)
# returns the job ARN, but we don't need it because we access it by its name
self.conn.create_auto_ml_job(**params_dict)
if wait_for_completion:
res = self.check_status(
job_name,
"AutoMLJobStatus",
# cannot pass the function directly because the parameter needs to be named
self._describe_auto_ml_job,
check_interval,
)
if "BestCandidate" in res:
return res["BestCandidate"]
return None
|
Create an auto ML job to predict the given column.
The learning input is based on data provided through S3 , and the output
is written to the specified S3 location.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.create_auto_ml_job`
:param job_name: Name of the job to create, needs to be unique within the account.
:param s3_input: The S3 location (folder or file) where to fetch the data.
By default, it expects csv with headers.
:param target_attribute: The name of the column containing the values to predict.
:param s3_output: The S3 folder where to write the model artifacts. Must be 128 characters or fewer.
:param role_arn: The ARN or the IAM role to use when interacting with S3.
Must have read access to the input, and write access to the output folder.
:param compressed_input: Set to True if the input is gzipped.
:param time_limit: The maximum amount of time in seconds to spend training the model(s).
:param autodeploy_endpoint_name: If specified, the best model will be deployed to an endpoint with
that name. No deployment made otherwise.
:param extras: Use this dictionary to set any variable input variable for job creation that is not
offered through the parameters of this function. The format is described in:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_auto_ml_job
:param wait_for_completion: Whether to wait for the job to finish before returning. Defaults to True.
:param check_interval: Interval in seconds between 2 status checks when waiting for completion.
:returns: Only if waiting for completion, a dictionary detailing the best model. The structure is that
of the "BestCandidate" key in:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.describe_auto_ml_job
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 1,227
|
[
"self",
"job_name",
"s3_input",
"target_attribute",
"s3_output",
"role_arn",
"compressed_input",
"time_limit",
"autodeploy_endpoint_name",
"extras",
"wait_for_completion",
"check_interval"
] |
dict | None
| true
| 7
| 7.68
|
apache/airflow
| 43,597
|
sphinx
| false
|
resolveArgumentValues
|
private ValueHolder[] resolveArgumentValues(RegisteredBean registeredBean, Executable executable) {
Parameter[] parameters = executable.getParameters();
ValueHolder[] resolved = new ValueHolder[parameters.length];
RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition();
if (beanDefinition.hasConstructorArgumentValues() &&
registeredBean.getBeanFactory() instanceof AbstractAutowireCapableBeanFactory beanFactory) {
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(
beanFactory, registeredBean.getBeanName(), beanDefinition, beanFactory.getTypeConverter());
ConstructorArgumentValues values = resolveConstructorArguments(
valueResolver, beanDefinition.getConstructorArgumentValues());
Set<ValueHolder> usedValueHolders = CollectionUtils.newHashSet(parameters.length);
for (int i = 0; i < parameters.length; i++) {
Class<?> parameterType = parameters[i].getType();
String parameterName = (parameters[i].isNamePresent() ? parameters[i].getName() : null);
ValueHolder valueHolder = values.getArgumentValue(
i, parameterType, parameterName, usedValueHolders);
if (valueHolder != null) {
resolved[i] = valueHolder;
usedValueHolders.add(valueHolder);
}
}
}
return resolved;
}
|
Resolve arguments for the specified registered bean.
@param registeredBean the registered bean
@return the resolved constructor or factory method arguments
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java
| 280
|
[
"registeredBean",
"executable"
] | true
| 6
| 7.28
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
assignmentId
|
synchronized int assignmentId() {
return assignmentId;
}
|
Monotonically increasing id which is incremented after every assignment change. This can
be used to check when an assignment has changed.
@return The current assignment Id
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
| 175
|
[] | true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
fit
|
def fit(self, X, y=None):
"""Fit the shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Returns the instance itself.
"""
X = validate_data(self, X)
# Not calling the parent object to fit, to avoid a potential
# matrix inversion when setting the precision
if self.assume_centered:
self.location_ = np.zeros(X.shape[1])
else:
self.location_ = X.mean(0)
covariance = empirical_covariance(X, assume_centered=self.assume_centered)
covariance = shrunk_covariance(covariance, self.shrinkage)
self._set_covariance(covariance)
return self
|
Fit the shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Returns the instance itself.
|
python
|
sklearn/covariance/_shrunk_covariance.py
| 255
|
[
"self",
"X",
"y"
] | false
| 3
| 6.08
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
hasLowerCase
|
private boolean hasLowerCase() {
for (char c : chars) {
if (Ascii.isLowerCase(c)) {
return true;
}
}
return false;
}
|
Returns an equivalent {@code Alphabet} except it ignores case.
|
java
|
android/guava/src/com/google/common/io/BaseEncoding.java
| 548
|
[] | true
| 2
| 6.4
|
google/guava
| 51,352
|
javadoc
| false
|
|
printBanner
|
private @Nullable Banner printBanner(ConfigurableEnvironment environment) {
if (this.properties.getBannerMode(environment) == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
: new DefaultResourceLoader(null);
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
if (this.properties.getBannerMode(environment) == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
|
Bind the environment to the {@link ApplicationProperties}.
@param environment the environment to bind
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
| 559
|
[
"environment"
] |
Banner
| true
| 4
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
destroy
|
@Override
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
if (this.invokeDisposableBean) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
}
try {
((DisposableBean) this.bean).destroy();
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
if (logger.isDebugEnabled()) {
// Log at warn level like below but add the exception stacktrace only with debug level
logger.warn(msg, ex);
}
else {
logger.warn(msg + ": " + ex);
}
}
}
}
if (this.invokeAutoCloseable) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking close() on bean with name '" + this.beanName + "'");
}
try {
((AutoCloseable) this.bean).close();
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
String msg = "Invocation of close method failed on bean with name '" + this.beanName + "'";
if (logger.isDebugEnabled()) {
// Log at warn level like below but add the exception stacktrace only with debug level
logger.warn(msg, ex);
}
else {
logger.warn(msg + ": " + ex);
}
}
}
}
else if (this.destroyMethods != null) {
for (Method destroyMethod : this.destroyMethods) {
invokeCustomDestroyMethod(destroyMethod);
}
}
else if (this.destroyMethodNames != null) {
for (String destroyMethodName : this.destroyMethodNames) {
Method destroyMethod = determineDestroyMethod(destroyMethodName);
if (destroyMethod != null) {
destroyMethod = ClassUtils.getPubliclyAccessibleMethodIfPossible(destroyMethod, this.bean.getClass());
invokeCustomDestroyMethod(destroyMethod);
}
}
}
}
|
Create a new DisposableBeanAdapter for the given bean.
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java
| 196
|
[] |
void
| true
| 15
| 6.8
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
isHttpOrHttpsPrefixed
|
function isHttpOrHttpsPrefixed (value) {
return (
value != null &&
value[0] === 'h' &&
value[1] === 't' &&
value[2] === 't' &&
value[3] === 'p' &&
(
value[4] === ':' ||
(
value[4] === 's' &&
value[5] === ':'
)
)
)
}
|
Check if the value is a valid http or https prefixed string.
@param {string} value
@returns {boolean}
|
javascript
|
deps/undici/src/lib/core/util.js
| 154
|
[
"value"
] | false
| 8
| 6.24
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
maybeDrainPendingCalls
|
private long maybeDrainPendingCalls(long now) {
long pollTimeout = Long.MAX_VALUE;
log.trace("Trying to choose nodes for {} at {}", pendingCalls, now);
List<Call> toRemove = new ArrayList<>();
// Using pendingCalls.size() to get the list size before the for-loop to avoid infinite loop.
// If call.fail keeps adding the call to pendingCalls,
// the loop like for (int i = 0; i < pendingCalls.size(); i++) can't stop.
int pendingSize = pendingCalls.size();
// pendingCalls could be modified in this loop,
// hence using for-loop instead of iterator to avoid ConcurrentModificationException.
for (int i = 0; i < pendingSize; i++) {
Call call = pendingCalls.get(i);
// If the call is being retried, await the proper backoff before finding the node
if (now < call.nextAllowedTryMs) {
pollTimeout = Math.min(pollTimeout, call.nextAllowedTryMs - now);
} else if (maybeDrainPendingCall(call, now)) {
toRemove.add(call);
}
}
// Use remove instead of removeAll to avoid delete all matched elements
for (Call call : toRemove) {
pendingCalls.remove(call);
}
return pollTimeout;
}
|
Choose nodes for the calls in the pendingCalls list.
@param now The current time in milliseconds.
@return The minimum time until a call is ready to be retried if any of the pending
calls are backing off after a failure
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
| 1,181
|
[
"now"
] | true
| 4
| 8.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
getTypeDependencyPackageName
|
function getTypeDependencyPackageName(npmPackage: string) {
if (npmPackage.startsWith('@')) {
const [scope, name] = npmPackage.split('/')
return `@types/${scope.slice(1)}__${name}`
} else {
return `@types/${npmPackage}`
}
}
|
Automatically get the type dependency package name, following the
DefinitelyTyped naming conventions.
@param npmPackage
@returns
|
typescript
|
helpers/compile/plugins/tscPlugin.ts
| 119
|
[
"npmPackage"
] | false
| 3
| 6.48
|
prisma/prisma
| 44,834
|
jsdoc
| false
|
|
deleteIndex
|
private void deleteIndex(ProjectId projectId, DeleteIndexRequest deleteIndexRequest, String reason, ActionListener<Void> listener) {
assert deleteIndexRequest.indices() != null && deleteIndexRequest.indices().length == 1
: "Data stream lifecycle deletes one index at a time";
// "saving" the index name here so we don't capture the entire request
String targetIndex = deleteIndexRequest.indices()[0];
logger.trace("Data stream lifecycle issues request to delete index [{}]", targetIndex);
client.projectClient(projectId).admin().indices().delete(deleteIndexRequest, new ActionListener<>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
if (acknowledgedResponse.isAcknowledged()) {
logger.info("Data stream lifecycle successfully deleted index [{}] due to {}", targetIndex, reason);
} else {
logger.trace(
"The delete request for index [{}] was not acknowledged. Data stream lifecycle service will retry on the"
+ " next run if the index still exists",
targetIndex
);
}
listener.onResponse(null);
}
@Override
public void onFailure(Exception e) {
if (e instanceof IndexNotFoundException) {
logger.trace("Data stream lifecycle did not delete index [{}] as it was already deleted", targetIndex);
// index was already deleted, treat this as a success
errorStore.clearRecordedError(projectId, targetIndex);
listener.onResponse(null);
return;
}
if (e instanceof SnapshotInProgressException) {
logger.info(
"Data stream lifecycle was unable to delete index [{}] because it's currently being snapshot. Retrying on "
+ "the next data stream lifecycle run",
targetIndex
);
}
listener.onFailure(e);
}
});
}
|
This method sends requests to delete any indices in the datastream that exceed its retention policy. It returns the set of indices
it has sent delete requests for.
@param project The project metadata from which to get index metadata
@param dataStream The data stream
@param indicesToExcludeForRemainingRun Indices to exclude from retention even if it would be time for them to be deleted
@return The set of indices that delete requests have been sent for
|
java
|
modules/data-streams/src/main/java/org/elasticsearch/datastreams/lifecycle/DataStreamLifecycleService.java
| 1,265
|
[
"projectId",
"deleteIndexRequest",
"reason",
"listener"
] |
void
| true
| 5
| 7.92
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
uniqueIndex
|
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
public final <K> ImmutableMap<K, @NonNull E> uniqueIndex(Function<? super E, K> keyFunction) {
return Maps.uniqueIndex((Iterable<@NonNull E>) getDelegate(), keyFunction);
}
|
Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed
by keys derived from those values. In other words, each input value produces an entry in the
map whose key is the result of applying {@code keyFunction} to that value. These entries appear
in the same order as they appeared in this fluent iterable. Example usage:
{@snippet :
Color red = new Color("red", 255, 0, 0);
...
FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue));
Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction());
assertThat(colorForName).containsEntry("red", red);
}
<p>If your index may associate multiple values with each key, use {@link #index(Function)
index}.
<p><b>{@code Stream} equivalent:</b> {@code
stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}.
@param keyFunction the function used to produce the key for each value
@return a map mapping the result of evaluating the function {@code keyFunction} on each value
in this fluent iterable to that value
@throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
value in this fluent iterable
@throws NullPointerException if any element of this iterable is {@code null}, or if {@code
keyFunction} produces {@code null} for any key
@since 14.0
|
java
|
android/guava/src/com/google/common/collect/FluentIterable.java
| 768
|
[
"keyFunction"
] | true
| 1
| 6.16
|
google/guava
| 51,352
|
javadoc
| false
|
|
of
|
public static <L, R> Pair<L, R> of(final Map.Entry<L, R> pair) {
return ImmutablePair.of(pair);
}
|
Creates an immutable pair from a map entry.
@param <L> the left element type.
@param <R> the right element type.
@param pair the map entry.
@return an immutable pair formed from the map entry.
@since 3.10
|
java
|
src/main/java/org/apache/commons/lang3/tuple/Pair.java
| 92
|
[
"pair"
] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
describeShareGroups
|
DescribeShareGroupsResult describeShareGroups(Collection<String> groupIds,
DescribeShareGroupsOptions options);
|
Describe some share groups in the cluster.
@param groupIds The IDs of the groups to describe.
@param options The options to use when describing the groups.
@return The DescribeShareGroupsResult.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 1,929
|
[
"groupIds",
"options"
] |
DescribeShareGroupsResult
| true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
isValidReferencePosition
|
function isValidReferencePosition(node: Node, searchSymbolName: string): boolean {
// Compare the length so we filter out strict superstrings of the symbol we are looking for
switch (node.kind) {
case SyntaxKind.PrivateIdentifier:
if (isJSDocMemberName(node.parent)) {
return true;
}
// falls through I guess
case SyntaxKind.Identifier:
return (node as PrivateIdentifier | Identifier).text.length === searchSymbolName.length;
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.StringLiteral: {
const str = node as StringLiteralLike;
return str.text.length === searchSymbolName.length && (
isLiteralNameOfPropertyDeclarationOrIndexAccess(str) ||
isNameOfModuleDeclaration(node) ||
isExpressionOfExternalModuleImportEqualsDeclaration(node) ||
(isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) ||
isImportOrExportSpecifier(node.parent)
);
}
case SyntaxKind.NumericLiteral:
return isLiteralNameOfPropertyDeclarationOrIndexAccess(node as NumericLiteral) && (node as NumericLiteral).text.length === searchSymbolName.length;
case SyntaxKind.DefaultKeyword:
return "default".length === searchSymbolName.length;
default:
return false;
}
}
|
Used as a quick check for whether a symbol is used at all in a file (besides its definition).
|
typescript
|
src/services/findAllReferences.ts
| 1,828
|
[
"node",
"searchSymbolName"
] | true
| 10
| 6
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
_validate_date_like_dtype
|
def _validate_date_like_dtype(dtype) -> None:
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The dtype is an illegal date-like dtype (e.g. the
frequency provided is too specific)
"""
try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
raise TypeError(e) from e
if typ not in ["generic", "ns"]:
raise ValueError(
f"{dtype.name!r} is too specific of a frequency, "
f"try passing {dtype.type.__name__!r}"
)
|
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The dtype is an illegal date-like dtype (e.g. the
frequency provided is too specific)
|
python
|
pandas/core/dtypes/common.py
| 1,770
|
[
"dtype"
] |
None
| true
| 2
| 6.88
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
count
|
def count(self) -> int:
"""
Get the number of input nodes.
Returns:
The number of input nodes
"""
return len(self._input_nodes)
|
Get the number of input nodes.
Returns:
The number of input nodes
|
python
|
torch/_inductor/kernel_inputs.py
| 65
|
[
"self"
] |
int
| true
| 1
| 6.56
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
_astype_nansafe
|
def _astype_nansafe(
arr: np.ndarray, dtype: DtypeObj, copy: bool = True, skipna: bool = False
) -> ArrayLike:
"""
Cast the elements of an array to a given dtype a nan-safe manner.
Parameters
----------
arr : ndarray
dtype : np.dtype or ExtensionDtype
copy : bool, default True
If False, a view will be attempted but may fail, if
e.g. the item sizes don't align.
skipna: bool, default False
Whether or not we should skip NaN when casting as a string-type.
Raises
------
ValueError
The dtype was a datetime64/timedelta64 dtype, but it had no unit.
"""
# dispatch on extension dtype if needed
if isinstance(dtype, ExtensionDtype):
return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
elif not isinstance(dtype, np.dtype): # pragma: no cover
raise ValueError("dtype must be np.dtype or ExtensionDtype")
if arr.dtype.kind in "mM":
from pandas.core.construction import ensure_wrapped_if_datetimelike
arr = ensure_wrapped_if_datetimelike(arr)
res = arr.astype(dtype, copy=copy)
return np.asarray(res)
if issubclass(dtype.type, str):
shape = arr.shape
if arr.ndim > 1:
arr = arr.ravel()
return lib.ensure_string_array(
arr, skipna=skipna, convert_na_value=False
).reshape(shape)
elif np.issubdtype(arr.dtype, np.floating) and dtype.kind in "iu":
return _astype_float_to_int_nansafe(arr, dtype, copy)
elif arr.dtype == object:
# if we have a datetime/timedelta array of objects
# then coerce to datetime64[ns] and use DatetimeArray.astype
if lib.is_np_dtype(dtype, "M"):
from pandas.core.arrays import DatetimeArray
dta = DatetimeArray._from_sequence(arr, dtype=dtype)
return dta._ndarray
elif lib.is_np_dtype(dtype, "m"):
from pandas.core.construction import ensure_wrapped_if_datetimelike
# bc we know arr.dtype == object, this is equivalent to
# `np.asarray(to_timedelta(arr))`, but using a lower-level API that
# does not require a circular import.
tdvals = array_to_timedelta64(arr)
tda = ensure_wrapped_if_datetimelike(tdvals)
return tda.astype(dtype, copy=False)._ndarray
if dtype.name in ("datetime64", "timedelta64"):
msg = (
f"The '{dtype.name}' dtype has no unit. Please pass in "
f"'{dtype.name}[ns]' instead."
)
raise ValueError(msg)
if copy or arr.dtype == object or dtype == object:
# Explicit copy, or required since NumPy can't view from / to object.
return arr.astype(dtype, copy=True)
return arr.astype(dtype, copy=copy)
|
Cast the elements of an array to a given dtype a nan-safe manner.
Parameters
----------
arr : ndarray
dtype : np.dtype or ExtensionDtype
copy : bool, default True
If False, a view will be attempted but may fail, if
e.g. the item sizes don't align.
skipna: bool, default False
Whether or not we should skip NaN when casting as a string-type.
Raises
------
ValueError
The dtype was a datetime64/timedelta64 dtype, but it had no unit.
|
python
|
pandas/core/dtypes/astype.py
| 57
|
[
"arr",
"dtype",
"copy",
"skipna"
] |
ArrayLike
| true
| 15
| 6.96
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
insertIndentation
|
function insertIndentation(pos: number, indentation: number, lineAdded: boolean | undefined): void {
const indentationString = getIndentationString(indentation, options);
if (lineAdded) {
// new line is added before the token by the formatting rules
// insert indentation string at the very beginning of the token
recordReplace(pos, 0, indentationString);
}
else {
const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile);
if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
recordReplace(startLinePosition, tokenStart.character, indentationString);
}
}
}
|
Tries to compute the indentation for a list element.
If list element is not in range then
function will pick its actual indentation
so it can be pushed downstream as inherited indentation.
If list element is in the range - its indentation will be equal
to inherited indentation from its predecessors.
|
typescript
|
src/services/formatting/formatting.ts
| 1,151
|
[
"pos",
"indentation",
"lineAdded"
] | true
| 5
| 6
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
findNodesForHydrationOverlay
|
function findNodesForHydrationOverlay(
forest: ComponentTreeNode[],
): {node: Node; status: HydrationStatus}[] {
return forest.flatMap((node) => {
if (node?.hydration?.status) {
// We highlight first level
return {node: node.nativeElement!, status: node.hydration};
}
if (node.children.length) {
return findNodesForHydrationOverlay(node.children);
}
return [];
});
}
|
Returns the first level of hydrated nodes
Note: Mismatched nodes nested in hydrated nodes aren't included
|
typescript
|
devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts
| 141
|
[
"forest"
] | true
| 3
| 6.56
|
angular/angular
| 99,544
|
jsdoc
| false
|
|
enterIf
|
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public boolean enterIf(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!enter(time, unit)) {
return false;
}
boolean satisfied = false;
try {
return satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
}
|
Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
lock, but does not wait for the guard to be satisfied.
@return whether the monitor was entered, which guarantees that the guard is now satisfied
|
java
|
android/guava/src/com/google/common/util/concurrent/Monitor.java
| 716
|
[
"guard",
"time",
"unit"
] | true
| 4
| 7.04
|
google/guava
| 51,352
|
javadoc
| false
|
|
checkRootNode
|
function checkRootNode(node: Node): Diagnostic[] | undefined {
if (isIdentifier(isExpressionStatement(node) ? node.expression : node)) {
return [createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
}
return undefined;
}
|
Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
@param node The unrefined extraction node.
|
typescript
|
src/services/refactors/extractSymbol.ts
| 577
|
[
"node"
] | true
| 3
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
escapeCsv
|
public static final String escapeCsv(final String input) {
return ESCAPE_CSV.translate(input);
}
|
Returns a {@link String} value for a CSV column enclosed in double quotes,
if required.
<p>If the value contains a comma, newline or double quote, then the
String value is returned enclosed in double quotes.</p>
<p>Any double quote characters in the value are escaped with another double quote.</p>
<p>If the value does not contain a comma, newline or double quote, then the
String value is returned unchanged.</p>
see <a href="https://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
<a href="https://datatracker.ietf.org/doc/html/rfc4180">RFC 4180</a>.
@param input the input CSV column String, may be null
@return the input String, enclosed in double quotes if the value contains a comma,
newline or double quote, {@code null} if null string input
@since 2.4
|
java
|
src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
| 431
|
[
"input"
] |
String
| true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
run8Point
|
static int run8Point( const Mat& _m1, const Mat& _m2, Mat& _fmatrix )
{
Point2d m1c(0,0), m2c(0,0);
double t, scale1 = 0, scale2 = 0;
const Point2f* m1 = _m1.ptr<Point2f>();
const Point2f* m2 = _m2.ptr<Point2f>();
CV_Assert( (_m1.cols == 1 || _m1.rows == 1) && _m1.size() == _m2.size());
int i, count = _m1.checkVector(2);
// compute centers and average distances for each of the two point sets
for( i = 0; i < count; i++ )
{
m1c += Point2d(m1[i]);
m2c += Point2d(m2[i]);
}
// calculate the normalizing transformations for each of the point sets:
// after the transformation each set will have the mass center at the coordinate origin
// and the average distance from the origin will be ~sqrt(2).
t = 1./count;
m1c *= t;
m2c *= t;
for( i = 0; i < count; i++ )
{
scale1 += norm(Point2d(m1[i].x - m1c.x, m1[i].y - m1c.y));
scale2 += norm(Point2d(m2[i].x - m2c.x, m2[i].y - m2c.y));
}
scale1 *= t;
scale2 *= t;
if( scale1 < FLT_EPSILON || scale2 < FLT_EPSILON )
return 0;
scale1 = std::sqrt(2.)/scale1;
scale2 = std::sqrt(2.)/scale2;
Matx<double, 9, 9> A;
// form a linear system Ax=0: for each selected pair of points m1 & m2,
// the row of A(=a) represents the coefficients of equation: (m2, 1)'*F*(m1, 1) = 0
// to save computation time, we compute (At*A) instead of A and then solve (At*A)x=0.
for( i = 0; i < count; i++ )
{
double x1 = (m1[i].x - m1c.x)*scale1;
double y1 = (m1[i].y - m1c.y)*scale1;
double x2 = (m2[i].x - m2c.x)*scale2;
double y2 = (m2[i].y - m2c.y)*scale2;
Vec<double, 9> r( x2*x1, x2*y1, x2, y2*x1, y2*y1, y2, x1, y1, 1 );
A += r*r.t();
}
Vec<double, 9> W;
Matx<double, 9, 9> V;
eigen(A, W, V);
for( i = 0; i < 9; i++ )
{
if( fabs(W[i]) < DBL_EPSILON )
break;
}
if( i < 8 )
return 0;
Matx33d F0( V.val + 9*8 ); // take the last column of v as a solution of Af = 0
// make F0 singular (of rank 2) by decomposing it with SVD,
// zeroing the last diagonal element of W and then composing the matrices back.
Vec3d w;
Matx33d U;
Matx33d Vt;
SVD::compute( F0, w, U, Vt);
w[2] = 0.;
F0 = U*Matx33d::diag(w)*Vt;
// apply the transformation that is inverse
// to what we used to normalize the point coordinates
Matx33d T1( scale1, 0, -scale1*m1c.x, 0, scale1, -scale1*m1c.y, 0, 0, 1 );
Matx33d T2( scale2, 0, -scale2*m2c.x, 0, scale2, -scale2*m2c.y, 0, 0, 1 );
F0 = T2.t()*F0*T1;
// make F(3,3) = 1
if( fabs(F0(2,2)) > FLT_EPSILON )
F0 *= 1./F0(2,2);
Mat(F0).copyTo(_fmatrix);
return 1;
}
|
Compute the fundamental matrix using the 8-point algorithm.
\f[
(\mathrm{m2}_i,1)^T \mathrm{fmatrix} (\mathrm{m1}_i,1) = 0
\f]
@param _m1 Contain points in the reference view. Depth CV_32F with 2-channel
1 column or 1-channel 2 columns. It has 8 rows.
@param _m2 Contain points in the other view. Depth CV_32F with 2-channel
1 column or 1-channel 2 columns. It has 8 rows.
@param _fmatrix Output fundamental matrix (or matrices) of type CV_64FC1.
The user is responsible for allocating the memory before calling
this function.
@return 1 on success, 0 on failure.
Note that the computed fundamental matrix is normalized, i.e.,
the last element \f$F_{33}\f$ is 1.
|
cpp
|
modules/calib3d/src/fundam.cpp
| 693
|
[] | true
| 12
| 8.16
|
opencv/opencv
| 85,374
|
doxygen
| false
|
|
describe_training_job
|
def describe_training_job(self, name: str):
"""
Get the training job info associated with the name.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_training_job`
:param name: the name of the training job
:return: A dict contains all the training job info
"""
return self.get_conn().describe_training_job(TrainingJobName=name)
|
Get the training job info associated with the name.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_training_job`
:param name: the name of the training job
:return: A dict contains all the training job info
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 570
|
[
"self",
"name"
] | true
| 1
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
|
matches
|
protected abstract boolean matches(String pattern, int patternIndex);
|
Does the pattern at the given index match the given String?
@param pattern the {@code String} pattern to match
@param patternIndex index of pattern (starting from 0)
@return {@code true} if there is a match, {@code false} otherwise
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java
| 187
|
[
"pattern",
"patternIndex"
] | true
| 1
| 6.48
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
replace
|
public StrBuilder replace(
final StrMatcher matcher, final String replaceStr,
final int startIndex, int endIndex, final int replaceCount) {
endIndex = validateRange(startIndex, endIndex);
return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
}
|
Advanced search and replaces within the builder using a matcher.
<p>
Matchers can be used to perform advanced behavior.
For example you could write a matcher to delete all occurrences
where the character 'a' is followed by a number.
</p>
@param matcher the matcher to use to find the deletion, null causes no action
@param replaceStr the string to replace the match with, null is a delete
@param startIndex the start index, inclusive, must be valid
@param endIndex the end index, exclusive, must be valid except
that if too large it is treated as end of string
@param replaceCount the number of times to replace, -1 for replace all
@return {@code this} instance.
@throws IndexOutOfBoundsException if start index is invalid
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 2,557
|
[
"matcher",
"replaceStr",
"startIndex",
"endIndex",
"replaceCount"
] |
StrBuilder
| true
| 1
| 6.72
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
printStackTrace
|
@Override
public void printStackTrace(PrintStream ps) {
synchronized (ps) {
super.printStackTrace(ps);
if (this.relatedCauses != null) {
for (Throwable relatedCause : this.relatedCauses) {
ps.println("Related cause:");
relatedCause.printStackTrace(ps);
}
}
}
}
|
Return the related causes, if any.
@return the array of related causes, or {@code null} if none
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java
| 169
|
[
"ps"
] |
void
| true
| 2
| 7.04
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
equal
|
public static boolean equal(Path path1, Path path2) throws IOException {
checkNotNull(path1);
checkNotNull(path2);
if (Files.isSameFile(path1, path2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
ByteSource source1 = asByteSource(path1);
ByteSource source2 = asByteSource(path2);
long len1 = source1.sizeIfKnown().or(0L);
long len2 = source2.sizeIfKnown().or(0L);
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return source1.contentEquals(source2);
}
|
Returns true if the files located by the given paths exist, are not directories, and contain
the same bytes.
@throws IOException if an I/O error occurs
@since 22.0
|
java
|
android/guava/src/com/google/common/io/MoreFiles.java
| 366
|
[
"path1",
"path2"
] | true
| 5
| 6
|
google/guava
| 51,352
|
javadoc
| false
|
|
list
|
List<Object> list() throws IOException;
|
Returns an instance of {@link Map} holding parsed map.
Serves as a replacement for the "map", "mapOrdered" and "mapStrings" methods above.
@param mapFactory factory for creating new {@link Map} objects
@param mapValueParser parser for parsing a single map value
@param <T> map value type
@return {@link Map} object
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParser.java
| 104
|
[] | true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
visitIdentifier
|
function visitIdentifier(node: Identifier): Identifier {
if (convertedLoopState) {
if (resolver.isArgumentsLocalBinding(node)) {
return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
}
}
if (node.flags & NodeFlags.IdentifierHasExtendedUnicodeEscape) {
return setOriginalNode(
setTextRange(
factory.createIdentifier(unescapeLeadingUnderscores(node.escapedText)),
node,
),
node,
);
}
return node;
}
|
Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
subtree, propagating specific facts from the subtree.
@param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
@param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
@param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
|
typescript
|
src/compiler/transformers/es2015.ts
| 874
|
[
"node"
] | true
| 5
| 6.24
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
infer_freq
|
def infer_freq(
index: DatetimeIndex | TimedeltaIndex | Series | DatetimeLikeArrayMixin,
) -> str | None:
"""
Infer the most likely frequency given the input index.
This method attempts to deduce the most probable frequency (e.g., 'D' for daily,
'H' for hourly) from a sequence of datetime-like objects. It is particularly useful
when the frequency of a time series is not explicitly set or known but can be
inferred from its values.
Parameters
----------
index : DatetimeIndex, TimedeltaIndex, Series or array-like
If passed a Series will use the values of the series (NOT THE INDEX).
Returns
-------
str or None
None if no discernible frequency.
Raises
------
TypeError
If the index is not datetime-like.
ValueError
If there are fewer than three values.
See Also
--------
date_range : Return a fixed frequency DatetimeIndex.
timedelta_range : Return a fixed frequency TimedeltaIndex with day as the default.
period_range : Return a fixed frequency PeriodIndex.
DatetimeIndex.freq : Return the frequency object if it is set, otherwise None.
Examples
--------
>>> idx = pd.date_range(start="2020/12/01", end="2020/12/30", periods=30)
>>> pd.infer_freq(idx)
'D'
"""
from pandas.core.api import DatetimeIndex
if isinstance(index, ABCSeries):
values = index._values
if isinstance(index.dtype, ArrowDtype):
import pyarrow as pa
if pa.types.is_timestamp(values.dtype.pyarrow_dtype):
# GH#58403
values = values._to_datetimearray()
if not (
lib.is_np_dtype(values.dtype, "mM")
or isinstance(values.dtype, DatetimeTZDtype)
or values.dtype == object
):
raise TypeError(
"cannot infer freq from a non-convertible dtype "
f"on a Series of {index.dtype}"
)
index = values
inferer: _FrequencyInferer
if not hasattr(index, "dtype"):
pass
elif isinstance(index.dtype, PeriodDtype):
raise TypeError(
"PeriodIndex given. Check the `freq` attribute instead of using infer_freq."
)
elif lib.is_np_dtype(index.dtype, "m"):
# Allow TimedeltaIndex and TimedeltaArray
inferer = _TimedeltaFrequencyInferer(index)
return inferer.get_freq()
elif is_numeric_dtype(index.dtype):
raise TypeError(
f"cannot infer freq from a non-convertible index of dtype {index.dtype}"
)
if not isinstance(index, DatetimeIndex):
index = DatetimeIndex(index)
inferer = _FrequencyInferer(index)
return inferer.get_freq()
|
Infer the most likely frequency given the input index.
This method attempts to deduce the most probable frequency (e.g., 'D' for daily,
'H' for hourly) from a sequence of datetime-like objects. It is particularly useful
when the frequency of a time series is not explicitly set or known but can be
inferred from its values.
Parameters
----------
index : DatetimeIndex, TimedeltaIndex, Series or array-like
If passed a Series will use the values of the series (NOT THE INDEX).
Returns
-------
str or None
None if no discernible frequency.
Raises
------
TypeError
If the index is not datetime-like.
ValueError
If there are fewer than three values.
See Also
--------
date_range : Return a fixed frequency DatetimeIndex.
timedelta_range : Return a fixed frequency TimedeltaIndex with day as the default.
period_range : Return a fixed frequency PeriodIndex.
DatetimeIndex.freq : Return the frequency object if it is set, otherwise None.
Examples
--------
>>> idx = pd.date_range(start="2020/12/01", end="2020/12/30", periods=30)
>>> pd.infer_freq(idx)
'D'
|
python
|
pandas/tseries/frequencies.py
| 91
|
[
"index"
] |
str | None
| true
| 12
| 8.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
findThreadById
|
public static Thread findThreadById(final long threadId, final String threadGroupName) {
Objects.requireNonNull(threadGroupName, "threadGroupName");
final Thread thread = findThreadById(threadId);
if (thread != null && thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals(threadGroupName)) {
return thread;
}
return null;
}
|
Finds the active thread with the specified id if it belongs to a thread group with the specified group name.
@param threadId The thread id.
@param threadGroupName The thread group name.
@return The threads which belongs to a thread group with the specified group name and the thread's id match the specified id. {@code null} is returned if
no such thread exists.
@throws NullPointerException if the group name is null.
@throws IllegalArgumentException if the specified id is zero or negative.
@throws SecurityException if the current thread cannot access the system thread group.
@throws SecurityException if the current thread cannot modify thread groups from this thread's thread group up to the system thread group.
|
java
|
src/main/java/org/apache/commons/lang3/ThreadUtils.java
| 203
|
[
"threadId",
"threadGroupName"
] |
Thread
| true
| 4
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
extractBasicBlockInfo
|
void extractBasicBlockInfo(
const BinaryFunctionListType &BinaryFunctions,
std::unordered_map<BinaryBasicBlock *, uint64_t> &BBAddr,
std::unordered_map<BinaryBasicBlock *, uint64_t> &BBSize) {
for (BinaryFunction *BF : BinaryFunctions) {
const BinaryContext &BC = BF->getBinaryContext();
for (BinaryBasicBlock &BB : *BF) {
if (BF->isSimple() || BC.HasRelocations) {
// Use addresses/sizes as in the output binary
BBAddr[&BB] = BB.getOutputAddressRange().first;
BBSize[&BB] = BB.getOutputSize();
} else {
// Output ranges should match the input if the body hasn't changed
BBAddr[&BB] = BB.getInputAddressRange().first + BF->getAddress();
BBSize[&BB] = BB.getOriginalSize();
}
}
}
}
|
Initialize and return a position map for binary basic blocks
|
cpp
|
bolt/lib/Passes/CacheMetrics.cpp
| 32
|
[] | true
| 4
| 6.4
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
possiblyDecryptPKCS1Key
|
private static byte[] possiblyDecryptPKCS1Key(Map<String, String> pemHeaders, String keyContents, Supplier<char[]> passwordSupplier)
throws GeneralSecurityException, IOException {
byte[] keyBytes = Base64.getDecoder().decode(keyContents);
String procType = pemHeaders.get("Proc-Type");
if ("4,ENCRYPTED".equals(procType)) {
// We only handle PEM encryption
String encryptionParameters = pemHeaders.get("DEK-Info");
if (null == encryptionParameters) {
// malformed pem
throw new IOException("Malformed PEM File, DEK-Info header is missing");
}
char[] password = passwordSupplier.get();
if (password == null) {
throw new IOException("cannot read encrypted key without a password");
}
Cipher cipher = getCipherFromParameters(encryptionParameters, password);
byte[] decryptedKeyBytes = cipher.doFinal(keyBytes);
return decryptedKeyBytes;
}
return keyBytes;
}
|
Decrypts the password protected contents using the algorithm and IV that is specified in the PEM Headers of the file
@param pemHeaders The Proc-Type and DEK-Info PEM headers that have been extracted from the key file
@param keyContents The key as a base64 encoded String
@param passwordSupplier A password supplier for the encrypted (password protected) key
@return the decrypted key bytes
@throws GeneralSecurityException if the key can't be decrypted
@throws IOException if the PEM headers are missing or malformed
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java
| 467
|
[
"pemHeaders",
"keyContents",
"passwordSupplier"
] | true
| 4
| 7.12
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
forInRight
|
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
|
This method is like `_.forIn` except that it iterates over properties of
`object` in the opposite order.
@static
@memberOf _
@since 2.0.0
@category Object
@param {Object} object The object to iterate over.
@param {Function} [iteratee=_.identity] The function invoked per iteration.
@returns {Object} Returns `object`.
@see _.forIn
@example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forInRight(new Foo, function(value, key) {
console.log(key);
});
// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
|
javascript
|
lodash.js
| 13,086
|
[
"object",
"iteratee"
] | false
| 2
| 7.52
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
compile
|
def compile(
gm: torch.fx.GraphModule,
example_inputs: list[InputType],
options: Optional[dict[str, Any]] = None,
):
"""
Compile a given FX graph with TorchInductor. This allows compiling
FX graphs captured without using TorchDynamo.
Args:
gm: The FX graph to compile.
example_inputs: List of tensor inputs.
options: Optional dict of config options. See `torch._inductor.config`.
Returns:
Callable with same behavior as gm but faster.
"""
from .compile_fx import compile_fx
return compile_fx(gm, example_inputs, config_patches=options)
|
Compile a given FX graph with TorchInductor. This allows compiling
FX graphs captured without using TorchDynamo.
Args:
gm: The FX graph to compile.
example_inputs: List of tensor inputs.
options: Optional dict of config options. See `torch._inductor.config`.
Returns:
Callable with same behavior as gm but faster.
|
python
|
torch/_inductor/__init__.py
| 33
|
[
"gm",
"example_inputs",
"options"
] | true
| 1
| 6.72
|
pytorch/pytorch
| 96,034
|
google
| false
|
|
visitFunctionExpression
|
function visitFunctionExpression(node: FunctionExpression): Expression {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return factory.createOmittedExpression();
}
const updated = factory.updateFunctionExpression(
node,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
visitFunctionBody(node.body, visitor, context) || factory.createBlock([]),
);
return updated;
}
|
Determines whether to emit an accessor declaration. We should not emit the
declaration if it does not have a body and is abstract.
@param node The declaration node.
|
typescript
|
src/compiler/transformers/ts.ts
| 1,573
|
[
"node"
] | true
| 3
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
newHashMap
|
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
public static <K extends @Nullable Object, V extends @Nullable Object>
HashMap<K, V> newHashMap() {
return new HashMap<>();
}
|
Creates a <i>mutable</i>, empty {@code HashMap} instance.
<p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
<p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead.
<p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
use the {@code HashMap} constructor directly, taking advantage of <a
href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
syntax</a>.
@return a new, empty {@code HashMap}
|
java
|
android/guava/src/com/google/common/collect/Maps.java
| 210
|
[] | true
| 1
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
|
generateBeanDefinitionMethod
|
private GeneratedMethod generateBeanDefinitionMethod(GenerationContext generationContext,
ClassName className, GeneratedMethods generatedMethods,
BeanRegistrationCodeFragments codeFragments, Modifier modifier) {
BeanRegistrationCodeGenerator codeGenerator = new BeanRegistrationCodeGenerator(
className, generatedMethods, this.registeredBean, codeFragments);
this.aotContributions.forEach(aotContribution -> aotContribution.applyTo(generationContext, codeGenerator));
CodeWarnings codeWarnings = new CodeWarnings();
codeWarnings.detectDeprecation(this.registeredBean.getBeanType());
return generatedMethods.add("getBeanDefinition", method -> {
method.addJavadoc("Get the $L definition for '$L'.",
(this.registeredBean.isInnerBean() ? "inner-bean" : "bean"),
getName());
method.addModifiers(modifier, Modifier.STATIC);
codeWarnings.suppress(method);
method.returns(BeanDefinition.class);
method.addCode(codeGenerator.generateCode(generationContext));
});
}
|
Return the {@link GeneratedClass} to use for the specified {@code target}.
<p>If the target class is an inner class, a corresponding inner class in
the original structure is created.
@param generationContext the generation context to use
@param target the chosen target class name for the bean definition
@return the generated class to use
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGenerator.java
| 158
|
[
"generationContext",
"className",
"generatedMethods",
"codeFragments",
"modifier"
] |
GeneratedMethod
| true
| 2
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
_pad_simple
|
def _pad_simple(array, pad_width, fill_value=None):
"""
Pad array on all sides with either a single value or undefined values.
Parameters
----------
array : ndarray
Array to grow.
pad_width : sequence of tuple[int, int]
Pad width on both sides for each dimension in `arr`.
fill_value : scalar, optional
If provided the padded area is filled with this value, otherwise
the pad area left undefined.
Returns
-------
padded : ndarray
The padded array with the same dtype as`array`. Its order will default
to C-style if `array` is not F-contiguous.
original_area_slice : tuple
A tuple of slices pointing to the area of the original array.
"""
# Allocate grown array
new_shape = tuple(
left + size + right
for size, (left, right) in zip(array.shape, pad_width)
)
order = 'F' if array.flags.fnc else 'C' # Fortran and not also C-order
padded = np.empty(new_shape, dtype=array.dtype, order=order)
if fill_value is not None:
padded.fill(fill_value)
# Copy old array into correct space
original_area_slice = tuple(
slice(left, left + size)
for size, (left, right) in zip(array.shape, pad_width)
)
padded[original_area_slice] = array
return padded, original_area_slice
|
Pad array on all sides with either a single value or undefined values.
Parameters
----------
array : ndarray
Array to grow.
pad_width : sequence of tuple[int, int]
Pad width on both sides for each dimension in `arr`.
fill_value : scalar, optional
If provided the padded area is filled with this value, otherwise
the pad area left undefined.
Returns
-------
padded : ndarray
The padded array with the same dtype as`array`. Its order will default
to C-style if `array` is not F-contiguous.
original_area_slice : tuple
A tuple of slices pointing to the area of the original array.
|
python
|
numpy/lib/_arraypad_impl.py
| 87
|
[
"array",
"pad_width",
"fill_value"
] | false
| 3
| 6.08
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
ensure_pod_is_valid_after_unpickling
|
def ensure_pod_is_valid_after_unpickling(pod: V1Pod) -> V1Pod | None:
"""
Convert pod to json and back so that pod is safe.
The pod_override in executor_config is a V1Pod object.
Such objects created with one k8s version, when unpickled in
an env with upgraded k8s version, may blow up when
`to_dict` is called, because openapi client code gen calls
getattr on all attrs in openapi_types for each object, and when
new attrs are added to that list, getattr will fail.
Here we re-serialize it to ensure it is not going to blow up.
:meta private:
"""
try:
# if to_dict works, the pod is fine
pod.to_dict()
return pod
except AttributeError:
pass
try:
from kubernetes.client.models.v1_pod import V1Pod
except ImportError:
return None
if not isinstance(pod, V1Pod):
return None
try:
from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator
# now we actually reserialize / deserialize the pod
pod_dict = sanitize_for_serialization(pod)
return PodGenerator.deserialize_model_dict(pod_dict)
except Exception:
return None
|
Convert pod to json and back so that pod is safe.
The pod_override in executor_config is a V1Pod object.
Such objects created with one k8s version, when unpickled in
an env with upgraded k8s version, may blow up when
`to_dict` is called, because openapi client code gen calls
getattr on all attrs in openapi_types for each object, and when
new attrs are added to that list, getattr will fail.
Here we re-serialize it to ensure it is not going to blow up.
:meta private:
|
python
|
airflow-core/src/airflow/utils/sqlalchemy.py
| 208
|
[
"pod"
] |
V1Pod | None
| true
| 2
| 6
|
apache/airflow
| 43,597
|
unknown
| false
|
can_produce
|
def can_produce(self, output_spec: Spec) -> bool:
"""Argsort can produce tensor outputs with integer dtype (long)."""
if not isinstance(output_spec, TensorSpec):
return False
# argsort returns indices, so it must be integer type (long)
return output_spec.dtype == torch.long and len(output_spec.size) > 0
|
Argsort can produce tensor outputs with integer dtype (long).
|
python
|
tools/experimental/torchfuzz/operators/argsort.py
| 23
|
[
"self",
"output_spec"
] |
bool
| true
| 3
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
readCertificates
|
public static List<Certificate> readCertificates(Collection<Path> certPaths) throws CertificateException, IOException {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
List<Certificate> certificates = new ArrayList<>(certPaths.size());
for (Path path : certPaths) {
try (InputStream input = Files.newInputStream(path)) {
final Collection<? extends Certificate> parsed = certFactory.generateCertificates(input);
if (parsed.isEmpty()) {
throw new SslConfigException("failed to parse any certificates from [" + path.toAbsolutePath() + "]");
}
certificates.addAll(parsed);
}
}
return certificates;
}
|
Parses a DER encoded private key and reads its algorithm identifier Object OID.
@param keyBytes the private key raw bytes
@return A string identifier for the key algorithm (RSA, DSA, or EC)
@throws GeneralSecurityException if the algorithm oid that is parsed from ASN.1 is unknown
@throws IOException if the DER encoded key can't be parsed
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java
| 685
|
[
"certPaths"
] | true
| 2
| 7.76
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
_emit_true_scheduling_delay_stats_for_finished_state
|
def _emit_true_scheduling_delay_stats_for_finished_state(self, finished_tis: list[TI]) -> None:
"""
Emit the true scheduling delay stats.
The true scheduling delay stats is defined as the time when the first
task in DAG starts minus the expected DAG run datetime.
This helper method is used in ``update_state`` when the state of the
DAG run is updated to a completed status (either success or failure).
It finds the first started task within the DAG, calculates the run's
expected start time based on the logical date and timetable, and gets
the delay from the difference of these two values.
The emitted data may contain outliers (e.g. when the first task was
cleared, so the second task's start date will be used), but we can get
rid of the outliers on the stats side through dashboards tooling.
Note that the stat will only be emitted for scheduler-triggered DAG runs
(i.e. when ``run_type`` is *SCHEDULED* and ``clear_number`` is equal to 0).
"""
from airflow.models.dag import get_run_data_interval
if self.state == TaskInstanceState.RUNNING:
return
if self.run_type != DagRunType.SCHEDULED:
return
if self.clear_number > 0:
return
if not finished_tis:
return
try:
dag = self.get_dag()
if not dag.timetable.periodic:
# We can't emit this metric if there is no following schedule to calculate from!
return
try:
first_start_date = min(ti.start_date for ti in finished_tis if ti.start_date)
except ValueError: # No start dates at all.
pass
else:
# TODO: Logically, this should be DagRunInfo.run_after, but the
# information is not stored on a DagRun, only before the actual
# execution on DagModel.next_dagrun_create_after. We should add
# a field on DagRun for this instead of relying on the run
# always happening immediately after the data interval.
data_interval_end = get_run_data_interval(dag.timetable, self).end
true_delay = first_start_date - data_interval_end
if true_delay.total_seconds() > 0:
Stats.timing(
f"dagrun.{dag.dag_id}.first_task_scheduling_delay", true_delay, tags=self.stats_tags
)
Stats.timing("dagrun.first_task_scheduling_delay", true_delay, tags=self.stats_tags)
except Exception:
self.log.warning("Failed to record first_task_scheduling_delay metric:", exc_info=True)
|
Emit the true scheduling delay stats.
The true scheduling delay stats is defined as the time when the first
task in DAG starts minus the expected DAG run datetime.
This helper method is used in ``update_state`` when the state of the
DAG run is updated to a completed status (either success or failure).
It finds the first started task within the DAG, calculates the run's
expected start time based on the logical date and timetable, and gets
the delay from the difference of these two values.
The emitted data may contain outliers (e.g. when the first task was
cleared, so the second task's start date will be used), but we can get
rid of the outliers on the stats side through dashboards tooling.
Note that the stat will only be emitted for scheduler-triggered DAG runs
(i.e. when ``run_type`` is *SCHEDULED* and ``clear_number`` is equal to 0).
|
python
|
airflow-core/src/airflow/models/dagrun.py
| 1,619
|
[
"self",
"finished_tis"
] |
None
| true
| 8
| 6
|
apache/airflow
| 43,597
|
unknown
| false
|
_get_timestamp_range_edges
|
def _get_timestamp_range_edges(
first: Timestamp,
last: Timestamp,
freq: BaseOffset,
unit: TimeUnit,
closed: Literal["right", "left"] = "left",
origin: TimeGrouperOrigin = "start_day",
offset: Timedelta | None = None,
) -> tuple[Timestamp, Timestamp]:
"""
Adjust the `first` Timestamp to the preceding Timestamp that resides on
the provided offset. Adjust the `last` Timestamp to the following
Timestamp that resides on the provided offset. Input Timestamps that
already reside on the offset will be adjusted depending on the type of
offset and the `closed` parameter.
Parameters
----------
first : pd.Timestamp
The beginning Timestamp of the range to be adjusted.
last : pd.Timestamp
The ending Timestamp of the range to be adjusted.
freq : pd.DateOffset
The dateoffset to which the Timestamps will be adjusted.
closed : {'right', 'left'}, default "left"
Which side of bin interval is closed.
origin : {'epoch', 'start', 'start_day'} or Timestamp, default 'start_day'
The timestamp on which to adjust the grouping. The timezone of origin must
match the timezone of the index.
If a timestamp is not used, these values are also supported:
- 'epoch': `origin` is 1970-01-01
- 'start': `origin` is the first value of the timeseries
- 'start_day': `origin` is the first day at midnight of the timeseries
offset : pd.Timedelta, default is None
An offset timedelta added to the origin.
Returns
-------
A tuple of length 2, containing the adjusted pd.Timestamp objects.
"""
if isinstance(freq, Tick):
index_tz = first.tz
if isinstance(origin, Timestamp) and (origin.tz is None) != (index_tz is None):
raise ValueError("The origin must have the same timezone as the index.")
if origin == "epoch":
# set the epoch based on the timezone to have similar bins results when
# resampling on the same kind of indexes on different timezones
origin = Timestamp("1970-01-01", tz=index_tz)
first, last = _adjust_dates_anchored(
first,
last,
freq,
closed=closed,
origin=origin,
offset=offset,
unit=unit,
)
else:
first = first.normalize()
last = last.normalize()
if closed == "left":
first = Timestamp(freq.rollback(first))
else:
first = Timestamp(first - freq)
last = Timestamp(last + freq)
return first, last
|
Adjust the `first` Timestamp to the preceding Timestamp that resides on
the provided offset. Adjust the `last` Timestamp to the following
Timestamp that resides on the provided offset. Input Timestamps that
already reside on the offset will be adjusted depending on the type of
offset and the `closed` parameter.
Parameters
----------
first : pd.Timestamp
The beginning Timestamp of the range to be adjusted.
last : pd.Timestamp
The ending Timestamp of the range to be adjusted.
freq : pd.DateOffset
The dateoffset to which the Timestamps will be adjusted.
closed : {'right', 'left'}, default "left"
Which side of bin interval is closed.
origin : {'epoch', 'start', 'start_day'} or Timestamp, default 'start_day'
The timestamp on which to adjust the grouping. The timezone of origin must
match the timezone of the index.
If a timestamp is not used, these values are also supported:
- 'epoch': `origin` is 1970-01-01
- 'start': `origin` is the first value of the timeseries
- 'start_day': `origin` is the first day at midnight of the timeseries
offset : pd.Timedelta, default is None
An offset timedelta added to the origin.
Returns
-------
A tuple of length 2, containing the adjusted pd.Timestamp objects.
|
python
|
pandas/core/resample.py
| 2,841
|
[
"first",
"last",
"freq",
"unit",
"closed",
"origin",
"offset"
] |
tuple[Timestamp, Timestamp]
| true
| 8
| 6.8
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
areNeighborCells
|
public static boolean areNeighborCells(long origin, long destination) {
return HexRing.areNeighbours(origin, destination);
}
|
returns whether or not the provided hexagons border
@param origin the first index
@param destination the second index
@return whether or not the provided hexagons border
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/H3.java
| 438
|
[
"origin",
"destination"
] | true
| 1
| 6.16
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
size
|
@Override
public int size() {
return rowList.size() * columnList.size();
}
|
Associates the value {@code null} with the specified keys, assuming both keys are valid. If
either key is null or isn't among the keys provided during construction, this method has no
effect.
<p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
are valid.
@param rowKey row key of mapping to be erased
@param columnKey column key of mapping to be erased
@return the value previously associated with the keys, or {@code null} if no mapping existed
for the keys
|
java
|
android/guava/src/com/google/common/collect/ArrayTable.java
| 524
|
[] | true
| 1
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
|
toStringBuilder
|
public StringBuilder toStringBuilder() {
return new StringBuilder(size).append(buffer, 0, size);
}
|
Gets a StringBuilder version of the string builder, creating a
new instance each time the method is called.
@return the builder as a StringBuilder
@since 3.2
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 2,994
|
[] |
StringBuilder
| true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
add
|
@CanIgnoreReturnValue
public abstract Builder<E> add(E element);
|
Adds {@code element} to the {@code ImmutableCollection} being built.
<p>Note that each builder class covariantly returns its own type from this method.
@param element the element to add
@return this {@code Builder} instance
@throws NullPointerException if {@code element} is null
|
java
|
android/guava/src/com/google/common/collect/ImmutableCollection.java
| 428
|
[
"element"
] | true
| 1
| 6
|
google/guava
| 51,352
|
javadoc
| false
|
|
isFullEnumerable
|
private static boolean isFullEnumerable(PropertySource<?> source) {
PropertySource<?> rootSource = getRootSource(source);
if (rootSource.getSource() instanceof Map<?, ?> map) {
// Check we're not security restricted
try {
map.size();
}
catch (UnsupportedOperationException ex) {
return false;
}
}
return (source instanceof EnumerablePropertySource);
}
|
Create a new {@link SpringConfigurationPropertySource} for the specified
{@link PropertySource}.
@param source the source Spring {@link PropertySource}
@return a {@link SpringConfigurationPropertySource} or
{@link SpringIterableConfigurationPropertySource} instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java
| 188
|
[
"source"
] | true
| 3
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
add
|
public Fraction add(final Fraction fraction) {
return addSub(fraction, true /* add */);
}
|
Adds the value of this fraction to another, returning the result in reduced form.
The algorithm follows Knuth, 4.5.1.
@param fraction the fraction to add, must not be {@code null}
@return a {@link Fraction} instance with the resulting values
@throws NullPointerException if the fraction is {@code null}
@throws ArithmeticException if the resulting numerator or denominator exceeds
{@code Integer.MAX_VALUE}
|
java
|
src/main/java/org/apache/commons/lang3/math/Fraction.java
| 523
|
[
"fraction"
] |
Fraction
| true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
create_or_update_glue_job
|
def create_or_update_glue_job(self) -> str | None:
"""
Create (or update) and return the Job name.
.. seealso::
- :external+boto3:py:meth:`Glue.Client.update_job`
- :external+boto3:py:meth:`Glue.Client.create_job`
:return:Name of the Job
"""
if self.job_name is None:
raise ValueError("job_name must be set to create or update a Glue job")
config = self.create_glue_job_config()
if self.has_job(self.job_name):
self.update_job(**config)
else:
self.log.info("Creating job: %s", self.job_name)
self.conn.create_job(**config)
return self.job_name
|
Create (or update) and return the Job name.
.. seealso::
- :external+boto3:py:meth:`Glue.Client.update_job`
- :external+boto3:py:meth:`Glue.Client.create_job`
:return:Name of the Job
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/glue.py
| 507
|
[
"self"
] |
str | None
| true
| 4
| 6.24
|
apache/airflow
| 43,597
|
unknown
| false
|
split
|
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
|
Splits `string` by `separator`.
**Note:** This method is based on
[`String#split`](https://mdn.io/String/split).
@static
@memberOf _
@since 4.0.0
@category String
@param {string} [string=''] The string to split.
@param {RegExp|string} separator The separator pattern to split by.
@param {number} [limit] The length to truncate results to.
@returns {Array} Returns the string segments.
@example
_.split('a-b-c', '-', 2);
// => ['a', 'b']
|
javascript
|
lodash.js
| 14,694
|
[
"string",
"separator",
"limit"
] | false
| 12
| 7.36
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
hashBlockCalls
|
std::string
hashBlockCalls(const DenseMap<uint32_t, yaml::bolt::BinaryFunctionProfile *>
&IdToYamlFunction,
const yaml::bolt::BinaryBasicBlockProfile &YamlBB) {
std::vector<std::string> FunctionNames;
for (const yaml::bolt::CallSiteInfo &CallSiteInfo : YamlBB.CallSites) {
auto It = IdToYamlFunction.find(CallSiteInfo.DestId);
if (It == IdToYamlFunction.end())
continue;
StringRef Name = NameResolver::dropNumNames(It->second->Name);
FunctionNames.push_back(std::string(Name));
}
std::sort(FunctionNames.begin(), FunctionNames.end());
std::string HashString;
for (const std::string &FunctionName : FunctionNames)
HashString.append(FunctionName);
return HashString;
}
|
The same as the $hashBlockCalls function, but for profiled functions.
|
cpp
|
bolt/lib/Core/HashUtilities.cpp
| 189
|
[] | true
| 2
| 6.4
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
__init__
|
def __init__(self, levels: list[DimEntry]):
"""
Initialize and push dynamic layers for all first-class dimensions.
Args:
levels: List of dimension entries to create layers for
"""
from . import Dim
self.levels_start = 0
self.levels_to_dim = []
for l in levels:
if not l.is_positional():
d = l.dim()
assert isinstance(d, Dim)
self.levels_to_dim.append(d)
# Sort by level for stable ordering
self.levels_to_dim.sort(key=lambda d: d._level)
|
Initialize and push dynamic layers for all first-class dimensions.
Args:
levels: List of dimension entries to create layers for
|
python
|
functorch/dim/_enable_all_layers.py
| 34
|
[
"self",
"levels"
] | true
| 3
| 6.72
|
pytorch/pytorch
| 96,034
|
google
| false
|
|
completed_count
|
def completed_count(self):
"""Task completion count.
Note that `complete` means `successful` in this context. In other words, the
return value of this method is the number of ``successful`` tasks.
Returns:
int: the number of complete (i.e. successful) tasks.
"""
return sum(int(result.successful()) for result in self.results)
|
Task completion count.
Note that `complete` means `successful` in this context. In other words, the
return value of this method is the number of ``successful`` tasks.
Returns:
int: the number of complete (i.e. successful) tasks.
|
python
|
celery/result.py
| 656
|
[
"self"
] | false
| 1
| 6.08
|
celery/celery
| 27,741
|
unknown
| false
|
|
value
|
public XContentBuilder value(Boolean value) throws IOException {
return (value == null) ? nullValue() : value(value.booleanValue());
}
|
@return the value of the "human readable" flag. When the value is equal to true,
some types of values are written in a format easier to read for a human.
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
| 418
|
[
"value"
] |
XContentBuilder
| true
| 2
| 6.96
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
get_multi_stream
|
async def get_multi_stream(
self, log_group: str, streams: list[str], positions: dict[str, Any]
) -> AsyncGenerator[Any, tuple[int, Any | None]]:
"""
Iterate over the available events coming and interleaving the events from each stream so they're yielded in timestamp order.
:param log_group: The name of the log group.
:param streams: A list of the log stream names. The position of the stream in this list is
the stream number.
:param positions: A list of pairs of (timestamp, skip) which represents the last record
read from each stream.
"""
positions = positions or {s: Position(timestamp=0, skip=0) for s in streams}
events: list[Any | None] = []
logs_hook = AwsLogsHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
event_iters = [
logs_hook.get_log_events_async(log_group, s, positions[s].timestamp, positions[s].skip)
for s in streams
]
for event_stream in event_iters:
if not event_stream:
events.append(None)
continue
try:
events.append(await event_stream.__anext__())
except StopAsyncIteration:
events.append(None)
while any(events):
i = argmin(events, lambda x: x["timestamp"] if x else 9999999999) or 0
yield i, events[i]
try:
events[i] = await event_iters[i].__anext__()
except StopAsyncIteration:
events[i] = None
|
Iterate over the available events coming and interleaving the events from each stream so they're yielded in timestamp order.
:param log_group: The name of the log group.
:param streams: A list of the log stream names. The position of the stream in this list is
the stream number.
:param positions: A list of pairs of (timestamp, skip) which represents the last record
read from each stream.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 1,393
|
[
"self",
"log_group",
"streams",
"positions"
] |
AsyncGenerator[Any, tuple[int, Any | None]]
| true
| 7
| 6.88
|
apache/airflow
| 43,597
|
sphinx
| false
|
parseJsonMetadata
|
private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) throws IOException {
try {
return new InitializrServiceMetadata(getContentAsJson(httpEntity));
}
catch (JSONException ex) {
throw new ReportableException("Invalid content received from server (" + ex.getMessage() + ")", ex);
}
}
|
Loads the service capabilities of the service at the specified URL. If the service
supports generating a textual representation of the capabilities, it is returned,
otherwise {@link InitializrServiceMetadata} is returned.
@param serviceUrl to url of the initializer service
@return the service capabilities (as a String) or the
{@link InitializrServiceMetadata} describing the service
@throws IOException if the service capabilities cannot be loaded
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
| 134
|
[
"httpEntity"
] |
InitializrServiceMetadata
| true
| 2
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
createProperties
|
protected Properties createProperties() {
Properties result = CollectionFactory.createStringAdaptingProperties();
process((properties, map) -> result.putAll(properties));
return result;
}
|
Template method that subclasses may override to construct the object
returned by this factory. The default implementation returns a
properties with the content of all resources.
<p>Invoked lazily the first time {@link #getObject()} is invoked in
case of a shared singleton; else, on each {@link #getObject()} call.
@return the object returned by this factory
@see #process(MatchCallback)
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.java
| 132
|
[] |
Properties
| true
| 1
| 6.72
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
highlight_null
|
def highlight_null(
self,
color: str = "red",
subset: Subset | None = None,
props: str | None = None,
) -> Styler:
"""
Highlight missing values with a style.
Parameters
----------
%(color)s
%(subset)s
%(props)s
Returns
-------
Styler
Instance of class where null values are highlighted with given style.
See Also
--------
Styler.highlight_max: Highlight the maximum with a style.
Styler.highlight_min: Highlight the minimum with a style.
Styler.highlight_between: Highlight a defined range with a style.
Styler.highlight_quantile: Highlight values defined by a quantile with a style.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2], "B": [3, np.nan]})
>>> df.style.highlight_null(color="yellow") # doctest: +SKIP
Please see:
`Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
"""
def f(data: DataFrame, props: str) -> np.ndarray:
return np.where(pd.isna(data).to_numpy(), props, "")
if props is None:
props = f"background-color: {color};"
return self.apply(f, axis=None, subset=subset, props=props)
|
Highlight missing values with a style.
Parameters
----------
%(color)s
%(subset)s
%(props)s
Returns
-------
Styler
Instance of class where null values are highlighted with given style.
See Also
--------
Styler.highlight_max: Highlight the maximum with a style.
Styler.highlight_min: Highlight the minimum with a style.
Styler.highlight_between: Highlight a defined range with a style.
Styler.highlight_quantile: Highlight values defined by a quantile with a style.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2], "B": [3, np.nan]})
>>> df.style.highlight_null(color="yellow") # doctest: +SKIP
Please see:
`Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
|
python
|
pandas/io/formats/style.py
| 3,301
|
[
"self",
"color",
"subset",
"props"
] |
Styler
| true
| 2
| 6.8
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
__init__
|
def __init__(self, sub_dir: PathLike[str] | None = None) -> None:
"""Initialize the PersistentMemoizer with two-level caching.
Args:
sub_dir: Optional subdirectory within the cache directory for
organizing cached results. Defaults to empty string if not specified.
If non-empty, cache entries will be stored under cache_entries[sub_dir].
If empty, cache entries are merged into root cache_entries.
"""
# Use a Memoizer instance for in-memory caching
self._memoizer: Memoizer = Memoizer(sub_key=str(sub_dir) if sub_dir else None)
# Store on-disk cache as a separate attribute
self._disk_cache: implementations._OnDiskCacheImpl = (
implementations._OnDiskCacheImpl(sub_dir=sub_dir)
)
|
Initialize the PersistentMemoizer with two-level caching.
Args:
sub_dir: Optional subdirectory within the cache directory for
organizing cached results. Defaults to empty string if not specified.
If non-empty, cache entries will be stored under cache_entries[sub_dir].
If empty, cache entries are merged into root cache_entries.
|
python
|
torch/_inductor/runtime/caching/interfaces.py
| 616
|
[
"self",
"sub_dir"
] |
None
| true
| 2
| 6.4
|
pytorch/pytorch
| 96,034
|
google
| false
|
matchesPattern
|
protected boolean matchesPattern(String signatureString) {
for (int i = 0; i < this.patterns.length; i++) {
boolean matched = matches(signatureString, i);
if (matched) {
for (int j = 0; j < this.excludedPatterns.length; j++) {
boolean excluded = matchesExclusion(signatureString, j);
if (excluded) {
return false;
}
}
return true;
}
}
return false;
}
|
Match the specified candidate against the configured patterns.
@param signatureString "java.lang.Object.hashCode" style signature
@return whether the candidate matches at least one of the specified patterns
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java
| 144
|
[
"signatureString"
] | true
| 5
| 7.44
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
get_parameter_value
|
def get_parameter_value(self, parameter: str, default: str | ArgNotSet = NOTSET) -> str:
"""
Return the provided Parameter or an optional default.
If it is encrypted, then decrypt and mask.
.. seealso::
- :external+boto3:py:meth:`SSM.Client.get_parameter`
:param parameter: The SSM Parameter name to return the value for.
:param default: Optional default value to return if none is found.
"""
try:
param = self.conn.get_parameter(Name=parameter, WithDecryption=True)["Parameter"]
value = param["Value"]
if param["Type"] == "SecureString":
mask_secret(value)
return value
except self.conn.exceptions.ParameterNotFound:
if is_arg_set(default):
return default
raise
|
Return the provided Parameter or an optional default.
If it is encrypted, then decrypt and mask.
.. seealso::
- :external+boto3:py:meth:`SSM.Client.get_parameter`
:param parameter: The SSM Parameter name to return the value for.
:param default: Optional default value to return if none is found.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/ssm.py
| 55
|
[
"self",
"parameter",
"default"
] |
str
| true
| 3
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
toString
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName());
sb.append(" for target bean '").append(this.targetBeanName).append('\'');
Class<?> targetClass = this.targetClass;
if (targetClass != null) {
sb.append(" of type [").append(targetClass.getName()).append(']');
}
return sb.toString();
}
|
Copy configuration from the other AbstractBeanFactoryBasedTargetSource object.
Subclasses should override this if they wish to expose it.
@param other object to copy configuration from
|
java
|
spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java
| 184
|
[] |
String
| true
| 2
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
getJSONObject
|
public JSONObject getJSONObject(int index) throws JSONException {
Object object = get(index);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
else {
throw JSON.typeMismatch(index, object, "JSONObject");
}
}
|
Returns the value at {@code index} if it exists and is a {@code
JSONObject}.
@param index the index to get the value from
@return the object at {@code index}
@throws JSONException if the value doesn't exist or is not a {@code
JSONObject}.
|
java
|
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
| 553
|
[
"index"
] |
JSONObject
| true
| 2
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
toPrimitive
|
public static boolean[] toPrimitive(final Boolean[] array) {
return toPrimitive(array, false);
}
|
Converts an array of object Booleans to primitives.
<p>
This method returns {@code null} for a {@code null} input array.
</p>
<p>
Null array elements map to false, like {@code Boolean.parseBoolean(null)} and its callers return false.
</p>
@param array a {@link Boolean} array, may be {@code null}.
@return a {@code boolean} array, {@code null} if null array input.
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 8,820
|
[
"array"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
choose_offload_sets
|
def choose_offload_sets(
fwd_module: fx.GraphModule,
num_fwd_outputs: int,
static_lifetime_input_nodes: OrderedSet[fx.Node],
) -> bool:
"""
Decide which nodes will be offloaded based on the marked nodes and feasibility.
Marks nodes with "saved_for_offloading" if they should and can be offloaded.
Args:
fwd_module: Forward graph module
bwd_module: Backward graph module
num_fwd_outputs: Number of forward outputs
Returns:
bool: Whether activation offloading should be performed
"""
fwd_outputs: OrderedSet[fx.Node] = OrderedSet(
fwd_module.graph.find_nodes(op="output")[0].args[0]
)
model_outputs: OrderedSet[fx.Node] = OrderedSet(
fwd_module.graph.find_nodes(op="output")[0].args[0][:num_fwd_outputs]
)
should_perform_offloading = False
for node in fwd_module.graph.nodes:
if node.meta.get("should_offload", False) and can_offload(
node, fwd_outputs, model_outputs, static_lifetime_input_nodes
):
node.meta["saved_for_offloading"] = True
node.meta["original_device"] = node.meta["val"].device
should_perform_offloading = True
return should_perform_offloading
|
Decide which nodes will be offloaded based on the marked nodes and feasibility.
Marks nodes with "saved_for_offloading" if they should and can be offloaded.
Args:
fwd_module: Forward graph module
bwd_module: Backward graph module
num_fwd_outputs: Number of forward outputs
Returns:
bool: Whether activation offloading should be performed
|
python
|
torch/_functorch/_activation_offloading/activation_offloading.py
| 269
|
[
"fwd_module",
"num_fwd_outputs",
"static_lifetime_input_nodes"
] |
bool
| true
| 4
| 7.44
|
pytorch/pytorch
| 96,034
|
google
| false
|
checkExecSyncError
|
function checkExecSyncError(ret, args, cmd) {
let err;
if (ret.error) {
err = ret.error;
ObjectAssign(err, ret);
} else if (ret.status !== 0) {
let msg = 'Command failed: ';
msg += cmd || ArrayPrototypeJoin(args, ' ');
if (ret.stderr && ret.stderr.length > 0)
msg += `\n${ret.stderr.toString()}`;
err = genericNodeError(msg, ret);
}
return err;
}
|
Spawns a new process synchronously using the given `file`.
@param {string} file
@param {string[]} [args]
@param {{
cwd?: string | URL;
input?: string | Buffer | TypedArray | DataView;
argv0?: string;
stdio?: string | Array;
env?: Record<string, string>;
uid?: number;
gid?: number;
timeout?: number;
killSignal?: string | number;
maxBuffer?: number;
encoding?: string;
shell?: boolean | string;
windowsVerbatimArguments?: boolean;
windowsHide?: boolean;
}} [options]
@returns {{
pid: number;
output: Array;
stdout: Buffer | string;
stderr: Buffer | string;
status: number | null;
signal: string | null;
error: Error;
}}
|
javascript
|
lib/child_process.js
| 915
|
[
"ret",
"args",
"cmd"
] | false
| 7
| 6.8
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
resolveBeanClass
|
public @Nullable Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
String className = getBeanClassName();
if (className == null) {
return null;
}
Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
this.beanClass = resolvedClass;
return resolvedClass;
}
|
Determine the class of the wrapped bean, resolving it from a
specified class name if necessary. Will also reload a specified
Class from its name when called with the bean class already resolved.
@param classLoader the ClassLoader to use for resolving a (potential) class name
@return the resolved bean class
@throws ClassNotFoundException if the class name could be resolved
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java
| 484
|
[
"classLoader"
] | true
| 2
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
fireAutoConfigurationImportEvents
|
private void fireAutoConfigurationImportEvents(List<String> configurations, Set<String> exclusions) {
List<AutoConfigurationImportListener> listeners = getAutoConfigurationImportListeners();
if (!listeners.isEmpty()) {
AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions);
for (AutoConfigurationImportListener listener : listeners) {
invokeAwareMethods(listener);
listener.onAutoConfigurationImportEvent(event);
}
}
}
|
Returns the auto-configurations excluded by the
{@code spring.autoconfigure.exclude} property.
@return excluded auto-configurations
@since 2.3.2
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java
| 314
|
[
"configurations",
"exclusions"
] |
void
| true
| 2
| 6.4
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
transform
|
public <U extends @Nullable Object> ClosingFuture<U> transform(
ClosingFunction<? super V, U> function, Executor executor) {
checkNotNull(function);
AsyncFunction<V, U> applyFunction =
new AsyncFunction<V, U>() {
@Override
public ListenableFuture<U> apply(V input) throws Exception {
return closeables.applyClosingFunction(function, input);
}
@Override
public String toString() {
return function.toString();
}
};
// TODO(dpb): Switch to future.transformSync when that exists (passing a throwing function).
return derive(future.transformAsync(applyFunction, executor));
}
|
Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
to its value. The function can use a {@link DeferredCloser} to capture objects to be closed
when the pipeline is done.
<p>If this {@code ClosingFuture} fails, the function will not be called, and the derived {@code
ClosingFuture} will be equivalent to this one.
<p>If the function throws an exception, that exception is used as the result of the derived
{@code ClosingFuture}.
<p>Example usage:
{@snippet :
ClosingFuture<List<Row>> rowsFuture =
queryFuture.transform((closer, result) -> result.getRows(), executor);
}
<p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
about heavyweight listeners are also applicable to heavyweight functions passed to this method.
<p>After calling this method, you may not call {@link #finishToFuture()}, {@link
#finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
the original {@code ClosingFuture} instance.
@param function transforms the value of this step to the value of the derived step
@param executor executor to run the function in
@return the derived step
@throws IllegalStateException if a {@code ClosingFuture} has already been derived from this
one, or if this {@code ClosingFuture} has already been {@linkplain #finishToFuture()
finished}
|
java
|
android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
| 675
|
[
"function",
"executor"
] | true
| 1
| 6.4
|
google/guava
| 51,352
|
javadoc
| false
|
|
resolveDeclaredEventTypes
|
private static List<ResolvableType> resolveDeclaredEventTypes(Method method, @Nullable EventListener ann) {
int count = (KotlinDetector.isSuspendingFunction(method) ? method.getParameterCount() - 1 : method.getParameterCount());
if (count > 1) {
throw new IllegalStateException(
"Maximum one parameter is allowed for event listener method: " + method);
}
if (ann != null) {
Class<?>[] classes = ann.classes();
if (classes.length > 0) {
List<ResolvableType> types = new ArrayList<>(classes.length);
for (Class<?> eventType : classes) {
types.add(ResolvableType.forClass(eventType));
}
return types;
}
}
if (count == 0) {
throw new IllegalStateException(
"Event parameter is mandatory for event listener method: " + method);
}
return Collections.singletonList(ResolvableType.forMethodParameter(method, 0));
}
|
Construct a new ApplicationListenerMethodAdapter.
@param beanName the name of the bean to invoke the listener method on
@param targetClass the target class that the method is declared on
@param method the listener method to invoke
|
java
|
spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java
| 128
|
[
"method",
"ann"
] | true
| 6
| 6.56
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
entryIterator
|
@Override
Iterator<Entry<Cut<C>, Range<C>>> entryIterator() {
if (restriction.isEmpty()) {
return emptyIterator();
}
Iterator<Range<C>> completeRangeItr;
if (lowerBoundWindow.upperBound.isLessThan(restriction.lowerBound)) {
return emptyIterator();
} else if (lowerBoundWindow.lowerBound.isLessThan(restriction.lowerBound)) {
// starts at the first range with upper bound strictly greater than restriction.lowerBound
completeRangeItr =
rangesByUpperBound.tailMap(restriction.lowerBound, false).values().iterator();
} else {
// starts at the first range with lower bound above lowerBoundWindow.lowerBound
completeRangeItr =
rangesByLowerBound
.tailMap(
lowerBoundWindow.lowerBound.endpoint(),
lowerBoundWindow.lowerBoundType() == BoundType.CLOSED)
.values()
.iterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound));
return new AbstractIterator<Entry<Cut<C>, Range<C>>>() {
@Override
protected @Nullable Entry<Cut<C>, Range<C>> computeNext() {
if (!completeRangeItr.hasNext()) {
return endOfData();
}
Range<C> nextRange = completeRangeItr.next();
if (upperBoundOnLowerBounds.isLessThan(nextRange.lowerBound)) {
return endOfData();
} else {
nextRange = nextRange.intersection(restriction);
return immutableEntry(nextRange.lowerBound, nextRange);
}
}
};
}
|
restriction is the subRangeSet view; ranges are truncated to their intersection with
restriction.
|
java
|
android/guava/src/com/google/common/collect/TreeRangeSet.java
| 774
|
[] | true
| 6
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
|
validateProducerState
|
private void validateProducerState() {
if (isTransactional && producerId == RecordBatch.NO_PRODUCER_ID)
throw new IllegalArgumentException("Cannot write transactional messages without a valid producer ID");
if (producerId != RecordBatch.NO_PRODUCER_ID) {
if (producerEpoch == RecordBatch.NO_PRODUCER_EPOCH)
throw new IllegalArgumentException("Invalid negative producer epoch");
if (baseSequence < 0 && !isControlBatch)
throw new IllegalArgumentException("Invalid negative sequence number used");
if (magic < RecordBatch.MAGIC_VALUE_V2)
throw new IllegalArgumentException("Idempotent messages are not supported for magic " + magic);
}
}
|
Release resources required for record appends (e.g. compression buffers). Once this method is called, it's only
possible to update the RecordBatch header.
|
java
|
clients/src/main/java/org/apache/kafka/common/record/MemoryRecordsBuilder.java
| 388
|
[] |
void
| true
| 8
| 6.4
|
apache/kafka
| 31,560
|
javadoc
| false
|
supportsAdvice
|
boolean supportsAdvice(Advice advice);
|
Does this adapter understand this advice object? Is it valid to
invoke the {@code getInterceptors} method with an Advisor that
contains this advice as an argument?
@param advice an Advice such as a BeforeAdvice
@return whether this adapter understands the given advice object
@see #getInterceptor(org.springframework.aop.Advisor)
@see org.springframework.aop.BeforeAdvice
|
java
|
spring-aop/src/main/java/org/springframework/aop/framework/adapter/AdvisorAdapter.java
| 48
|
[
"advice"
] | true
| 1
| 6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
submit_job
|
def submit_job(
self,
jobName: str,
jobQueue: str,
jobDefinition: str,
arrayProperties: dict,
parameters: dict,
containerOverrides: dict,
ecsPropertiesOverride: dict,
eksPropertiesOverride: dict,
tags: dict,
) -> dict:
"""
Submit a Batch job.
:param jobName: the name for the AWS Batch job
:param jobQueue: the queue name on AWS Batch
:param jobDefinition: the job definition name on AWS Batch
:param arrayProperties: the same parameter that boto3 will receive
:param parameters: the same parameter that boto3 will receive
:param containerOverrides: the same parameter that boto3 will receive
:param ecsPropertiesOverride: the same parameter that boto3 will receive
:param eksPropertiesOverride: the same parameter that boto3 will receive
:param tags: the same parameter that boto3 will receive
:return: an API response
"""
...
|
Submit a Batch job.
:param jobName: the name for the AWS Batch job
:param jobQueue: the queue name on AWS Batch
:param jobDefinition: the job definition name on AWS Batch
:param arrayProperties: the same parameter that boto3 will receive
:param parameters: the same parameter that boto3 will receive
:param containerOverrides: the same parameter that boto3 will receive
:param ecsPropertiesOverride: the same parameter that boto3 will receive
:param eksPropertiesOverride: the same parameter that boto3 will receive
:param tags: the same parameter that boto3 will receive
:return: an API response
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_client.py
| 97
|
[
"self",
"jobName",
"jobQueue",
"jobDefinition",
"arrayProperties",
"parameters",
"containerOverrides",
"ecsPropertiesOverride",
"eksPropertiesOverride",
"tags"
] |
dict
| true
| 1
| 6.4
|
apache/airflow
| 43,597
|
sphinx
| false
|
run
|
public SpringApplication.Running run(String... args) {
RunListener runListener = new RunListener();
SpringApplicationHook hook = new SingleUseSpringApplicationHook((springApplication) -> {
springApplication.addPrimarySources(this.sources);
springApplication.setAdditionalProfiles(this.additionalProfiles.toArray(String[]::new));
return runListener;
});
withHook(hook, () -> this.main.accept(args));
return runListener;
}
|
Run the application using the given args.
@param args the main method args
@return the running {@link ApplicationContext}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
| 1,534
|
[] | true
| 1
| 6.56
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
sctype2char
|
def sctype2char(sctype):
"""
Return the string representation of a scalar dtype.
Parameters
----------
sctype : scalar dtype or object
If a scalar dtype, the corresponding string character is
returned. If an object, `sctype2char` tries to infer its scalar type
and then return the corresponding string character.
Returns
-------
typechar : str
The string character corresponding to the scalar type.
Raises
------
ValueError
If `sctype` is an object for which the type can not be inferred.
See Also
--------
obj2sctype, issctype, issubsctype, mintypecode
Examples
--------
>>> from numpy._core.numerictypes import sctype2char
>>> for sctype in [np.int32, np.double, np.cdouble, np.bytes_, np.ndarray]:
... print(sctype2char(sctype))
l # may vary
d
D
S
O
>>> x = np.array([1., 2-1.j])
>>> sctype2char(x)
'D'
>>> sctype2char(list)
'O'
"""
sctype = obj2sctype(sctype)
if sctype is None:
raise ValueError("unrecognized type")
if sctype not in sctypeDict.values():
# for compatibility
raise KeyError(sctype)
return dtype(sctype).char
|
Return the string representation of a scalar dtype.
Parameters
----------
sctype : scalar dtype or object
If a scalar dtype, the corresponding string character is
returned. If an object, `sctype2char` tries to infer its scalar type
and then return the corresponding string character.
Returns
-------
typechar : str
The string character corresponding to the scalar type.
Raises
------
ValueError
If `sctype` is an object for which the type can not be inferred.
See Also
--------
obj2sctype, issctype, issubsctype, mintypecode
Examples
--------
>>> from numpy._core.numerictypes import sctype2char
>>> for sctype in [np.int32, np.double, np.cdouble, np.bytes_, np.ndarray]:
... print(sctype2char(sctype))
l # may vary
d
D
S
O
>>> x = np.array([1., 2-1.j])
>>> sctype2char(x)
'D'
>>> sctype2char(list)
'O'
|
python
|
numpy/_core/numerictypes.py
| 478
|
[
"sctype"
] | false
| 3
| 7.68
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
filteredStates
|
public Set<TransactionState> filteredStates() {
return filteredStates;
}
|
Returns the set of states to be filtered or empty if no states have been specified.
@return the current set of filtered states (empty means that no states are filtered and
all transactions will be returned)
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/ListTransactionsOptions.java
| 93
|
[] | true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
toString
|
public static String toString(final Annotation a) {
final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
for (final Method m : a.annotationType().getDeclaredMethods()) {
if (m.getParameterTypes().length > 0) {
continue; // what?
}
try {
builder.append(m.getName(), m.invoke(a));
} catch (final ReflectiveOperationException ex) {
throw new UncheckedException(ex);
}
}
return builder.build();
}
|
Generate a string representation of an Annotation, as suggested by
{@link Annotation#toString()}.
@param a the annotation of which a string representation is desired
@return the standard string representation of an annotation, not
{@code null}
|
java
|
src/main/java/org/apache/commons/lang3/AnnotationUtils.java
| 331
|
[
"a"
] |
String
| true
| 3
| 7.28
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
shouldSkipHeartbeat
|
public boolean shouldSkipHeartbeat() {
MemberState state = state();
return state == MemberState.UNSUBSCRIBED ||
state == MemberState.FATAL ||
state == MemberState.STALE ||
state == MemberState.FENCED;
}
|
@return True if the member should not send heartbeats, which is the case when it is in a
state where it is not an active member of the group.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
| 754
|
[] | true
| 4
| 8.24
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
swapkey
|
def swapkey(self, old_key: str, new_key: str, new_value=None) -> None:
"""
Replace a variable name, with a potentially new value.
Parameters
----------
old_key : str
Current variable name to replace
new_key : str
New variable name to replace `old_key` with
new_value : object
Value to be replaced along with the possible renaming
"""
if self.has_resolvers:
maps = self.resolvers.maps + self.scope.maps
else:
maps = self.scope.maps
maps.append(self.temps)
for mapping in maps:
if old_key in mapping:
mapping[new_key] = new_value
return
|
Replace a variable name, with a potentially new value.
Parameters
----------
old_key : str
Current variable name to replace
new_key : str
New variable name to replace `old_key` with
new_value : object
Value to be replaced along with the possible renaming
|
python
|
pandas/core/computation/scope.py
| 247
|
[
"self",
"old_key",
"new_key",
"new_value"
] |
None
| true
| 5
| 6.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
hasnans
|
def hasnans(self) -> bool:
"""
Return True if there are any NaNs.
Enables various performance speedups.
Returns
-------
bool
See Also
--------
Index.isna : Detect missing values.
Index.dropna : Return Index without NA/NaN values.
Index.fillna : Fill NA/NaN values with the specified value.
Examples
--------
>>> s = pd.Series([1, 2, 3], index=["a", "b", None])
>>> s
a 1
b 2
None 3
dtype: int64
>>> s.index.hasnans
True
"""
if self._can_hold_na:
return bool(self._isnan.any())
else:
return False
|
Return True if there are any NaNs.
Enables various performance speedups.
Returns
-------
bool
See Also
--------
Index.isna : Detect missing values.
Index.dropna : Return Index without NA/NaN values.
Index.fillna : Fill NA/NaN values with the specified value.
Examples
--------
>>> s = pd.Series([1, 2, 3], index=["a", "b", None])
>>> s
a 1
b 2
None 3
dtype: int64
>>> s.index.hasnans
True
|
python
|
pandas/core/indexes/base.py
| 2,608
|
[
"self"
] |
bool
| true
| 3
| 8.32
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
removeAllOccurrences
|
public static byte[] removeAllOccurrences(final byte[] array, final byte element) {
return (byte[]) removeAt(array, indexesOf(array, element));
}
|
Removes the occurrences of the specified element from the specified byte array.
<p>
All subsequent elements are shifted to the left (subtracts one from their indices).
If the array doesn't contain such an element, no elements are removed from the array.
{@code null} will be returned if the input array is {@code null}.
</p>
@param array the input array, will not be modified, and may be {@code null}.
@param element the element to remove.
@return A new array containing the existing elements except the occurrences of the specified element.
@since 3.10
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 5,453
|
[
"array",
"element"
] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
meanOf
|
public static double meanOf(Iterator<? extends Number> values) {
checkArgument(values.hasNext());
long count = 1;
double mean = values.next().doubleValue();
while (values.hasNext()) {
double value = values.next().doubleValue();
count++;
if (isFinite(value) && isFinite(mean)) {
// Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
mean += (value - mean) / count;
} else {
mean = calculateNewMeanNonFinite(mean, value);
}
}
return mean;
}
|
Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the
values. The count must be non-zero.
<p>The definition of the mean is the same as {@link Stats#mean}.
@param values a series of values, which will be converted to {@code double} values (this may
cause loss of precision)
@throws IllegalArgumentException if the dataset is empty
|
java
|
android/guava/src/com/google/common/math/Stats.java
| 492
|
[
"values"
] | true
| 4
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
openRawZipData
|
public CloseableDataBlock openRawZipData() throws IOException {
this.data.open();
return (!this.nameOffsetLookups.hasAnyEnabled()) ? this.data : getVirtualData();
}
|
Open a {@link DataBlock} containing the raw zip data. For container zip files, this
may be smaller than the original file since additional bytes are permitted at the
front of a zip file. For nested zip files, this will be only the contents of the
nest zip.
<p>
For nested directory zip files, a virtual data block will be created containing
only the relevant content.
<p>
To release resources, the {@link #close()} method of the data block should be
called explicitly or by try-with-resources.
<p>
The returned data block should not be accessed once {@link #close()} has been
called.
@return the zip data
@throws IOException on I/O error
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java
| 141
|
[] |
CloseableDataBlock
| true
| 2
| 8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
of
|
static WritableJson of(WritableJson writableJson) {
return new WritableJson() {
@Override
public void to(Appendable out) throws IOException {
writableJson.to(out);
}
@Override
public String toString() {
return toJsonString();
}
};
}
|
Factory method used to create a {@link WritableJson} with a sensible
{@link Object#toString()} that delegate to {@link WritableJson#toJsonString()}.
@param writableJson the source {@link WritableJson}
@return a new {@link WritableJson} with a sensible {@link Object#toString()}.
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/json/WritableJson.java
| 159
|
[
"writableJson"
] |
WritableJson
| true
| 1
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
toArray
|
public static short[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ShortArrayAsList) {
return ((ShortArrayAsList) collection).toShortArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
short[] array = new short[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
}
return array;
}
|
Returns an array containing each value of {@code collection}, converted to a {@code short}
value in the manner of {@link Number#shortValue}.
<p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
Calling this method is as thread-safe as calling that method.
@param collection a collection of {@code Number} instances
@return an array containing the same values as {@code collection}, in the same order, converted
to primitives
@throws NullPointerException if {@code collection} or any of its elements is null
@since 1.0 (parameter was {@code Collection<Short>} before 12.0)
|
java
|
android/guava/src/com/google/common/primitives/Shorts.java
| 589
|
[
"collection"
] | true
| 3
| 8.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
addReference
|
function addReference(referenceLocation: Node, relatedSymbol: Symbol | RelatedSymbol, state: State): void {
const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }; // eslint-disable-line local/no-in-operator
// if rename symbol from default export anonymous function, for example `export default function() {}`, we do not need to add reference
if (state.options.use === FindReferencesUse.Rename && referenceLocation.kind === SyntaxKind.DefaultKeyword) {
return;
}
const addRef = state.referenceAdder(symbol);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
else {
addRef(referenceLocation, kind);
}
}
|
Search within node "container" for references for a search value, where the search value is defined as a
tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
searchLocation: a node where the search value
|
typescript
|
src/services/findAllReferences.ts
| 2,115
|
[
"referenceLocation",
"relatedSymbol",
"state"
] | true
| 6
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
getConfigurationClassFilter
|
private ConfigurationClassFilter getConfigurationClassFilter() {
ConfigurationClassFilter configurationClassFilter = this.configurationClassFilter;
if (configurationClassFilter == null) {
List<AutoConfigurationImportFilter> filters = getAutoConfigurationImportFilters();
for (AutoConfigurationImportFilter filter : filters) {
invokeAwareMethods(filter);
}
configurationClassFilter = new ConfigurationClassFilter(this.beanClassLoader, filters);
this.configurationClassFilter = configurationClassFilter;
}
return configurationClassFilter;
}
|
Returns the auto-configurations excluded by the
{@code spring.autoconfigure.exclude} property.
@return excluded auto-configurations
@since 2.3.2
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java
| 282
|
[] |
ConfigurationClassFilter
| true
| 2
| 7.6
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
doSanitizeHtml
|
function doSanitizeHtml(untrusted: string, config: DomSanitizerConfig | undefined, outputType: 'dom' | 'trusted'): TrustedHTML | DocumentFragment {
try {
const resolvedConfig: DomPurifyTypes.Config = { ...defaultDomPurifyConfig };
if (config?.allowedTags) {
if (config.allowedTags.override) {
resolvedConfig.ALLOWED_TAGS = [...config.allowedTags.override];
}
if (config.allowedTags.augment) {
resolvedConfig.ALLOWED_TAGS = [...(resolvedConfig.ALLOWED_TAGS ?? []), ...config.allowedTags.augment];
}
}
let resolvedAttributes: Array<string | SanitizeAttributeRule> = [...defaultAllowedAttrs];
if (config?.allowedAttributes) {
if (config.allowedAttributes.override) {
resolvedAttributes = [...config.allowedAttributes.override];
}
if (config.allowedAttributes.augment) {
resolvedAttributes = [...resolvedAttributes, ...config.allowedAttributes.augment];
}
}
// All attr names are lower-case in the sanitizer hooks
resolvedAttributes = resolvedAttributes.map((attr): string | SanitizeAttributeRule => {
if (typeof attr === 'string') {
return attr.toLowerCase();
}
return {
attributeName: attr.attributeName.toLowerCase(),
shouldKeep: attr.shouldKeep,
};
});
const allowedAttrNames = new Set(resolvedAttributes.map(attr => typeof attr === 'string' ? attr : attr.attributeName));
const allowedAttrPredicates = new Map<string, SanitizeAttributeRule>();
for (const attr of resolvedAttributes) {
if (typeof attr === 'string') {
// New string attribute value clears previously set predicates
allowedAttrPredicates.delete(attr);
} else {
allowedAttrPredicates.set(attr.attributeName, attr);
}
}
resolvedConfig.ALLOWED_ATTR = Array.from(allowedAttrNames);
hookDomPurifyHrefAndSrcSanitizer(
{
override: config?.allowedLinkProtocols?.override ?? [Schemas.http, Schemas.https],
allowRelativePaths: config?.allowRelativeLinkPaths ?? false
},
{
override: config?.allowedMediaProtocols?.override ?? [Schemas.http, Schemas.https],
allowRelativePaths: config?.allowRelativeMediaPaths ?? false
});
if (config?.replaceWithPlaintext) {
dompurify.addHook('uponSanitizeElement', replaceWithPlainTextHook);
}
if (allowedAttrPredicates.size) {
dompurify.addHook('uponSanitizeAttribute', (node, e) => {
const predicate = allowedAttrPredicates.get(e.attrName);
if (predicate) {
const result = predicate.shouldKeep(node, e);
if (typeof result === 'string') {
e.keepAttr = true;
e.attrValue = result;
} else {
e.keepAttr = result;
}
} else {
e.keepAttr = allowedAttrNames.has(e.attrName);
}
});
}
if (outputType === 'dom') {
return dompurify.sanitize(untrusted, {
...resolvedConfig,
RETURN_DOM_FRAGMENT: true
});
} else {
return dompurify.sanitize(untrusted, {
...resolvedConfig,
RETURN_TRUSTED_TYPE: true
}) as unknown as TrustedHTML; // Cast from lib TrustedHTML to global TrustedHTML
}
} finally {
dompurify.removeAllHooks();
}
}
|
Sanitizes an html string.
@param untrusted The HTML string to sanitize.
@param config Optional configuration for sanitization. If not provided, defaults to a safe configuration.
@returns A sanitized string of html.
|
typescript
|
src/vs/base/browser/domSanitize.ts
| 244
|
[
"untrusted",
"config",
"outputType"
] | true
| 19
| 7.12
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
addCallback
|
public static <V extends @Nullable Object> void addCallback(
ListenableFuture<V> future, FutureCallback<? super V> callback, Executor executor) {
Preconditions.checkNotNull(callback);
future.addListener(new CallbackListener<V>(future, callback), executor);
}
|
Registers separate success and failure callbacks to be run when the {@code Future}'s
computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
computation is already complete, immediately.
<p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
callbacks, but any callback added through this method is guaranteed to be called once the
computation is complete.
<p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception
thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an
exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught
and logged.
<p>Example:
{@snippet :
ListenableFuture<QueryResult> future = ...;
Executor e = ...
addCallback(future,
new FutureCallback<QueryResult>() {
public void onSuccess(QueryResult result) {
storeInCache(result);
}
public void onFailure(Throwable t) {
reportError(t);
}
}, e);
}
<p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
the warnings the {@link MoreExecutors#directExecutor} documentation.
<p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
ListenableFuture#addListener addListener}.
@param future The future attach the callback to.
@param callback The callback to invoke when {@code future} is completed.
@param executor The executor to run {@code callback} when the future completes.
@since 10.0
|
java
|
android/guava/src/com/google/common/util/concurrent/Futures.java
| 1,097
|
[
"future",
"callback",
"executor"
] |
void
| true
| 1
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.