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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
logDeprecatedBean | protected void logDeprecatedBean(String beanName, Class<?> beanType, BeanDefinition beanDefinition) {
StringBuilder builder = new StringBuilder();
builder.append(beanType);
builder.append(" ['");
builder.append(beanName);
builder.append('\'');
String resourceDescription = beanDefinition.getResourceDescripti... | Logs a warning for a bean annotated with {@link Deprecated @Deprecated}.
@param beanName the name of the deprecated bean
@param beanType the user-specified type of the deprecated bean
@param beanDefinition the definition of the deprecated bean | java | spring-beans/src/main/java/org/springframework/beans/factory/config/DeprecatedBeanWarner.java | 81 | [
"beanName",
"beanType",
"beanDefinition"
] | void | true | 2 | 6.4 | spring-projects/spring-framework | 59,386 | javadoc | false |
transformObjectLiteralMembersSortText | function transformObjectLiteralMembersSortText(start: number): void {
for (let i = start; i < symbols.length; i++) {
const symbol = symbols[i];
const symbolId = getSymbolId(symbol);
const origin = symbolToOriginInfoMap?.[i];
const target = getEmitScriptTarget... | Filters out completion suggestions for named imports or exports.
@returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
do not occur at the current position and have not otherwise been typed. | typescript | src/services/completions.ts | 5,215 | [
"start"
] | true | 3 | 6.72 | microsoft/TypeScript | 107,154 | jsdoc | false | |
requireBracketsForIPv6 | @CanIgnoreReturnValue
public HostAndPort requireBracketsForIPv6() {
checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host);
return this;
} | Generate an error if the host might be a non-bracketed IPv6 literal.
<p>URI formatting requires that IPv6 literals be surrounded by brackets, like "[2001:db8::1]".
Chain this call after {@link #fromString(String)} to increase the strictness of the parser, and
disallow IPv6 literals that don't contain these brackets.
<p... | java | android/guava/src/com/google/common/net/HostAndPort.java | 271 | [] | HostAndPort | true | 1 | 6.4 | google/guava | 51,352 | javadoc | false |
calculateDeadlineMs | static long calculateDeadlineMs(final long currentTimeMs, final long timeoutMs) {
if (currentTimeMs > Long.MAX_VALUE - timeoutMs)
return Long.MAX_VALUE;
else
return currentTimeMs + timeoutMs;
} | Calculate the deadline timestamp based on the current time and timeout.
@param currentTimeMs Current time, in milliseconds
@param timeoutMs Timeout, in milliseconds
@return Absolute time by which event should be completed | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEvent.java | 121 | [
"currentTimeMs",
"timeoutMs"
] | true | 2 | 7.44 | apache/kafka | 31,560 | javadoc | false | |
localeLookupList | public static List<Locale> localeLookupList(final Locale locale) {
return localeLookupList(locale, locale);
} | Obtains the list of locales to search through when performing a locale search.
<pre>
localeLookupList(Locale("fr", "CA", "xxx"))
= [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr")]
</pre>
@param locale the locale to start from.
@return the unmodifiable list of Locale objects, 0 being locale, not null. | java | src/main/java/org/apache/commons/lang3/LocaleUtils.java | 268 | [
"locale"
] | true | 1 | 6.32 | apache/commons-lang | 2,896 | javadoc | false | |
range | public static IntStream range(final int endExclusive) {
return IntStream.range(0, endExclusive);
} | Shorthand for {@code IntStream.range(0, i)}.
@param endExclusive the exclusive upper bound.
@return a sequential {@link IntStream} for the range of {@code int} elements. | java | src/main/java/org/apache/commons/lang3/stream/IntStreams.java | 49 | [
"endExclusive"
] | IntStream | true | 1 | 6.48 | apache/commons-lang | 2,896 | javadoc | false |
getExpireAfterAccessNanos | @SuppressWarnings("GoodTime") // nanos internally, should be Duration
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS
: expireAfterAccessNanos;
} | Specifies that each entry should be automatically removed from the cache once a fixed duration
has elapsed after the entry's creation, the most recent replacement of its value, or its last
access. Access time is reset by all cache read and write operations (including {@code
Cache.asMap().get(Object)} and {@code Cache.a... | java | android/guava/src/com/google/common/cache/CacheBuilder.java | 848 | [] | true | 2 | 7.6 | google/guava | 51,352 | javadoc | false | |
getWriteMethodParameter | public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) {
if (pd instanceof GenericTypeAwarePropertyDescriptor gpd) {
return new MethodParameter(gpd.getWriteMethodParameter());
}
else {
Method writeMethod = pd.getWriteMethod();
Assert.state(writeMethod != null, "No write method avail... | Obtain a new MethodParameter object for the write method of the
specified property.
@param pd the PropertyDescriptor for the property
@return a corresponding MethodParameter object | java | spring-beans/src/main/java/org/springframework/beans/BeanUtils.java | 633 | [
"pd"
] | MethodParameter | true | 2 | 7.28 | spring-projects/spring-framework | 59,386 | javadoc | false |
run | @Override
public void run() {
InterruptibleTask<?> localTask = task;
if (localTask != null) {
localTask.run();
}
/*
* In the Async case, we may have called setFuture(pendingFuture), in which case afterDone()
* won't have been called yet.
*/
this.task = null;
} | Creates a {@code ListenableFutureTask} that will upon running, execute the given {@code
Runnable}, and arrange that {@code get} will return the given result on successful completion.
@param runnable the runnable task
@param result the result to return on successful completion. If you don't need a particular
result,... | java | android/guava/src/com/google/common/util/concurrent/TrustedListenableFutureTask.java | 76 | [] | void | true | 2 | 6.4 | google/guava | 51,352 | javadoc | false |
buildMessage | private static String buildMessage(@Nullable ConfigurationPropertyName name, Bindable<?> target) {
StringBuilder message = new StringBuilder();
message.append("Failed to bind properties");
message.append((name != null) ? " under '" + name + "'" : "");
message.append(" to ").append(target.getType());
return me... | Return the configuration property name of the item that was being bound.
@return the configuration property name | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindException.java | 78 | [
"name",
"target"
] | String | true | 2 | 6.72 | spring-projects/spring-boot | 79,428 | javadoc | false |
registerMetricForSubscription | @Override
public void registerMetricForSubscription(KafkaMetric metric) {
if (!metrics().containsKey(metric.metricName())) {
clientTelemetryReporter.ifPresent(reporter -> reporter.metricChange(metric));
} else {
log.debug("Skipping registration for metric {}. Existing produc... | Add the provided application metric for subscription.
This metric will be added to this client's metrics
that are available for subscription and sent as
telemetry data to the broker.
The provided metric must map to an OTLP metric data point
type in the OpenTelemetry v1 metrics protobuf message types.
Specifically, the ... | java | clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java | 1,406 | [
"metric"
] | void | true | 2 | 6.72 | apache/kafka | 31,560 | javadoc | false |
setCount | @CanIgnoreReturnValue
@Override
public Builder<E> setCount(E element, int count) {
checkNotNull(element);
CollectPreconditions.checkNonnegative(count, "count");
maintenance();
elements[length] = element;
counts[length] = ~count;
length++;
return this;
} | Adds or removes the necessary occurrences of an element such that the element attains the
desired count.
@param element the element to add or remove occurrences of
@param count the desired count of the element in this multiset
@return this {@code Builder} object
@throws NullPointerException if {@code element} is null
@... | java | android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java | 618 | [
"element",
"count"
] | true | 1 | 6.4 | google/guava | 51,352 | javadoc | false | |
canSendMore | public boolean canSendMore(String node) {
Deque<NetworkClient.InFlightRequest> queue = requests.get(node);
return queue == null || queue.isEmpty() ||
(queue.peekFirst().send.completed() && queue.size() < this.maxInFlightRequestsPerConnection);
} | Can we send more requests to this node?
@param node Node in question
@return true iff we have no requests still being sent to the given node | java | clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java | 96 | [
"node"
] | true | 4 | 8.08 | apache/kafka | 31,560 | javadoc | false | |
expireDelegationToken | default ExpireDelegationTokenResult expireDelegationToken(byte[] hmac) {
return expireDelegationToken(hmac, new ExpireDelegationTokenOptions());
} | Expire a Delegation Token.
<p>
This is a convenience method for {@link #expireDelegationToken(byte[], ExpireDelegationTokenOptions)} with default options.
This will expire the token immediately. See the overload for more details.
@param hmac HMAC of the Delegation token
@return The ExpireDelegationTokenResult. | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 792 | [
"hmac"
] | ExpireDelegationTokenResult | true | 1 | 6.16 | apache/kafka | 31,560 | javadoc | false |
unstack | def unstack(
self,
level: IndexLabel = -1,
fill_value: Hashable | None = None,
sort: bool = True,
) -> DataFrame:
"""
Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
Parameters
----------
level : int, str, or list of... | Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
Parameters
----------
level : int, str, or list of these, default last level
Level(s) to unstack, can pass level name.
fill_value : scalar value, default None
Value to use when replacing NaN values.
sort : bool, default True
Sort th... | python | pandas/core/series.py | 4,346 | [
"self",
"level",
"fill_value",
"sort"
] | DataFrame | true | 1 | 7.28 | pandas-dev/pandas | 47,362 | numpy | false |
refactor_levels | def refactor_levels(
level: Level | list[Level] | None,
obj: Index,
) -> list[int]:
"""
Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``.
Parameters
----------
level : int, str, list
Original ``level`` arg supplied to above methods.
obj:
Eith... | Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``.
Parameters
----------
level : int, str, list
Original ``level`` arg supplied to above methods.
obj:
Either ``self.index`` or ``self.columns``
Returns
-------
list : refactored arg with a list of levels to hide | python | pandas/io/formats/style_render.py | 2,087 | [
"level",
"obj"
] | list[int] | true | 7 | 6.88 | pandas-dev/pandas | 47,362 | numpy | false |
findAllAnnotationsOnBean | <A extends Annotation> Set<A> findAllAnnotationsOnBean(
String beanName, Class<A> annotationType, boolean allowFactoryBeanInit)
throws NoSuchBeanDefinitionException; | Find all {@link Annotation} instances of {@code annotationType} on the specified
bean, traversing its interfaces and superclasses if no annotation can be found on
the given class itself, as well as checking the bean's factory method (if any).
@param beanName the name of the bean to look for annotations on
@param annota... | java | spring-beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java | 418 | [
"beanName",
"annotationType",
"allowFactoryBeanInit"
] | true | 1 | 6.32 | spring-projects/spring-framework | 59,386 | javadoc | false | |
findPrimaryConstructor | @SuppressWarnings("unchecked")
public static <T> @Nullable Constructor<T> findPrimaryConstructor(Class<T> clazz) {
try {
KClass<T> kClass = JvmClassMappingKt.getKotlinClass(clazz);
KFunction<T> primaryCtor = KClasses.getPrimaryConstructor(kClass);
if (primaryCtor == null) {
return null;
}
... | Retrieve the Java constructor corresponding to the Kotlin primary constructor, if any.
@param clazz the {@link Class} of the Kotlin class
@see <a href="https://kotlinlang.org/docs/reference/classes.html#constructors">
https://kotlinlang.org/docs/reference/classes.html#constructors</a> | java | spring-beans/src/main/java/org/springframework/beans/BeanUtils.java | 873 | [
"clazz"
] | true | 5 | 6.4 | spring-projects/spring-framework | 59,386 | javadoc | false | |
__call__ | def __call__(self, iterable):
"""Dispatch the tasks and return the results.
Parameters
----------
iterable : iterable
Iterable containing tuples of (delayed_function, args, kwargs) that should
be consumed.
Returns
-------
results : list
... | Dispatch the tasks and return the results.
Parameters
----------
iterable : iterable
Iterable containing tuples of (delayed_function, args, kwargs) that should
be consumed.
Returns
-------
results : list
List of results of the tasks. | python | sklearn/utils/parallel.py | 54 | [
"self",
"iterable"
] | false | 2 | 6.08 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
all | public KafkaFuture<Map<ConfigResource, Config>> all() {
return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture<?>[0])).
thenApply(v -> {
Map<ConfigResource, Config> configs = new HashMap<>(futures.size());
for (Map.Entry<ConfigResource, KafkaFut... | Return a future which succeeds only if all the config descriptions succeed. | java | clients/src/main/java/org/apache/kafka/clients/admin/DescribeConfigsResult.java | 50 | [] | true | 2 | 7.04 | apache/kafka | 31,560 | javadoc | false | |
equals | @Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof FeatureUpdate)) {
return false;
}
final FeatureUpdate that = (FeatureUpdate) other;
return this.maxVersionLevel == that.maxVersionLevel... | @param maxVersionLevel The new maximum version level for the finalized feature.
a value of zero is special and indicates that the update is intended to
delete the finalized feature, and should be accompanied by setting
the upgradeType to safe ... | java | clients/src/main/java/org/apache/kafka/clients/admin/FeatureUpdate.java | 88 | [
"other"
] | true | 4 | 6.56 | apache/kafka | 31,560 | javadoc | false | |
concat | function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copy... | Creates a new array concatenating `array` with any additional arrays
and/or values.
@static
@memberOf _
@since 4.0.0
@category Array
@param {Array} array The array to concatenate.
@param {...*} [values] The values to concatenate.
@returns {Array} Returns the new concatenated array.
@example
var array = [1];
var other =... | javascript | lodash.js | 7,014 | [] | false | 4 | 8.56 | lodash/lodash | 61,490 | jsdoc | false | |
notEmpty | public static <T extends Collection<?>> T notEmpty(final T collection) {
return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
} | <p>Validates that the specified argument collection is neither {@code null}
nor a size of zero (no elements); otherwise throwing an exception.
<pre>Validate.notEmpty(myCollection);</pre>
<p>The message in the exception is "The validated collection is
empty".
@param <T> the collection type.
@param collection ... | java | src/main/java/org/apache/commons/lang3/Validate.java | 827 | [
"collection"
] | T | true | 1 | 6.16 | apache/commons-lang | 2,896 | javadoc | false |
check_for_prefix | def check_for_prefix(self, prefix: str, delimiter: str, bucket_name: str | None = None) -> bool:
"""
Check that a prefix exists in a bucket.
:param bucket_name: the name of the bucket
:param prefix: a key prefix
:param delimiter: the delimiter marks key hierarchy.
:retur... | Check that a prefix exists in a bucket.
:param bucket_name: the name of the bucket
:param prefix: a key prefix
:param delimiter: the delimiter marks key hierarchy.
:return: False if the prefix does not exist in the bucket and True if it does. | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py | 367 | [
"self",
"prefix",
"delimiter",
"bucket_name"
] | bool | true | 2 | 8.24 | apache/airflow | 43,597 | sphinx | false |
removeRequest | @Override
void removeRequest() {
if (!unsentOffsetCommitRequests().remove(this)) {
log.warn("OffsetCommit request to remove not found in the outbound buffer: {}", this);
}
} | Handle OffsetCommitResponse. This will complete the request future successfully if no
errors are found in the response. If the response contains errors, this will:
- handle expected errors and fail the future with specific exceptions depending on the error
- fail the future with a non-recoverable KafkaException for... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java | 862 | [] | void | true | 2 | 6.08 | apache/kafka | 31,560 | javadoc | false |
toChar | public static char toChar(final Character ch, final char defaultValue) {
return ch != null ? ch.charValue() : defaultValue;
} | Converts the Character to a char handling {@code null}.
<pre>
CharUtils.toChar(null, 'X') = 'X'
CharUtils.toChar(' ', 'X') = ' '
CharUtils.toChar('A', 'X') = 'A'
</pre>
@param ch the character to convert
@param defaultValue the value to use if the Character is null
@return the char value of the Character or ... | java | src/main/java/org/apache/commons/lang3/CharUtils.java | 296 | [
"ch",
"defaultValue"
] | true | 2 | 8 | apache/commons-lang | 2,896 | javadoc | false | |
checkIndexBounds | private static void checkIndexBounds(long index) {
assert index >= MIN_INDEX && index <= MAX_INDEX : "index must be in range [" + MIN_INDEX + ".." + MAX_INDEX + "]";
} | Provides the index of the bucket of the exponential histogram with the given scale that contains the provided value.
@param value the value to find the bucket for
@param scale the scale of the histogram
@return the index of the bucket | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialScaleUtils.java | 283 | [
"index"
] | void | true | 2 | 8 | elastic/elasticsearch | 75,680 | javadoc | false |
handleExitCode | private void handleExitCode(@Nullable ConfigurableApplicationContext context, Throwable exception) {
int exitCode = getExitCodeFromException(context, exception);
if (exitCode != 0) {
if (context != null) {
context.publishEvent(new ExitCodeEvent(context, exitCode));
}
SpringBootExceptionHandler handler ... | Register that the given exception has been logged. By default, if the running in
the main thread, this method will suppress additional printing of the stacktrace.
@param exception the exception that was logged | java | core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java | 881 | [
"context",
"exception"
] | void | true | 4 | 7.04 | spring-projects/spring-boot | 79,428 | javadoc | false |
uppercase | public static String uppercase(String value) {
return UppercaseProcessor.apply(value);
} | Uses {@link UppercaseProcessor} to convert a string to its uppercase
equivalent.
@param value string to convert
@return uppercase equivalent | java | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/Processors.java | 51 | [
"value"
] | String | true | 1 | 6 | elastic/elasticsearch | 75,680 | javadoc | false |
grouped_reduce | def grouped_reduce(self, func: Callable) -> Self:
"""
Apply grouped reduction function blockwise, returning a new BlockManager.
Parameters
----------
func : grouped reduction function
Returns
-------
BlockManager
"""
result_blocks: list[B... | Apply grouped reduction function blockwise, returning a new BlockManager.
Parameters
----------
func : grouped reduction function
Returns
-------
BlockManager | python | pandas/core/internals/managers.py | 1,597 | [
"self",
"func"
] | Self | true | 7 | 6.24 | pandas-dev/pandas | 47,362 | numpy | false |
closeBeanFactory | @Override
protected final void closeBeanFactory() {
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory != null) {
beanFactory.setSerializationId(null);
this.beanFactory = null;
}
} | This implementation performs an actual refresh of this context's underlying
bean factory, shutting down the previous bean factory (if any) and
initializing a fresh bean factory for the next phase of the context's lifecycle. | java | spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableApplicationContext.java | 146 | [] | void | true | 2 | 6.72 | spring-projects/spring-framework | 59,386 | javadoc | false |
_na_for_min_count | def _na_for_min_count(values: np.ndarray, axis: AxisInt | None) -> Scalar | np.ndarray:
"""
Return the missing value for `values`.
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction, required if values.ndim > 1.
Returns
-------
result : scalar ... | Return the missing value for `values`.
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction, required if values.ndim > 1.
Returns
-------
result : scalar or ndarray
For 1-D values, returns a scalar of the correct missing type.
For 2-D values, returns a 1-D array where each elem... | python | pandas/core/nanops.py | 419 | [
"values",
"axis"
] | Scalar | np.ndarray | true | 5 | 6.88 | pandas-dev/pandas | 47,362 | numpy | false |
tokenize_string | def tokenize_string(source: str) -> Iterator[tuple[int, str]]:
"""
Tokenize a Python source code string.
Parameters
----------
source : str
The Python source code string.
Returns
-------
tok_generator : Iterator[Tuple[int, str]]
An iterator yielding all tokens with only... | Tokenize a Python source code string.
Parameters
----------
source : str
The Python source code string.
Returns
-------
tok_generator : Iterator[Tuple[int, str]]
An iterator yielding all tokens with only toknum and tokval (Tuple[ing, str]). | python | pandas/core/computation/parsing.py | 223 | [
"source"
] | Iterator[tuple[int, str]] | true | 3 | 6.4 | pandas-dev/pandas | 47,362 | numpy | false |
optBoolean | public boolean optBoolean(String name, boolean fallback) {
Object object = opt(name);
Boolean result = JSON.toBoolean(object);
return result != null ? result : fallback;
} | Returns the value mapped by {@code name} if it exists and is a boolean or can be
coerced to a boolean. Returns {@code fallback} otherwise.
@param name the name of the property
@param fallback a fallback value
@return the value or {@code fallback} | java | cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java | 421 | [
"name",
"fallback"
] | true | 2 | 8.24 | spring-projects/spring-boot | 79,428 | javadoc | false | |
createServiceLocatorException | protected Exception createServiceLocatorException(Constructor<Exception> exceptionConstructor, BeansException cause) {
Class<?>[] paramTypes = exceptionConstructor.getParameterTypes();
@Nullable Object[] args = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
if (String.class == par... | Create a service locator exception for the given cause.
Only called in case of a custom service locator exception.
<p>The default implementation can handle all variations of
message and exception arguments.
@param exceptionConstructor the constructor to use
@param cause the cause of the service lookup failure
@return t... | java | spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java | 312 | [
"exceptionConstructor",
"cause"
] | Exception | true | 4 | 7.44 | spring-projects/spring-framework | 59,386 | javadoc | false |
updateAutoCommitTimer | private void updateAutoCommitTimer(final long currentTimeMs) {
this.autoCommitState.ifPresent(t -> t.updateTimer(currentTimeMs));
} | Enqueue a request to fetch committed offsets, that will be sent on the next call to {@link #poll(long)}.
@param partitions Partitions to fetch offsets for.
@param deadlineMs Time until which the request should be retried if it fails
with expected retriable errors.
@return Future that... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java | 577 | [
"currentTimeMs"
] | void | true | 1 | 6.8 | apache/kafka | 31,560 | javadoc | false |
read | private int read(ByteBuffer dst, int pos) {
int remaining = dst.remaining();
int length = Math.min(this.bytes.length - pos, remaining);
if (this.maxReadSize > 0 && length > this.maxReadSize) {
length = this.maxReadSize;
}
dst.put(this.bytes, pos, length);
return length;
} | Create a new {@link ByteArrayDataBlock} backed by the given bytes.
@param bytes the bytes to use | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ByteArrayDataBlock.java | 56 | [
"dst",
"pos"
] | true | 3 | 6.56 | spring-projects/spring-boot | 79,428 | javadoc | false | |
benchmark_gpu | def benchmark_gpu( # type: ignore[override]
self: Self,
_callable: Callable[[], Any],
estimation_iters: int = 5,
memory_warmup_iters: int = 100,
benchmark_iters: int = 100,
max_benchmark_duration: int = 25,
return_mode: str = "min",
grad_to_none: list[tor... | Benchmark a GPU callable using a custom benchmarking implementation.
Arguments:
- _callable: The callable to benchmark.
Keyword Arguments:
- estimation_iters: Optionally, the number of iterations to run `_callable`
during runtime estimation.
- memory_warmup_iters: Optionally, the number of iterations to flush the L2
... | python | torch/_inductor/runtime/benchmarking.py | 331 | [
"self",
"_callable",
"estimation_iters",
"memory_warmup_iters",
"benchmark_iters",
"max_benchmark_duration",
"return_mode",
"grad_to_none",
"is_vetted_benchmarking"
] | float | list[float] | true | 12 | 7.84 | pytorch/pytorch | 96,034 | google | false |
maybeValidatePositionForCurrentLeader | public synchronized boolean maybeValidatePositionForCurrentLeader(ApiVersions apiVersions,
TopicPartition tp,
Metadata.LeaderAndEpoch leaderAndEpoch) {
TopicPartitionState ... | Enter the offset validation state if the leader for this partition is known to support a usable version of the
OffsetsForLeaderEpoch API. If the leader node does not support the API, simply complete the offset validation.
@param apiVersions supported API versions
@param tp topic partition to validate
@param leaderAndEp... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java | 542 | [
"apiVersions",
"tp",
"leaderAndEpoch"
] | true | 5 | 7.76 | apache/kafka | 31,560 | javadoc | false | |
of | @SuppressWarnings("unchecked")
static <T> BindResult<T> of(@Nullable T value) {
if (value == null) {
return (BindResult<T>) UNBOUND;
}
return new BindResult<>(value);
} | Return the object that was bound, or throw an exception to be created by the
provided supplier if no value has been bound.
@param <X> the type of the exception to be thrown
@param exceptionSupplier the supplier which will return the exception to be thrown
@return the present value
@throws X if there is no value present | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindResult.java | 150 | [
"value"
] | true | 2 | 7.76 | spring-projects/spring-boot | 79,428 | javadoc | false | |
clearInFlightCorrelationId | private void clearInFlightCorrelationId() {
inFlightRequestCorrelationId = NO_INFLIGHT_REQUEST_CORRELATION_ID;
} | Returns the first inflight sequence for a given partition. This is the base sequence of an inflight batch with
the lowest sequence number.
@return the lowest inflight sequence if the transaction manager is tracking inflight requests for this partition.
If there are no inflight requests being tracked for this pa... | java | clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java | 979 | [] | void | true | 1 | 6.64 | apache/kafka | 31,560 | javadoc | false |
unmodifiableOrNull | private static <K extends @Nullable Object, V extends @Nullable Object>
@Nullable Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, ? extends V> entry) {
return (entry == null) ? null : unmodifiableEntry(entry);
} | Returns an unmodifiable view of the specified navigable map. Query operations on the returned
map read through to the specified map, and attempts to modify the returned map, whether direct
or via its views, result in an {@code UnsupportedOperationException}.
<p>The returned navigable map will be serializable if the spe... | java | android/guava/src/com/google/common/collect/Maps.java | 3,306 | [
"entry"
] | true | 2 | 7.84 | google/guava | 51,352 | javadoc | false | |
_try_get_metadata_from_dynamo | def _try_get_metadata_from_dynamo(
mod: torch.nn.Module,
param_keys: KeysView[str],
full_args_num: int,
full_args_descs: list[DifferentiableAOTInput],
) -> tuple[Optional[list[torch._guards.Source]], list[int]]:
"""
Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModu... | Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModule.
We first verify that `mod` does come from Dynamo, then we handle cases where
metadata might be missing.
Returns:
aot_autograd_arg_pos_to_source: used to dedup params and their guards
static_input_indices: used to identify stati... | python | torch/_functorch/_aot_autograd/frontend_utils.py | 111 | [
"mod",
"param_keys",
"full_args_num",
"full_args_descs"
] | tuple[Optional[list[torch._guards.Source]], list[int]] | true | 11 | 7.52 | pytorch/pytorch | 96,034 | unknown | false |
quantile | @Override
public double quantile(double q) {
if (q < 0 || q > 1) {
throw new IllegalArgumentException("q should be in [0,1], got " + q);
}
AVLGroupTree values = summary;
if (values.isEmpty()) {
// no centroids means no data, no way to get a quantile
... | @param q The quantile desired. Can be in the range [0,1].
@return The minimum value x such that we think that the proportion of samples is ≤ x is q. | java | libs/tdigest/src/main/java/org/elasticsearch/tdigest/AVLTreeDigest.java | 294 | [
"q"
] | true | 11 | 8.32 | elastic/elasticsearch | 75,680 | javadoc | false | |
isEmpty | function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
... | Checks if `value` is an empty object, collection, map, or set.
Objects are considered empty if they have no own enumerable string keyed
properties.
Array-like values such as `arguments` objects, arrays, buffers, strings, or
jQuery-like collections are considered empty if they have a `length` of `0`.
Similarly, maps and... | javascript | lodash.js | 11,586 | [
"value"
] | false | 13 | 7.68 | lodash/lodash | 61,490 | jsdoc | false | |
drainUninterruptibly | @CanIgnoreReturnValue
@J2ktIncompatible
@GwtIncompatible // BlockingQueue
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <E> int drainUninterruptibly(
BlockingQueue<E> q,
Collection<? super E> buffer,
int numElements,
long timeout,
TimeUnit unit) ... | Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
with a different behavior in case it is interrupted while waiting. In that case, the operation
will continue as usual, and in the end the thread's interruption status will be set (no {@code
InterruptedException} is thrown).
@pa... | java | android/guava/src/com/google/common/collect/Queues.java | 384 | [
"q",
"buffer",
"numElements",
"timeout",
"unit"
] | true | 7 | 7.76 | google/guava | 51,352 | javadoc | false | |
consumingIterator | public static <T extends @Nullable Object> Iterator<T> consumingIterator(Iterator<T> iterator) {
checkNotNull(iterator);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
@ParametricNullness
public T ne... | Returns a view of the supplied {@code iterator} that removes each element from the supplied
{@code iterator} as it is returned.
<p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
will fail on the first call to {@code next}. The returned {@link Iterator} is also not
thread-safe... | java | android/guava/src/com/google/common/collect/Iterators.java | 997 | [
"iterator"
] | true | 1 | 6.88 | google/guava | 51,352 | javadoc | false | |
calendarToZonedDateTime | private static ZonedDateTime calendarToZonedDateTime(Calendar source) {
if (source instanceof GregorianCalendar gc) {
return gc.toZonedDateTime();
}
else {
return Instant.ofEpochMilli(source.getTimeInMillis()).atZone(source.getTimeZone().toZoneId());
}
} | Install the converters into the converter registry.
@param registry the converter registry | java | spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeConverters.java | 79 | [
"source"
] | ZonedDateTime | true | 2 | 6.4 | spring-projects/spring-framework | 59,386 | javadoc | false |
addMetricIfAbsent | public KafkaMetric addMetricIfAbsent(MetricName metricName, MetricConfig config, MetricValueProvider<?> metricValueProvider) {
KafkaMetric metric = new KafkaMetric(new Object(),
Objects.requireNonNull(metricName),
Objects.requireNonNull(metricValueProvider),
confi... | Create or get an existing metric to monitor an object that implements MetricValueProvider.
This metric won't be associated with any sensor. This is a way to expose existing values as metrics.
This method takes care of synchronisation while updating/accessing metrics by concurrent threads.
@param metricName The name of ... | java | clients/src/main/java/org/apache/kafka/common/metrics/Metrics.java | 531 | [
"metricName",
"config",
"metricValueProvider"
] | KafkaMetric | true | 3 | 7.76 | apache/kafka | 31,560 | javadoc | false |
calculateNextColorValue | function calculateNextColorValue(
srcValue: ColorValue,
targetValue: ColorValue,
changeRate: number,
): ColorValue {
const nextColor: (string | number)[] = [srcValue.value[0]];
// Skip the first element since it represents the type.
for (let i = 1; i < targetValue.value.length; i++) {
const srcChannel ... | Calculate the next `CssPropertyValue` based on the source and a target one.
@param srcValue The source value
@param targetValue The target values (it's either the final or the initial value)
@param changeRate The change rate relative to the target (i.e. 1 = target value; 0 = source value)
@returns The newly generated v... | typescript | adev/src/app/features/home/animation/calculations/calc-css-value.ts | 98 | [
"srcValue",
"targetValue",
"changeRate"
] | true | 2 | 8.08 | angular/angular | 99,544 | jsdoc | false | |
sum | def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
"""
Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.ndarray.sum : corre... | Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.ndarray.sum : corresponding function for ndarrays
numpy.sum : equivalent function
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[1,2... | python | numpy/ma/core.py | 5,196 | [
"self",
"axis",
"dtype",
"out",
"keepdims"
] | false | 7 | 6.08 | numpy/numpy | 31,054 | unknown | false | |
open | public static ZipContent open(Path path) throws IOException {
return open(new Source(path.toAbsolutePath(), null));
} | Open {@link ZipContent} from the specified path. The resulting {@link ZipContent}
<em>must</em> be {@link #close() closed} by the caller.
@param path the zip path
@return a {@link ZipContent} instance
@throws IOException on I/O error | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java | 360 | [
"path"
] | ZipContent | true | 1 | 6.64 | spring-projects/spring-boot | 79,428 | javadoc | false |
get_waiter | def get_waiter(
self,
waiter_name: str,
parameters: dict[str, str] | None = None,
config_overrides: dict[str, Any] | None = None,
deferrable: bool = False,
client=None,
) -> Waiter:
"""
Get a waiter by name.
First checks if there is a custom w... | Get a waiter by name.
First checks if there is a custom waiter with the provided waiter_name and
uses that if it exists, otherwise it will check the service client for a
waiter that matches the name and pass that through.
If `deferrable` is True, the waiter will be an AIOWaiter, generated from the
client that is pass... | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/base_aws.py | 959 | [
"self",
"waiter_name",
"parameters",
"config_overrides",
"deferrable",
"client"
] | Waiter | true | 10 | 7.04 | apache/airflow | 43,597 | sphinx | false |
handshake | @Override
public void handshake() throws IOException {
if (state == State.NOT_INITIALIZED) {
try {
startHandshake();
} catch (SSLException e) {
maybeProcessHandshakeFailure(e, false, null);
}
}
if (ready())
throw... | Performs SSL handshake, non blocking.
Before application data (kafka protocols) can be sent client & kafka broker must
perform ssl handshake.
During the handshake SSLEngine generates encrypted data that will be transported over socketChannel.
Each SSLEngine operation generates SSLEngineResult , of which SSLEngineResult... | java | clients/src/main/java/org/apache/kafka/common/network/SslTransportLayer.java | 279 | [] | void | true | 12 | 6.4 | apache/kafka | 31,560 | javadoc | false |
writeBytesTo | @CanIgnoreReturnValue
public int writeBytesTo(byte[] dest, int offset, int maxLength) {
maxLength = min(maxLength, bits() / 8);
Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length);
writeBytesToImpl(dest, offset, maxLength);
return maxLength;
} | Copies bytes from this hash code into {@code dest}.
@param dest the byte array into which the hash code will be written
@param offset the start offset in the data
@param maxLength the maximum number of bytes to write
@return the number of bytes written to {@code dest}
@throws IndexOutOfBoundsException if there is not e... | java | android/guava/src/com/google/common/hash/HashCode.java | 83 | [
"dest",
"offset",
"maxLength"
] | true | 1 | 6.72 | google/guava | 51,352 | javadoc | false | |
construct_from_string | def construct_from_string(cls, string: str_type) -> DatetimeTZDtype:
"""
Construct a DatetimeTZDtype from a string.
Parameters
----------
string : str
The string alias for this DatetimeTZDtype.
Should be formatted like ``datetime64[ns, <tz>]``,
... | Construct a DatetimeTZDtype from a string.
Parameters
----------
string : str
The string alias for this DatetimeTZDtype.
Should be formatted like ``datetime64[ns, <tz>]``,
where ``<tz>`` is the timezone name.
Examples
--------
>>> DatetimeTZDtype.construct_from_string("datetime64[ns, UTC]")
datetime64[ns,... | python | pandas/core/dtypes/dtypes.py | 872 | [
"cls",
"string"
] | DatetimeTZDtype | true | 3 | 8.16 | pandas-dev/pandas | 47,362 | numpy | false |
_list_keys_async | async def _list_keys_async(
self,
client: AioBaseClient,
bucket_name: str | None = None,
prefix: str | None = None,
delimiter: str | None = None,
page_size: int | None = None,
max_items: int | None = None,
) -> list[str]:
"""
List keys in a buc... | List keys in a bucket under prefix and not containing delimiter.
:param bucket_name: the name of the bucket
:param prefix: a key prefix
:param delimiter: the delimiter marks key hierarchy.
:param page_size: pagination size
:param max_items: maximum items to return
:return: a list of matched keys | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py | 664 | [
"self",
"client",
"bucket_name",
"prefix",
"delimiter",
"page_size",
"max_items"
] | list[str] | true | 7 | 8.08 | apache/airflow | 43,597 | sphinx | false |
of | static Option of(String name, String valueDescription, String description) {
return new Option(name, valueDescription, description, false);
} | Factory method to create value option.
@param name the name of the option
@param valueDescription a description of the expected value
@param description a description of the option
@return a new {@link Option} instance | java | loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/Command.java | 369 | [
"name",
"valueDescription",
"description"
] | Option | true | 1 | 6.48 | spring-projects/spring-boot | 79,428 | javadoc | false |
_register_lowering | def _register_lowering(
aten_fn,
decomp_fn: Callable[..., Any],
broadcast: bool,
type_promotion_kind: Optional[ELEMENTWISE_TYPE_PROMOTION_KIND],
convert_input_to_bool: bool,
lowering_dict: dict[Union[Callable[..., Any], str], Callable[..., Any]],
):
"""
Add a lowering to lowerings dict
... | Add a lowering to lowerings dict
Arguments:
aten_fn: torch.ops.aten.* fn we are lowering
decomp_fn: alternate implementation on our IR
broadcast: True to apply broadcasting to tensor inputs
type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion
convert_... | python | torch/_inductor/lowering.py | 474 | [
"aten_fn",
"decomp_fn",
"broadcast",
"type_promotion_kind",
"convert_input_to_bool",
"lowering_dict"
] | true | 6 | 6.08 | pytorch/pytorch | 96,034 | google | false | |
_derive_colors | def _derive_colors(
*,
color: Color | Collection[Color] | None,
colormap: str | Colormap | None,
color_type: str,
num_colors: int,
) -> list[Color]:
"""
Derive colors from either `colormap`, `color_type` or `color` inputs.
Get a list of colors either from `colormap`, or from `color`,
... | Derive colors from either `colormap`, `color_type` or `color` inputs.
Get a list of colors either from `colormap`, or from `color`,
or from `color_type` (if both `colormap` and `color` are None).
Parameters
----------
color : str or sequence, optional
Color(s) to be used for deriving sequence of colors.
Can b... | python | pandas/plotting/_matplotlib/style.py | 111 | [
"color",
"colormap",
"color_type",
"num_colors"
] | list[Color] | true | 6 | 6.72 | pandas-dev/pandas | 47,362 | numpy | false |
createValues | @SuppressWarnings("unchecked")
@Override
ImmutableCollection<V> createValues() {
return (ImmutableList<V>) new KeysOrValuesAsList(alternatingKeysAndValues, 1, size);
} | Returns a hash table for the specified keys and values, and ensures that neither keys nor
values are null. This method may update {@code alternatingKeysAndValues} if there are duplicate
keys. If so, the return value will indicate how many entries are still valid, and will also
include a {@link Builder.DuplicateKey} in ... | java | android/guava/src/com/google/common/collect/RegularImmutableMap.java | 568 | [] | true | 1 | 6.88 | google/guava | 51,352 | javadoc | false | |
compare | public static int compare(byte a, byte b) {
return toUnsignedInt(a) - toUnsignedInt(b);
} | Compares the two specified {@code byte} values, treating them as unsigned values between 0 and
255 inclusive. For example, {@code (byte) -127} is considered greater than {@code (byte) 127}
because it is seen as having the value of positive {@code 129}.
@param a the first {@code byte} to compare
@param b the second {@co... | java | android/guava/src/com/google/common/primitives/UnsignedBytes.java | 130 | [
"a",
"b"
] | true | 1 | 6.64 | google/guava | 51,352 | javadoc | false | |
contains | @Override
public boolean contains(@Nullable Class<?> exClass) {
if (super.contains(exClass)) {
return true;
}
if (this.relatedCauses != null) {
for (Throwable relatedCause : this.relatedCauses) {
if (relatedCause instanceof NestedRuntimeException nested && nested.contains(exClass)) {
return true;
... | 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 | 195 | [
"exClass"
] | true | 5 | 7.04 | spring-projects/spring-framework | 59,386 | javadoc | false | |
isAssignable | public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
if (!ArrayUtils.isSameLength(classArray, toClassArray)) {
return false;
}
classArray = ArrayUtils.nullToEmpty(classArray);
toClassArray = ArrayUtils.nullToEmpty(toCl... | Tests whether an array of Classes can be assigned to another array of Classes.
<p>
This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in the input arrays. It can be
used to check if a set of arguments (the first parameter) are suitably compatible with a set of method parameter
types ... | java | src/main/java/org/apache/commons/lang3/ClassUtils.java | 1,460 | [
"classArray",
"toClassArray",
"autoboxing"
] | true | 4 | 7.92 | apache/commons-lang | 2,896 | javadoc | false | |
_get_feature_index | def _get_feature_index(fx, feature_names=None):
"""Get feature index.
Parameters
----------
fx : int or str
Feature index or name.
feature_names : list of str, default=None
All feature names from which to search the indices.
Returns
-------
idx : int
Feature in... | Get feature index.
Parameters
----------
fx : int or str
Feature index or name.
feature_names : list of str, default=None
All feature names from which to search the indices.
Returns
-------
idx : int
Feature index. | python | sklearn/inspection/_pd_utils.py | 40 | [
"fx",
"feature_names"
] | false | 3 | 6.08 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
isCreatable | public static boolean isCreatable(final String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
final char[] chars = str.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
... | Checks whether the String is a valid Java number.
<p>
Valid numbers include hexadecimal marked with the {@code 0x} or {@code 0X} qualifier, octal numbers, scientific notation and numbers marked with a type
qualifier (e.g. 123L).
</p>
<p>
Non-hexadecimal strings beginning with a leading zero are treated as octal values.... | java | src/main/java/org/apache/commons/lang3/math/NumberUtils.java | 555 | [
"str"
] | true | 45 | 6.8 | apache/commons-lang | 2,896 | javadoc | false | |
getLastType | function getLastType(stack: ProcessorState['measureStack']) {
if (stack.length > 0) {
const {type} = stack[stack.length - 1];
return type;
}
return null;
} | Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@flow | javascript | packages/react-devtools-timeline/src/import-worker/preprocessData.js | 127 | [] | false | 2 | 6.24 | facebook/react | 241,750 | jsdoc | false | |
setSortTextToOptionalMember | function setSortTextToOptionalMember() {
symbols.forEach(m => {
if (m.flags & SymbolFlags.Optional) {
const symbolId = getSymbolId(m);
symbolToSortTextMap[symbolId] = symbolToSortTextMap[symbolId] ?? SortText.OptionalMember;
}
});
} | Filters out completion suggestions for named imports or exports.
@returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
do not occur at the current position and have not otherwise been typed. | typescript | src/services/completions.ts | 5,194 | [] | false | 2 | 6.96 | microsoft/TypeScript | 107,154 | jsdoc | false | |
batchIterator | @Override
public AbstractIterator<FileChannelRecordBatch> batchIterator() {
return batchIterator(start);
} | Get an iterator over the record batches in the file, starting at a specific position. This is similar to
{@link #batches()} except that callers specify a particular position to start reading the batches from. This
method must be used with caution: the start position passed in must be a known start of a batch.
@param st... | java | clients/src/main/java/org/apache/kafka/common/record/FileRecords.java | 429 | [] | true | 1 | 6.96 | apache/kafka | 31,560 | javadoc | false | |
get | public static Binder get(Environment environment, @Nullable BindHandler defaultBindHandler) {
Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
PropertySourcesPlaceholdersResolver placeholdersResolver = new PropertySourcesPlaceholdersResolver(environment);
return new B... | Create a new {@link Binder} instance from the specified environment.
@param environment the environment source (must have attached
{@link ConfigurationPropertySources})
@param defaultBindHandler the default bind handler to use if none is specified when
binding
@return a {@link Binder} instance
@since 2.2.0 | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java | 568 | [
"environment",
"defaultBindHandler"
] | Binder | true | 1 | 6.24 | spring-projects/spring-boot | 79,428 | javadoc | false |
visitVariableDeclaration | function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
const ancestorFacts = enterSubtree(HierarchyFacts.ExportedVariableStatement, HierarchyFacts.None);
let updated: VisitResult<VariableDeclaration>;
if (isBindingPattern(node.name)) {
up... | Visits a VariableDeclaration node with a binding pattern.
@param node A VariableDeclaration node. | typescript | src/compiler/transformers/es2015.ts | 2,914 | [
"node"
] | true | 3 | 6.4 | microsoft/TypeScript | 107,154 | jsdoc | false | |
addContextDataPairs | private static void addContextDataPairs(ContextPairs.Pairs<ReadOnlyStringMap> contextPairs) {
contextPairs.add((contextData, pairs) -> contextData.forEach(pairs::accept));
} | Converts the log4j2 event level to the Syslog event level code.
@param event the log event
@return an integer representing the syslog log level code
@see Severity class from Log4j2 which contains the conversion logic | java | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/GraylogExtendedLogFormatStructuredLogFormatter.java | 142 | [
"contextPairs"
] | void | true | 1 | 6.8 | spring-projects/spring-boot | 79,428 | javadoc | false |
ceiling | public static Calendar ceiling(final Calendar calendar, final int field) {
Objects.requireNonNull(calendar, "calendar");
return modify((Calendar) calendar.clone(), field, ModifyType.CEILING);
} | Gets a date ceiling, leaving the field specified as the most
significant field.
<p>For example, if you had the date-time of 28 Mar 2002
13:45:01.231, if you passed with HOUR, it would return 28 Mar
2002 14:00:00.000. If this was passed with MONTH, it would
return 1 Apr 2002 0:00:00.000.</p>
@param calendar the date t... | java | src/main/java/org/apache/commons/lang3/time/DateUtils.java | 348 | [
"calendar",
"field"
] | Calendar | true | 1 | 6.64 | apache/commons-lang | 2,896 | javadoc | false |
apply_over_axes | def apply_over_axes(func, a, axes):
"""
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has... | Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension is inserted before
`ax... | python | numpy/lib/_shape_base_impl.py | 422 | [
"func",
"a",
"axes"
] | false | 8 | 7.6 | numpy/numpy | 31,054 | numpy | false | |
hermmulx | def hermmulx(c):
"""Multiply a Hermite series by x.
Multiply the Hermite series `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
... | Multiply a Hermite series by x.
Multiply the Hermite series `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the result of the multiplication.
See Also
... | python | numpy/polynomial/hermite.py | 392 | [
"c"
] | false | 4 | 7.68 | numpy/numpy | 31,054 | numpy | false | |
put | private @Nullable V put(@ParametricNullness K key, @ParametricNullness V value, boolean force) {
int keyHash = Hashing.smearedHash(key);
int entryForKey = findEntryByKey(key, keyHash);
if (entryForKey != ABSENT) {
V oldValue = values[entryForKey];
if (Objects.equals(oldValue, value)) {
r... | Returns {@code true} if this BiMap contains an entry whose value is equal to {@code value} (or,
equivalently, if this inverse view contains a key that is equal to {@code value}).
<p>Due to the property that values in a BiMap are unique, this will tend to execute in
faster-than-linear time.
@param value the object to se... | java | android/guava/src/com/google/common/collect/HashBiMap.java | 287 | [
"key",
"value",
"force"
] | V | true | 5 | 7.92 | google/guava | 51,352 | javadoc | false |
now | private static <E extends Throwable> Instant now(final FailableConsumer<Instant, E> nowConsumer) throws E {
final Instant start = Instant.now();
nowConsumer.accept(start);
return start;
} | Tests whether the given Duration is positive (duration > 0).
@param duration the value to test
@return whether the given Duration is positive (duration > 0). | java | src/main/java/org/apache/commons/lang3/time/DurationUtils.java | 153 | [
"nowConsumer"
] | Instant | true | 1 | 6.88 | apache/commons-lang | 2,896 | javadoc | false |
arctanh | def arctanh(x):
"""
Compute the inverse hyperbolic tangent of `x`.
Return the "principal value" (for a description of this, see
`numpy.arctanh`) of ``arctanh(x)``. For real `x` such that
``abs(x) < 1``, this is a real number. If `abs(x) > 1`, or if `x` is
complex, the result is complex. Finall... | Compute the inverse hyperbolic tangent of `x`.
Return the "principal value" (for a description of this, see
`numpy.arctanh`) of ``arctanh(x)``. For real `x` such that
``abs(x) < 1``, this is a real number. If `abs(x) > 1`, or if `x` is
complex, the result is complex. Finally, `x = 1` returns``inf`` and
``x=-1`` retur... | python | numpy/lib/_scimath_impl.py | 591 | [
"x"
] | false | 1 | 6 | numpy/numpy | 31,054 | numpy | false | |
visitFunctionDeclaration | function visitFunctionDeclaration(node: FunctionDeclaration): FunctionDeclaration {
const savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
const ancestorFacts = enterSubtree(HierarchyFacts.FunctionExcludes, HierarchyFacts.FunctionIncludes);
const paramete... | Visits a FunctionDeclaration node.
@param node a FunctionDeclaration node. | typescript | src/compiler/transformers/es2015.ts | 2,481 | [
"node"
] | true | 2 | 6.24 | microsoft/TypeScript | 107,154 | jsdoc | false | |
nullToEmpty | public static int[] nullToEmpty(final int[] array) {
return isEmpty(array) ? EMPTY_INT_ARRAY : array;
} | Defensive programming technique to change a {@code null}
reference to an empty one.
<p>
This method returns an empty array for a {@code null} input array.
</p>
<p>
As a memory optimizing technique an empty array passed in will be overridden with
the empty {@code public static} references in this class.
</p>
@param arra... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 4,489 | [
"array"
] | true | 2 | 8.16 | apache/commons-lang | 2,896 | javadoc | false | |
findGulpCommand | async function findGulpCommand(rootPath: string): Promise<string> {
const platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath, 'node_modules', '.bin', 'gulp.cmd'))) {
const globalGulp = path.join(process.env.APPDATA ? process.env.APPDATA : '', 'npm', 'gulp.cmd');
if (await ex... | Check if the given filename is a file.
If returns false in case the file does not exist or
the file stats cannot be accessed/queried or it
is no file at all.
@param filename
the filename to the checked
@returns
true in case the file exists, in any other case false. | typescript | extensions/gulp/src/main.ts | 89 | [
"rootPath"
] | true | 8 | 7.92 | microsoft/vscode | 179,840 | jsdoc | true | |
findUrlsInClasspath | private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
} | Loads the relocations from the classpath. Relocations are stored in files named
{@code META-INF/spring/full-qualified-annotation-name.replacements} on the
classpath. The file is loaded using {@link Properties#load(java.io.InputStream)}
with each entry containing an auto-configuration class name as the key and the
repla... | java | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationReplacements.java | 113 | [
"classLoader",
"location"
] | true | 2 | 7.44 | spring-projects/spring-boot | 79,428 | javadoc | false | |
includes | def includes(self, x):
"""Test whether all values of x are in interval range.
Parameters
----------
x : ndarray
Array whose elements are tested to be in interval range.
Returns
-------
result : bool
"""
if self.low_inclusive:
... | Test whether all values of x are in interval range.
Parameters
----------
x : ndarray
Array whose elements are tested to be in interval range.
Returns
-------
result : bool | python | sklearn/_loss/link.py | 32 | [
"self",
"x"
] | false | 6 | 6.08 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
indexesOf | public static BitSet indexesOf(final long[] array, final long valueToFind) {
return indexesOf(array, valueToFind, 0);
} | Finds the indices of the given value in the array.
<p>This method returns an empty BitSet for a {@code null} input array.</p>
@param array the array to search for the object, may be {@code null}.
@param valueToFind the value to find.
@return a BitSet of all the indices of the value within the array,
an empty BitSet ... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 2,232 | [
"array",
"valueToFind"
] | BitSet | true | 1 | 6.8 | apache/commons-lang | 2,896 | javadoc | false |
toString | @Override
public String toString() {
StringBuilder bld = new StringBuilder();
if (sessionId == INVALID_SESSION_ID) {
bld.append("(sessionId=INVALID, ");
} else {
bld.append("(sessionId=").append(sessionId).append(", ");
}
if (epoch == INITIAL_EPOCH) {
... | Return the metadata for the next incremental response. | java | clients/src/main/java/org/apache/kafka/common/requests/FetchMetadata.java | 146 | [] | String | true | 4 | 6.88 | apache/kafka | 31,560 | javadoc | false |
toArray | public static long[] toArray(Collection<? extends Number> collection) {
if (collection instanceof LongArrayAsList) {
return ((LongArrayAsList) collection).toLongArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
long[] array = new long[len];
for (int i = 0... | Returns an array containing each value of {@code collection}, converted to a {@code long} value
in the manner of {@link Number#longValue}.
<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 collecti... | java | android/guava/src/com/google/common/primitives/Longs.java | 677 | [
"collection"
] | true | 3 | 8.08 | google/guava | 51,352 | javadoc | false | |
get_engine | def get_engine():
"""Get the configured engine, raising an error if not configured."""
if engine is None:
raise RuntimeError("Engine not configured. Call configure_orm() first.")
return engine | Get the configured engine, raising an error if not configured. | python | airflow-core/src/airflow/settings.py | 142 | [] | false | 2 | 6.08 | apache/airflow | 43,597 | unknown | false | |
sampleVariance | public double sampleVariance() {
checkState(count > 1);
if (isNaN(sumOfSquaresOfDeltas)) {
return NaN;
}
return ensureNonNegative(sumOfSquaresOfDeltas) / (count - 1);
} | Returns the <a href="http://en.wikipedia.org/wiki/Variance#Sample_variance">unbiased sample
variance</a> of the values. If this dataset is a sample drawn from a population, this is an
unbiased estimator of the population variance of the population. The count must be greater than
one.
<p>This is not guaranteed to return... | java | android/guava/src/com/google/common/math/Stats.java | 341 | [] | true | 2 | 6.24 | google/guava | 51,352 | javadoc | false | |
load | @Nullable ConfigData load(ConfigDataLoaderContext context, R resource)
throws IOException, ConfigDataResourceNotFoundException; | Load {@link ConfigData} for the given resource.
@param context the loader context
@param resource the resource to load
@return the loaded config data or {@code null} if the location should be skipped
@throws IOException on IO error
@throws ConfigDataResourceNotFoundException if the resource cannot be found | java | core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLoader.java | 66 | [
"context",
"resource"
] | ConfigData | true | 1 | 6.32 | spring-projects/spring-boot | 79,428 | javadoc | false |
getBean | @Override
public Object getBean(String name, @Nullable Object @Nullable ... args) throws BeansException {
if (!ObjectUtils.isEmpty(args)) {
throw new UnsupportedOperationException(
"StaticListableBeanFactory does not support explicit bean creation arguments");
}
return getBean(name);
} | Add a new singleton bean.
<p>Will overwrite any existing instance for the given name.
@param name the name of the bean
@param bean the bean instance | java | spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java | 152 | [
"name"
] | Object | true | 2 | 6.88 | spring-projects/spring-framework | 59,386 | javadoc | false |
groupSubscribe | synchronized boolean groupSubscribe(Collection<String> topics) {
if (!hasAutoAssignedPartitions())
throw new IllegalStateException(SUBSCRIPTION_EXCEPTION_MESSAGE);
groupSubscription = new HashSet<>(topics);
return !subscription.containsAll(groupSubscription);
} | Set the current group subscription. This is used by the group leader to ensure
that it receives metadata updates for all topics that the group is interested in.
@param topics All topics from the group subscription
@return true if the group subscription contains topics which are not part of the local subscription | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java | 239 | [
"topics"
] | true | 2 | 8.24 | apache/kafka | 31,560 | javadoc | false | |
_split_line | def _split_line(s: str, parts):
"""
Parameters
----------
s: str
Fixed-length string to split
parts: list of (name, length) pairs
Used to break up string, name '_' will be filtered from output.
Returns
-------
Dict of name:contents of string at given location.
"""
... | Parameters
----------
s: str
Fixed-length string to split
parts: list of (name, length) pairs
Used to break up string, name '_' will be filtered from output.
Returns
-------
Dict of name:contents of string at given location. | python | pandas/io/sas/sas_xport.py | 138 | [
"s",
"parts"
] | true | 2 | 6.72 | pandas-dev/pandas | 47,362 | numpy | false | |
escapeSlow | protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = Platform.charBufferFromThreadLocal();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, inde... | Returns the escaped form of a given literal string, starting at the given index. This method is
called by the {@link #escape(String)} method when it discovers that escaping is required. It is
protected to allow subclasses to override the fastpath escaping function to inline their
escaping test. See {@link CharEscaperBu... | java | android/guava/src/com/google/common/escape/UnicodeEscaper.java | 157 | [
"s",
"index"
] | String | true | 10 | 8 | google/guava | 51,352 | javadoc | false |
_terminate_process_tree | def _terminate_process_tree(
process: subprocess.Popen[bytes],
timeout: int = 5,
force_kill_remaining: bool = True,
) -> None:
"""
Terminate a process and all its children recursively.
Uses psutil to ensure all child processes are properly terminated,
which is important for cleaning up subp... | Terminate a process and all its children recursively.
Uses psutil to ensure all child processes are properly terminated,
which is important for cleaning up subprocesses like serve-log servers.
:param process: The subprocess.Popen process to terminate
:param timeout: Timeout in seconds to wait for graceful termination... | python | airflow-core/src/airflow/cli/hot_reload.py | 71 | [
"process",
"timeout",
"force_kill_remaining"
] | None | true | 5 | 6.64 | apache/airflow | 43,597 | sphinx | false |
descendingEntryIterator | @Override
Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() {
if (restriction.isEmpty()) {
return emptyIterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBou... | restriction is the subRangeSet view; ranges are truncated to their intersection with
restriction. | java | android/guava/src/com/google/common/collect/TreeRangeSet.java | 816 | [] | true | 5 | 6.08 | google/guava | 51,352 | javadoc | false | |
scanSourceCharacter | function scanSourceCharacter(): string {
const size = anyUnicodeMode ? charSize(codePointChecked(pos)) : 1;
pos += size;
return size > 0 ? text.substring(pos - size, pos) : "";
} | A stack of scopes for named capturing groups. @see {scanGroupName} | typescript | src/compiler/scanner.ts | 3,568 | [] | true | 3 | 6.4 | microsoft/TypeScript | 107,154 | jsdoc | false | |
isArrayIndex | function isArrayIndex(key) {
const keyNum = +key;
if (`${keyNum}` !== key) { return false; }
return keyNum >= 0 && keyNum < 0xFFFF_FFFF;
} | Checks if the given key is a valid array index.
@param {string} key - The key to check.
@returns {boolean} - Returns `true` if the key is a valid array index, else `false`. | javascript | lib/internal/modules/esm/resolve.js | 461 | [
"key"
] | false | 3 | 6.24 | nodejs/node | 114,839 | jsdoc | false | |
appendSeparator | public StrBuilder appendSeparator(final char separator, final int loopIndex) {
if (loopIndex > 0) {
append(separator);
}
return this;
} | Appends a separator to the builder if the loop index is greater than zero.
The separator is appended using {@link #append(char)}.
<p>
This method is useful for adding a separator each time around the
loop except the first.
</p>
<pre>{@code
for (int i = 0; i < list.size(); i++) {
appendSeparator(",", i);
append(list... | java | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | 1,268 | [
"separator",
"loopIndex"
] | StrBuilder | true | 2 | 7.92 | apache/commons-lang | 2,896 | javadoc | false |
handleCause | public static void handleCause(final ExecutionException ex) throws ConcurrentException {
final ConcurrentException cause = extractCause(ex);
if (cause != null) {
throw cause;
}
} | Handles the specified {@link ExecutionException}. This method calls
{@link #extractCause(ExecutionException)} for obtaining the cause of the
exception - which might already cause an unchecked exception or an error
being thrown. If the cause is a checked exception however, it is wrapped
in a {@link ConcurrentException},... | java | src/main/java/org/apache/commons/lang3/concurrent/ConcurrentUtils.java | 247 | [
"ex"
] | void | true | 2 | 6.72 | apache/commons-lang | 2,896 | javadoc | false |
value | @SuppressWarnings("unchecked")
public T value() {
if (!succeeded())
throw new IllegalStateException("Attempt to retrieve value from future which hasn't successfully completed");
return (T) result.get();
} | Get the value corresponding to this request (only available if the request succeeded)
@return the value set in {@link #complete(Object)}
@throws IllegalStateException if the future is not complete or failed | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestFuture.java | 71 | [] | T | true | 2 | 7.12 | apache/kafka | 31,560 | javadoc | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.