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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
getAllInterfaces | private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
while (cls != null) {
final Class<?>[] interfaces = cls.getInterfaces();
for (final Class<?> i : interfaces) {
if (interfacesFound.add(i)) {
getAllInterfaces(... | Gets the interfaces for the specified class.
@param cls the class to look up, may be {@code null}.
@param interfacesFound the {@link Set} of interfaces for the class. | java | src/main/java/org/apache/commons/lang3/ClassUtils.java | 386 | [
"cls",
"interfacesFound"
] | void | true | 3 | 6.88 | apache/commons-lang | 2,896 | javadoc | false |
abbreviateMiddle | public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isAnyEmpty(str, middle) || length >= str.length() || length < middle.length() + 2) {
return str;
}
final int targetString = length - middle.length();
final int startOffset = t... | Abbreviates a String to the length passed, replacing the middle characters with the supplied replacement String.
<p>
This abbreviation only occurs if the following criteria is met:
</p>
<ul>
<li>Neither the String for abbreviation nor the replacement String are null or empty</li>
<li>The length to truncate to is less t... | java | src/main/java/org/apache/commons/lang3/StringUtils.java | 419 | [
"str",
"middle",
"length"
] | String | true | 4 | 7.92 | apache/commons-lang | 2,896 | javadoc | false |
newConnections | private NetworkConnections<N, E> newConnections() {
return isDirected()
? allowsParallelEdges()
? DirectedMultiNetworkConnections.<N, E>of()
: DirectedNetworkConnections.<N, E>of()
: allowsParallelEdges()
? UndirectedMultiNetworkConnections.<N, E>of()
... | Adds {@code node} to the graph and returns the associated {@link NetworkConnections}.
@throws IllegalStateException if {@code node} is already present | java | android/guava/src/com/google/common/graph/StandardMutableNetwork.java | 166 | [] | true | 4 | 6.08 | google/guava | 51,352 | javadoc | false | |
masked_invalid | def masked_invalid(a, copy=True):
"""
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to ``masked_where``, with
`condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
Only applies to arrays with a dtype where NaNs or infs make sense
(i.e. float... | Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to ``masked_where``, with
`condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
Only applies to arrays with a dtype where NaNs or infs make sense
(i.e. floating point types), but accepts any array_like object.
See Also... | python | numpy/ma/core.py | 2,389 | [
"a",
"copy"
] | false | 2 | 7.84 | numpy/numpy | 31,054 | unknown | false | |
getProxyImports | private String[] getProxyImports() {
List<String> result = new ArrayList<>(3);
result.add(AutoProxyRegistrar.class.getName());
result.add(ProxyCachingConfiguration.class.getName());
if (JSR_107_PRESENT && JCACHE_IMPL_PRESENT) {
result.add(PROXY_JCACHE_CONFIGURATION_CLASS);
}
return StringUtils.toStringAr... | Return the imports to use if the {@link AdviceMode} is set to {@link AdviceMode#PROXY}.
<p>Take care of adding the necessary JSR-107 import if it is available. | java | spring-context/src/main/java/org/springframework/cache/annotation/CachingConfigurationSelector.java | 81 | [] | true | 3 | 6.56 | spring-projects/spring-framework | 59,386 | javadoc | false | |
get_versions | def get_versions() -> dict:
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in whi... | Get version information or return default if unable to do so. | python | pandas/_version.py | 643 | [] | dict | true | 3 | 7.04 | pandas-dev/pandas | 47,362 | unknown | false |
getLevelConfiguration | public LevelConfiguration getLevelConfiguration() {
LevelConfiguration result = getLevelConfiguration(ConfigurationScope.INHERITED);
Assert.state(result != null, "Inherited level configuration must not be null");
return result;
} | Return the level configuration, considering inherited loggers.
@return the level configuration
@since 2.7.13 | java | core/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java | 103 | [] | LevelConfiguration | true | 1 | 6.4 | spring-projects/spring-boot | 79,428 | javadoc | false |
toString | @Override
public String toString() {
return "FastDateParser[" + pattern + ", " + locale + ", " + timeZone.getID() + "]";
} | Gets a string version of this formatter.
@return a debugging string | java | src/main/java/org/apache/commons/lang3/time/FastDateParser.java | 1,114 | [] | String | true | 1 | 6.96 | apache/commons-lang | 2,896 | javadoc | false |
resolveSecureSetting | private char[] resolveSecureSetting(String key, char[] defaultValue) {
try {
char[] setting = getSecureSetting(expandSettingKey(key));
if (setting == null || setting.length == 0) {
return defaultValue;
}
return setting;
} catch (RuntimeExce... | Resolve all necessary configuration settings, and load a {@link SslConfiguration}.
@param basePath The base path to use for any settings that represent file paths. Typically points to the Elasticsearch
configuration directory.
@throws SslConfigException For any problems with the configuration, or with l... | java | libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java | 462 | [
"key",
"defaultValue"
] | true | 5 | 6.24 | elastic/elasticsearch | 75,680 | javadoc | false | |
create_ingestion | def create_ingestion(
self,
data_set_id: str,
ingestion_id: str,
ingestion_type: str,
wait_for_completion: bool = True,
check_interval: int = 30,
aws_account_id: str | None = None,
) -> dict:
"""
Create and start a new SPICE ingestion for a dat... | Create and start a new SPICE ingestion for a dataset; refresh the SPICE datasets.
.. seealso::
- :external+boto3:py:meth:`QuickSight.Client.create_ingestion`
:param data_set_id: ID of the dataset used in the ingestion.
:param ingestion_id: ID for the ingestion.
:param ingestion_type: Type of ingestion: "INCREMEN... | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/quicksight.py | 47 | [
"self",
"data_set_id",
"ingestion_id",
"ingestion_type",
"wait_for_completion",
"check_interval",
"aws_account_id"
] | dict | true | 3 | 7.44 | apache/airflow | 43,597 | sphinx | false |
checkStrictModeDeleteExpression | function checkStrictModeDeleteExpression(node: DeleteExpression) {
// Grammar checking
if (inStrictMode && node.expression.kind === SyntaxKind.Identifier) {
// When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
// UnaryExpression is a direct... | Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
@param symbolTable - The symbol table which node will be added to.
@param parent - node's parent declaration.
@param node - The declaration to be added to the symbol table
@param includes - The SymbolFlags that n... | typescript | src/compiler/binder.ts | 2,633 | [
"node"
] | false | 3 | 6.08 | microsoft/TypeScript | 107,154 | jsdoc | false | |
escapeJson | public static final String escapeJson(final String input) {
return ESCAPE_JSON.translate(input);
} | Escapes the characters in a {@link String} using Json String rules.
<p>Escapes any values it finds into their Json String form.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
<p>So a tab becomes the characters {@code '\\'} and
{@code 't'}.</p>
<p>The only difference between Java strin... | java | src/main/java/org/apache/commons/lang3/StringEscapeUtils.java | 550 | [
"input"
] | String | true | 1 | 6.96 | apache/commons-lang | 2,896 | javadoc | false |
empirical_covariance | def empirical_covariance(X, *, assume_centered=False):
"""Compute the Maximum likelihood covariance estimator.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
assume_centered : bool, default=False
If `True`, dat... | Compute the Maximum likelihood covariance estimator.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
assume_centered : bool, default=False
If `True`, data will not be centered before computation.
Useful when working with data whose mea... | python | sklearn/covariance/_empirical_covariance.py | 65 | [
"X",
"assume_centered"
] | false | 6 | 7.04 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
listClientMetricsResources | @SuppressWarnings({"deprecation", "removal"})
@Override
public ListClientMetricsResourcesResult listClientMetricsResources(ListClientMetricsResourcesOptions options) {
final long now = time.milliseconds();
final KafkaFutureImpl<Collection<ClientMetricsResourceListing>> future = new KafkaFutureIm... | Forcefully terminates an ongoing transaction for a given transactional ID.
<p>
This API is intended for well-formed but long-running transactions that are known to the
transaction coordinator. It is primarily designed for supporting 2PC (two-phase commit) workflows,
where a coordinator may need to unilaterally terminat... | java | clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java | 4,921 | [
"options"
] | ListClientMetricsResourcesResult | true | 2 | 7.44 | apache/kafka | 31,560 | javadoc | false |
_get_store_line | def _get_store_line(
self,
value: Union[str, CppCSEVariable],
var: str,
index: sympy.Expr,
dtype: torch.dtype,
accu_store: bool = False,
):
"""
Get a store line buffer that stores `value` into `var` at `index` of `dtype`. It handles
both contig... | Get a store line buffer that stores `value` into `var` at `index` of `dtype`. It handles
both contiguous and non-contiguous store cases.
:param value: Vectorized type templaterized on `dtype`.
:param var: buffer to store into.
:index: index into the `var`. | python | torch/_inductor/codegen/cpp.py | 2,906 | [
"self",
"value",
"var",
"index",
"dtype",
"accu_store"
] | true | 11 | 7.2 | pytorch/pytorch | 96,034 | sphinx | false | |
add_backward_reload_stream_ops | def add_backward_reload_stream_ops(graph: fx.Graph) -> None:
"""
Add stream operations for backward pass GPU reloading.
Pattern: fork → wait_stream → device_put → record_event → join → wait_event
This ensures that:
1. Reloading doesn't start prematurely (fork → wait_stream)
2. Reloading happen... | Add stream operations for backward pass GPU reloading.
Pattern: fork → wait_stream → device_put → record_event → join → wait_event
This ensures that:
1. Reloading doesn't start prematurely (fork → wait_stream)
2. Reloading happens on a separate stream (device_put)
3. First use waits for reload completion (record_even... | python | torch/_functorch/_activation_offloading/activation_offloading.py | 434 | [
"graph"
] | None | true | 4 | 6.8 | pytorch/pytorch | 96,034 | google | false |
put | @CanIgnoreReturnValue
@Override
public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
return super.put(key, value);
} | Stores a key-value pair in the multimap.
@param key key to store in the multimap
@param value value to store in the multimap
@return {@code true} always | java | android/guava/src/com/google/common/collect/AbstractListMultimap.java | 118 | [
"key",
"value"
] | true | 1 | 6.56 | google/guava | 51,352 | javadoc | false | |
run | protected @Nullable WebApplicationContext run(SpringApplication application) {
return (WebApplicationContext) application.run();
} | Called to run a fully configured {@link SpringApplication}.
@param application the application to run
@return the {@link WebApplicationContext} | java | core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java | 204 | [
"application"
] | WebApplicationContext | true | 1 | 6 | spring-projects/spring-boot | 79,428 | javadoc | false |
chunk | function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
... | Creates an array of elements split into groups the length of `size`.
If `array` can't be split evenly, the final chunk will be the remaining
elements.
@static
@memberOf _
@since 3.0.0
@category Array
@param {Array} array The array to process.
@param {number} [size=1] The length of each chunk
@param- {Object} [guard] En... | javascript | lodash.js | 6,942 | [
"array",
"size",
"guard"
] | false | 8 | 7.68 | lodash/lodash | 61,490 | jsdoc | false | |
isWarnEnabled | @Override
public boolean isWarnEnabled() {
synchronized (this.lines) {
return (this.destination == null) || this.destination.isWarnEnabled();
}
} | Create a new {@link DeferredLog} instance managed by a {@link DeferredLogFactory}.
@param destination the switch-over destination
@param lines the lines backing all related deferred logs
@since 2.4.0 | java | core/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java | 86 | [] | true | 2 | 6.4 | spring-projects/spring-boot | 79,428 | javadoc | false | |
found | public ItemsBuilder found(String singular, String plural) {
return new ItemsBuilder(this, "found", singular, plural);
} | Indicate that one or more results were found. For example
{@code found("bean", "beans").items("x", "y")} results in the message "found
beans x, y".
@param singular the article found in singular form
@param plural the article found in plural form
@return an {@link ItemsBuilder} | java | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java | 238 | [
"singular",
"plural"
] | ItemsBuilder | true | 1 | 6.8 | spring-projects/spring-boot | 79,428 | javadoc | false |
updateFetchPositions | public CompletableFuture<Void> updateFetchPositions(long deadlineMs) {
CompletableFuture<Void> result = new CompletableFuture<>();
try {
if (maybeCompleteWithPreviousException(result)) {
return result;
}
validatePositionsIfNeeded();
if (... | Update fetch positions for assigned partitions that do not have a position. This will:
<ul>
<li>check if all assigned partitions already have fetch positions and return right away if that's the case</li>
<li>trigger an async request to validate positions (detect log truncation)</li>
<li>fetch committed offs... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java | 235 | [
"deadlineMs"
] | true | 5 | 7.92 | apache/kafka | 31,560 | javadoc | false | |
dce_hop_extra_outputs | def dce_hop_extra_outputs(gm: torch.fx.GraphModule) -> bool:
"""
Remove unused extra outputs from HOP calls recursively.
Processes graphs top-down: first DCE the current graph's HOP outputs,
then recursively process nested subgraphs. This ensures that when we
process a nested subgraph, the parent h... | Remove unused extra outputs from HOP calls recursively.
Processes graphs top-down: first DCE the current graph's HOP outputs,
then recursively process nested subgraphs. This ensures that when we
process a nested subgraph, the parent has already removed unused getitems,
so the nested subgraph sees the correct usage inf... | python | torch/_dynamo/dce_extra_outputs.py | 35 | [
"gm"
] | bool | true | 12 | 8.08 | pytorch/pytorch | 96,034 | google | false |
standardFirstEntry | protected @Nullable Entry<E> standardFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
return Multisets.immutableEntry(entry.getElement(), entry.getCount());
} | A sensible definition of {@link #firstEntry()} in terms of {@code entrySet().iterator()}.
<p>If you override {@link #entrySet()}, you may wish to override {@link #firstEntry()} to
forward to this implementation. | java | android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java | 122 | [] | true | 2 | 6.24 | google/guava | 51,352 | javadoc | false | |
findSourceMap | function findSourceMap(sourceURL) {
if (typeof sourceURL !== 'string') {
return undefined;
}
// No source maps for builtin modules.
if (sourceURL.startsWith('node:')) {
return undefined;
}
if (!getSourceMapsSupport().nodeModules && isUnderNodeModules(sourceURL)) {
return undefined;
}
Sour... | Find a source map for a given actual source URL or path.
This function may be invoked from user code or test runner, this must not throw
any exceptions.
@param {string} sourceURL - actual source URL or path
@returns {import('internal/source_map/source_map').SourceMap | undefined} a source map or undefined if not found | javascript | lib/internal/source_map/source_map_cache.js | 369 | [
"sourceURL"
] | false | 9 | 6.24 | nodejs/node | 114,839 | jsdoc | false | |
endLoopBlock | function endLoopBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Loop);
const block = endBlock() as SwitchBlock;
const breakLabel = block.breakLabel;
if (!block.isScript) {
markLabel(breakLabel);
}
} | Ends a code block that supports `break` or `continue` statements that are defined in
generated code or in the source tree. | typescript | src/compiler/transformers/generators.ts | 2,340 | [] | true | 2 | 7.04 | microsoft/TypeScript | 107,154 | jsdoc | false | |
newLinkedHashMap | @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<>();
} | Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
<p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
<p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
use the {@code LinkedHashMap} constructor directly, taking... | java | android/guava/src/com/google/common/collect/Maps.java | 293 | [] | true | 1 | 6.08 | google/guava | 51,352 | javadoc | false | |
validate_inclusive | def validate_inclusive(inclusive: str | None) -> tuple[bool, bool]:
"""
Check that the `inclusive` argument is among {"both", "neither", "left", "right"}.
Parameters
----------
inclusive : {"both", "neither", "left", "right"}
Returns
-------
left_right_inclusive : tuple[bool, bool]
... | Check that the `inclusive` argument is among {"both", "neither", "left", "right"}.
Parameters
----------
inclusive : {"both", "neither", "left", "right"}
Returns
-------
left_right_inclusive : tuple[bool, bool]
Raises
------
ValueError : if argument is not among valid values | python | pandas/util/_validators.py | 424 | [
"inclusive"
] | tuple[bool, bool] | true | 3 | 6.08 | pandas-dev/pandas | 47,362 | numpy | false |
next | public char next(char c) throws JSONException {
char result = next();
if (result != c) {
throw syntaxError("Expected " + c + " but was " + result);
}
return result;
} | Returns the current position and the entire input string.
@return the current position and the entire input string. | java | cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONTokener.java | 485 | [
"c"
] | true | 2 | 6.88 | spring-projects/spring-boot | 79,428 | javadoc | false | |
toString | @Override
public String toString() {
return "(" +
"groupId='" + groupId + '\'' +
", isSimpleConsumerGroup=" + isSimpleConsumerGroup +
", groupState=" + groupState +
", type=" + type +
')';
} | The type of the consumer group.
@return An Optional containing the type, if available. | java | clients/src/main/java/org/apache/kafka/clients/admin/ConsumerGroupListing.java | 155 | [] | String | true | 1 | 6.88 | apache/kafka | 31,560 | javadoc | false |
containsBeanDefinition | protected abstract boolean containsBeanDefinition(String beanName); | Check if this bean factory contains a bean definition with the given name.
Does not consider any hierarchy this factory may participate in.
Invoked by {@code containsBean} when no cached singleton instance is found.
<p>Depending on the nature of the concrete bean factory implementation,
this operation might be expensiv... | java | spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java | 1,963 | [
"beanName"
] | true | 1 | 6.32 | spring-projects/spring-framework | 59,386 | javadoc | false | |
patch_environ | def patch_environ(new_env_variables: dict[str, str]) -> Generator[None, None, None]:
"""
Set environment variables in context.
After leaving the context, it restores its original state.
:param new_env_variables: Environment variables to set
"""
current_env_state = {key: os.environ.get(key) for ... | Set environment variables in context.
After leaving the context, it restores its original state.
:param new_env_variables: Environment variables to set | python | airflow-core/src/airflow/utils/process_utils.py | 329 | [
"new_env_variables"
] | Generator[None, None, None] | true | 5 | 6.4 | apache/airflow | 43,597 | sphinx | false |
bytesToInetAddress | private static InetAddress bytesToInetAddress(byte[] addr, @Nullable String scope) {
try {
InetAddress address = InetAddress.getByAddress(addr);
if (scope == null) {
return address;
}
checkArgument(
address instanceof Inet6Address, "Unexpected state, scope should only appea... | Convert a byte array into an InetAddress.
<p>{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP
address is of illegal length." We replace it with an unchecked exception, for use by callers
who already know that addr is an array of length 4 or 16.
@param addr the raw 4-byte or 16-byte ... | java | android/guava/src/com/google/common/net/InetAddresses.java | 419 | [
"addr",
"scope"
] | InetAddress | true | 6 | 7.92 | google/guava | 51,352 | javadoc | false |
fileTreeChildren | private static Iterable<Path> fileTreeChildren(Path dir) {
if (Files.isDirectory(dir, NOFOLLOW_LINKS)) {
try {
return listFiles(dir);
} catch (IOException e) {
// the exception thrown when iterating a DirectoryStream if an I/O exception occurs
throw new DirectoryIteratorException... | Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
starts from a {@link Path} and will return all files and directories it encounters.
<p>The returned traverser attempts to avoid following symbolic links to directories. However,
the traverser cannot guarantee that it will not f... | java | android/guava/src/com/google/common/io/MoreFiles.java | 301 | [
"dir"
] | true | 3 | 6.88 | google/guava | 51,352 | javadoc | false | |
command_line_usage | def command_line_usage() -> None:
"""Entry point for the compiler bisector command-line interface."""
if len(sys.argv) < 2:
print(HELP_TEXT)
sys.exit(1)
bisection_manager = CompilerBisector()
command = sys.argv[1]
if command == "end":
bisection_manager.delete_bisect_status(... | Entry point for the compiler bisector command-line interface. | python | torch/_inductor/compiler_bisector.py | 672 | [] | None | true | 15 | 6.48 | pytorch/pytorch | 96,034 | unknown | false |
getObjectType | @Override
public @Nullable Class<?> getObjectType() {
if (this.proxy != null) {
return this.proxy.getClass();
}
if (this.proxyInterfaces != null && this.proxyInterfaces.length == 1) {
return this.proxyInterfaces[0];
}
if (this.target instanceof TargetSource targetSource) {
return targetSource.getTar... | A hook for subclasses to post-process the {@link ProxyFactory}
before creating the proxy instance with it.
@param proxyFactory the AOP ProxyFactory about to be used
@since 4.2 | java | spring-aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java | 218 | [] | true | 6 | 6.4 | spring-projects/spring-framework | 59,386 | javadoc | false | |
urlParamsToForm | function urlParamsToForm() {
const regex = /(\w+)=(\w+)/g;
const search = decodeURIComponent(location.search);
let match: any[] | null;
while ((match = regex.exec(search))) {
const name = match[1];
const value = match[2];
const els = document.querySelectorAll('input[name="' + name + '"]');
let e... | @license
Copyright Google LLC All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE file at https://angular.dev/license | typescript | modules/benchmarks/src/util.ts | 75 | [] | false | 6 | 6.24 | angular/angular | 99,544 | jsdoc | false | |
getManifestInfo | private ManifestInfo getManifestInfo(ZipContent zipContent) {
ZipContent.Entry contentEntry = zipContent.getEntry(MANIFEST_NAME);
if (contentEntry == null) {
return ManifestInfo.NONE;
}
try {
try (InputStream inputStream = getInputStream(contentEntry)) {
Manifest manifest = new Manifest(inputStream);
... | Return if an entry with the given name exists.
@param name the name to check
@return if the entry exists | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/NestedJarFile.java | 313 | [
"zipContent"
] | ManifestInfo | true | 3 | 8.08 | spring-projects/spring-boot | 79,428 | javadoc | false |
estimatedBucketCount | public ExponentialHistogramBuilder estimatedBucketCount(int totalBuckets) {
estimatedBucketCount = totalBuckets;
return this;
} | If known, sets the estimated total number of buckets to minimize unnecessary allocations.
Only has an effect if invoked before the first call to
{@link #setPositiveBucket(long, long)} and {@link #setNegativeBucket(long, long)}.
@param totalBuckets the total number of buckets expected to be added
@return the builder | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramBuilder.java | 87 | [
"totalBuckets"
] | ExponentialHistogramBuilder | true | 1 | 6 | elastic/elasticsearch | 75,680 | javadoc | false |
getJsonMapper | private JsonMapper getJsonMapper() {
if (this.jsonMapper == null) {
this.jsonMapper = new JsonMapper();
}
return this.jsonMapper;
} | Creates an instance with a default {@link JsonMapper} that is created lazily. | java | core/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java | 65 | [] | JsonMapper | true | 2 | 6.56 | spring-projects/spring-boot | 79,428 | javadoc | false |
createFromDimensions | static CuVSIvfPqParams createFromDimensions(
long nRows,
long nFeatures,
CagraIndexParams.CuvsDistanceType distanceType,
int efConstruction
) {
if (nRows <= 0 || nFeatures <= 0) {
throw new IllegalArgumentException("Dataset dimensions must be positive: rows=" + nR... | Creates {@link CuVSIvfPqParams} with automatically calculated parameters based on dataset
dimensions and construction parameter.
<p>This is a convenience method when you have the dataset dimensions but not the dataset
object itself. The calculation logic is identical to {@link #create(int, int,
CagraIndexParams.CuvsDis... | java | libs/gpu-codec/src/main/java/org/elasticsearch/gpu/codec/CuVSIvfPqParamsFactory.java | 70 | [
"nRows",
"nFeatures",
"distanceType",
"efConstruction"
] | CuVSIvfPqParams | true | 7 | 7.52 | elastic/elasticsearch | 75,680 | javadoc | false |
array_split | def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis... | Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For an array of length l that should be split
into n sections, it returns l %... | python | numpy/lib/_shape_base_impl.py | 720 | [
"ary",
"indices_or_sections",
"axis"
] | false | 3 | 8 | numpy/numpy | 31,054 | unknown | false | |
bindModuleExportsAssignment | function bindModuleExportsAssignment(node: BindablePropertyAssignmentExpression) {
// A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
// is still pointing to 'module.exports'.
// We do not want to consider this as 'export=' since a modul... | Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
@param symbolTable - The symbol table which node will be added to.
@param parent - node's parent declaration.
@param node - The declaration to be added to the symbol table
@param includes - The SymbolFlags that n... | typescript | src/compiler/binder.ts | 3,236 | [
"node"
] | false | 8 | 6.08 | microsoft/TypeScript | 107,154 | jsdoc | false | |
inner | def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R:
"""Retrieve the cached result without calling the function.
Args:
*args: Positional arguments to generate the cache key.
**kwargs: Keyword arguments to generate the cache key.
... | Retrieve the cached result without calling the function.
Args:
*args: Positional arguments to generate the cache key.
**kwargs: Keyword arguments to generate the cache key.
Returns:
The cached result (decoded if decoder is provided).
Raises:
KeyError: If no cached result exists for the given paramete... | python | torch/_inductor/runtime/caching/interfaces.py | 560 | [] | _R | true | 3 | 8.08 | pytorch/pytorch | 96,034 | google | false |
record | private void record(BufferedStartupStep step) {
if (this.filter.test(step) && this.estimatedSize.get() < this.capacity) {
this.estimatedSize.incrementAndGet();
this.events.add(new TimelineEvent(step, this.clock.instant()));
}
while (true) {
BufferedStartupStep current = this.current.get();
BufferedSta... | Add a predicate filter to the list of existing ones.
<p>
A {@link StartupStep step} that doesn't match all filters will not be recorded.
@param filter the predicate filter to add. | java | core/spring-boot/src/main/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartup.java | 124 | [
"step"
] | void | true | 5 | 6.88 | spring-projects/spring-boot | 79,428 | javadoc | false |
check_for_wildcard_key | def check_for_wildcard_key(
self, wildcard_key: str, bucket_name: str | None = None, delimiter: str = ""
) -> bool:
"""
Check that a key matching a wildcard expression exists in a bucket.
:param wildcard_key: the path to the key
:param bucket_name: the name of the bucket
... | Check that a key matching a wildcard expression exists in a bucket.
:param wildcard_key: the path to the key
:param bucket_name: the name of the bucket
:param delimiter: the delimiter marks key hierarchy
:return: True if a key exists and False if not. | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py | 1,134 | [
"self",
"wildcard_key",
"bucket_name",
"delimiter"
] | bool | true | 1 | 7.04 | apache/airflow | 43,597 | sphinx | false |
toWatchPath | Path toWatchPath(ResourceLoader resourceLoader) {
try {
Assert.state(!isPemContent(), "Value contains PEM content");
Assert.state(this.value != null, "Value must not be null");
Resource resource = resourceLoader.getResource(this.value);
if (!resource.isFile()) {
throw new BundleContentNotWatchableExce... | Return if there is any property value present.
@return if the value is present | java | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ssl/BundleContentProperty.java | 56 | [
"resourceLoader"
] | Path | true | 4 | 7.04 | spring-projects/spring-boot | 79,428 | javadoc | false |
start | public void start(int timeoutMs) {
// start() is invoked internally instead of by the caller to avoid SpotBugs errors about starting a thread
// in a constructor.
start();
try {
if (!initializationLatch.await(timeoutMs, TimeUnit.MILLISECONDS)) {
maybeSetIniti... | Start the network thread and let it complete its initialization before proceeding. The
{@link ClassicKafkaConsumer} constructor blocks during creation of its {@link NetworkClient}, providing
precedent for waiting here.
In certain cases (e.g. an invalid {@link LoginModule} in {@link SaslConfigs#SASL_JAAS_CONFIG}), an er... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java | 119 | [
"timeoutMs"
] | void | true | 4 | 6.56 | apache/kafka | 31,560 | javadoc | false |
parseDependencies | private Map<String, Dependency> parseDependencies(JSONObject root) throws JSONException {
Map<String, Dependency> result = new HashMap<>();
if (!root.has(DEPENDENCIES_EL)) {
return result;
}
JSONObject dependencies = root.getJSONObject(DEPENDENCIES_EL);
JSONArray array = dependencies.getJSONArray(VALUES_EL... | Returns the defaults applicable to the service.
@return the defaults of the service | java | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java | 130 | [
"root"
] | true | 3 | 6.88 | spring-projects/spring-boot | 79,428 | javadoc | false | |
lazyLoadRimraf | function lazyLoadRimraf() {
if (rimraf === undefined)
({ rimraf } = require('internal/fs/rimraf'));
} | Synchronously truncates the file descriptor.
@param {number} fd
@param {number} [len]
@returns {void} | javascript | lib/fs.js | 1,110 | [] | false | 2 | 7.04 | nodejs/node | 114,839 | jsdoc | false | |
onLeaderElected | protected abstract Map<String, ByteBuffer> onLeaderElected(String leaderId,
String protocol,
List<JoinGroupResponseData.JoinGroupResponseMember> allMemberMetadata,
... | Invoked when the leader is elected. This is used by the leader to perform the assignment
if necessary and to push state to all the members of the group (e.g. to push partition
assignments in the case of the new consumer)
@param leaderId The id of the leader (which is this member)
@param protocol The protocol selected b... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java | 237 | [
"leaderId",
"protocol",
"allMemberMetadata",
"skipAssignment"
] | true | 1 | 6.16 | apache/kafka | 31,560 | javadoc | false | |
next | @Override
public Calendar next() {
if (spot.equals(endFinal)) {
throw new NoSuchElementException();
}
spot.add(Calendar.DATE, 1);
return (Calendar) spot.clone();
} | Returns the next calendar in the iteration.
@return Object calendar for the next date. | java | src/main/java/org/apache/commons/lang3/time/DateUtils.java | 95 | [] | Calendar | true | 2 | 8.08 | apache/commons-lang | 2,896 | javadoc | false |
rand_score | def rand_score(labels_true, labels_pred):
"""Rand index.
The Rand Index computes a similarity measure between two clusterings
by considering all pairs of samples and counting pairs that are
assigned in the same or different clusters in the predicted and
true clusterings [1]_ [2]_.
The raw RI s... | Rand index.
The Rand Index computes a similarity measure between two clusterings
by considering all pairs of samples and counting pairs that are
assigned in the same or different clusters in the predicted and
true clusterings [1]_ [2]_.
The raw RI score [3]_ is:
.. code-block:: text
RI = (number of agreeing pai... | python | sklearn/metrics/cluster/_supervised.py | 280 | [
"labels_true",
"labels_pred"
] | false | 3 | 7.28 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
_compute_lower_bound | def _compute_lower_bound(self, log_resp, log_prob_norm):
"""Estimate the lower bound of the model.
The lower bound on the likelihood (of the training data with respect to
the model) is used to detect the convergence and has to increase at
each iteration.
Parameters
----... | Estimate the lower bound of the model.
The lower bound on the likelihood (of the training data with respect to
the model) is used to detect the convergence and has to increase at
each iteration.
Parameters
----------
X : array-like of shape (n_samples, n_features)
log_resp : array, shape (n_samples, n_components)
... | python | sklearn/mixture/_bayesian_mixture.py | 781 | [
"self",
"log_resp",
"log_prob_norm"
] | false | 5 | 6.08 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
collect | public <A, R> R collect(final Supplier<R> supplier, final BiConsumer<R, ? super O> accumulator, final BiConsumer<R, R> combiner) {
makeTerminated();
return stream().collect(supplier, accumulator, combiner);
} | Performs a mutable reduction operation on the elements of this FailableStream.
A mutable reduction is one in which the reduced value is a mutable result
container, such as an {@link ArrayList}, and elements are incorporated by updating
the state of the result rather than by replacing the result. This produces a result ... | java | src/main/java/org/apache/commons/lang3/Streams.java | 318 | [
"supplier",
"accumulator",
"combiner"
] | R | true | 1 | 6.16 | apache/commons-lang | 2,896 | javadoc | false |
refreshProperties | protected PropertiesHolder refreshProperties(String filename, @Nullable PropertiesHolder propHolder) {
long refreshTimestamp = (getCacheMillis() < 0 ? -1 : System.currentTimeMillis());
Resource resource = resolveResource(filename);
if (resource != null) {
long fileTimestamp = -1;
if (getCacheMillis() >= 0)... | Refresh the PropertiesHolder for the given bundle filename.
<p>The holder can be {@code null} if not cached before, or a timed-out cache entry
(potentially getting re-validated against the current last-modified timestamp).
@param filename the bundle filename (basename + Locale)
@param propHolder the current PropertiesH... | java | spring-context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java | 458 | [
"filename",
"propHolder"
] | PropertiesHolder | true | 12 | 6.24 | spring-projects/spring-framework | 59,386 | javadoc | false |
_load_into_new_table | def _load_into_new_table(self, table_name: str, delete_on_error: bool) -> str:
"""
Import S3 key or keys into a new DynamoDB table.
:param table_name: Name of the table that shall be created
:param delete_on_error: If set, the new DynamoDB table will be deleted in case of import errors
... | Import S3 key or keys into a new DynamoDB table.
:param table_name: Name of the table that shall be created
:param delete_on_error: If set, the new DynamoDB table will be deleted in case of import errors
:return: The Amazon resource number (ARN) | python | providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_dynamodb.py | 147 | [
"self",
"table_name",
"delete_on_error"
] | str | true | 6 | 7.84 | apache/airflow | 43,597 | sphinx | false |
goodFastHash | public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return Murmur3_32HashFunction.GOOD_FAST_HASH_32;
}
if (bits <= 128) {
return Murmur3_128HashFunction.GOOD_FAST_HASH_128;
}
// Otherwise, join toget... | Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm
the returned function implements is unspecified and subject to change without notice.
<p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code
Hashing} class is loaded. <b>Do not use this metho... | java | android/guava/src/com/google/common/hash/Hashing.java | 64 | [
"minimumBits"
] | HashFunction | true | 4 | 7.76 | google/guava | 51,352 | javadoc | false |
getJavaVersion | public static JavaVersion getJavaVersion() {
List<JavaVersion> candidates = Arrays.asList(JavaVersion.values());
Collections.reverse(candidates);
for (JavaVersion candidate : candidates) {
if (candidate.available) {
return candidate;
}
}
return SEVENTEEN;
} | Returns the {@link JavaVersion} of the current runtime.
@return the {@link JavaVersion} | java | core/spring-boot/src/main/java/org/springframework/boot/system/JavaVersion.java | 120 | [] | JavaVersion | true | 2 | 7.6 | spring-projects/spring-boot | 79,428 | javadoc | false |
instance | public Struct instance(Field field) {
return instance(schema.get(field.name));
} | Create a struct instance for the given field which must be a container type (struct or array)
@param field The name of the field to create (field must be a schema type)
@return The struct
@throws SchemaException If the given field is not a container type | java | clients/src/main/java/org/apache/kafka/common/protocol/types/Struct.java | 186 | [
"field"
] | Struct | true | 1 | 6 | apache/kafka | 31,560 | javadoc | false |
parse | @Override
public TemporalAccessor parse(String text, Locale locale) throws ParseException {
try {
return doParse(text, locale, this.formatter);
}
catch (DateTimeParseException ex) {
if (!ObjectUtils.isEmpty(this.fallbackPatterns)) {
for (String pattern : this.fallbackPatterns) {
try {
DateTi... | Create a new TemporalAccessorParser for the given TemporalAccessor type.
@param temporalAccessorType the specific TemporalAccessor class
(LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, OffsetTime)
@param formatter the base DateTimeFormatter instance | java | spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java | 88 | [
"text",
"locale"
] | TemporalAccessor | true | 6 | 6.08 | spring-projects/spring-framework | 59,386 | javadoc | false |
argmin | def argmin(self, skipna: bool = True) -> int:
"""
Return the index of minimum value.
In case of multiple occurrences of the minimum value, the index
corresponding to the first occurrence is returned.
Parameters
----------
skipna : bool, default True
Ret... | Return the index of minimum value.
In case of multiple occurrences of the minimum value, the index
corresponding to the first occurrence is returned.
Parameters
----------
skipna : bool, default True
Returns
-------
int
See Also
--------
ExtensionArray.argmax : Return the index of the maximum value.
Examples
-----... | python | pandas/core/arrays/base.py | 968 | [
"self",
"skipna"
] | int | true | 3 | 8.48 | pandas-dev/pandas | 47,362 | numpy | false |
getAllSuperclasses | public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {
if (cls == null) {
return null;
}
final List<Class<?>> classes = new ArrayList<>();
Class<?> superclass = cls.getSuperclass();
while (superclass != null) {
classes.add(superclass);
... | Gets a {@link List} of superclasses for the given class.
@param cls the class to look up, may be {@code null}.
@return the {@link List} of superclasses in order going up from this one {@code null} if null input. | java | src/main/java/org/apache/commons/lang3/ClassUtils.java | 404 | [
"cls"
] | true | 3 | 8.24 | apache/commons-lang | 2,896 | javadoc | false | |
of | public static CorrelationIdFormatter of(Collection<String> spec) {
if (CollectionUtils.isEmpty(spec)) {
return DEFAULT;
}
List<Part> parts = spec.stream().map(Part::of).toList();
return new CorrelationIdFormatter(parts);
} | Create a new {@link CorrelationIdFormatter} instance from the given specification.
@param spec a pre-separated specification
@return a new {@link CorrelationIdFormatter} instance | java | core/spring-boot/src/main/java/org/springframework/boot/logging/CorrelationIdFormatter.java | 156 | [
"spec"
] | CorrelationIdFormatter | true | 2 | 7.12 | spring-projects/spring-boot | 79,428 | javadoc | false |
maybeAutoCommitOffsetsAsync | private RequestFuture<Void> maybeAutoCommitOffsetsAsync() {
if (autoCommitEnabled)
return autoCommitOffsetsAsync();
return null;
} | Commit offsets synchronously. This method will retry until the commit completes successfully
or an unrecoverable error is encountered.
@param offsets The offsets to be committed
@throws org.apache.kafka.common.errors.AuthorizationException if the consumer is not authorized to the group
or to any of the spec... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java | 1,248 | [] | true | 2 | 7.44 | apache/kafka | 31,560 | javadoc | false | |
combine_first | def combine_first(self, other) -> Series:
"""
Update null elements with value in the same location in 'other'.
Combine two Series objects by filling null values in one Series with
non-null values from the other Series. Result index will be the union
of the two indexes.
... | Update null elements with value in the same location in 'other'.
Combine two Series objects by filling null values in one Series with
non-null values from the other Series. Result index will be the union
of the two indexes.
Parameters
----------
other : Series
The value(s) to be used for filling null values.
Ret... | python | pandas/core/series.py | 3,269 | [
"self",
"other"
] | Series | true | 5 | 8.56 | pandas-dev/pandas | 47,362 | numpy | false |
send_robust | def send_robust(self, sender, **named):
"""
Send signal from sender to all connected receivers catching errors.
If any receivers are asynchronous, they are called after all the
synchronous receivers via a single call to async_to_sync(). They are
also executed concurrently with a... | Send signal from sender to all connected receivers catching errors.
If any receivers are asynchronous, they are called after all the
synchronous receivers via a single call to async_to_sync(). They are
also executed concurrently with asyncio.TaskGroup().
Arguments:
sender
The sender of the signal. Can be... | python | django/dispatch/dispatcher.py | 313 | [
"self",
"sender"
] | false | 6 | 6 | django/django | 86,204 | google | false | |
_maybe_mark | def _maybe_mark(
estimator,
check,
expected_failed_checks: dict[str, str] | None = None,
mark: Literal["xfail", "skip", None] = None,
pytest=None,
xfail_strict: bool | None = None,
):
"""Mark the test as xfail or skip if needed.
Parameters
----------
estimator : estimator object... | Mark the test as xfail or skip if needed.
Parameters
----------
estimator : estimator object
Estimator instance for which to generate checks.
check : partial or callable
Check to be marked.
expected_failed_checks : dict[str, str], default=None
Dictionary of the form {check_name: reason} for checks that are... | python | sklearn/utils/estimator_checks.py | 421 | [
"estimator",
"check",
"expected_failed_checks",
"mark",
"pytest",
"xfail_strict"
] | true | 7 | 6.96 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
ohlc | def ohlc(self):
"""
Compute open, high, low and close values of a group, excluding missing values.
Returns
-------
DataFrame
Open, high, low and close values within each group.
See Also
--------
DataFrame.agg : Aggregate using one or more ope... | Compute open, high, low and close values of a group, excluding missing values.
Returns
-------
DataFrame
Open, high, low and close values within each group.
See Also
--------
DataFrame.agg : Aggregate using one or more operations over the specified axis.
DataFrame.resample : Resample time-series data.
DataFrame.g... | python | pandas/core/resample.py | 1,707 | [
"self"
] | false | 4 | 6.64 | pandas-dev/pandas | 47,362 | unknown | false | |
deleteConsumerGroupOffsets | DeleteConsumerGroupOffsetsResult deleteConsumerGroupOffsets(String groupId,
Set<TopicPartition> partitions,
DeleteConsumerGroupOffsetsOptions options); | Delete committed offsets for a set of partitions in a consumer group. This will
succeed at the partition level only if the group is not actively subscribed
to the corresponding topic.
@param options The options to use when deleting offsets in a consumer group.
@return The DeleteConsumerGroupOffsetsResult. | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 1,022 | [
"groupId",
"partitions",
"options"
] | DeleteConsumerGroupOffsetsResult | true | 1 | 6.64 | apache/kafka | 31,560 | javadoc | false |
toString | @Override
public String toString() {
return "QuorumInfo(" +
"leaderId=" + leaderId +
", leaderEpoch=" + leaderEpoch +
", highWatermark=" + highWatermark +
", voters=" + voters +
", observers=" + observers +
", nodes=" + nodes +
... | @return The voter nodes in the Raft cluster, or an empty map if KIP-853 is not enabled. | java | clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java | 98 | [] | String | true | 1 | 7.04 | apache/kafka | 31,560 | javadoc | false |
chebline | def chebline(off, scl):
"""
Chebyshev series whose graph is a straight line.
Parameters
----------
off, scl : scalars
The specified line is given by ``off + scl*x``.
Returns
-------
y : ndarray
This module's representation of the Chebyshev series for
``off + scl... | Chebyshev series whose graph is a straight line.
Parameters
----------
off, scl : scalars
The specified line is given by ``off + scl*x``.
Returns
-------
y : ndarray
This module's representation of the Chebyshev series for
``off + scl*x``.
See Also
--------
numpy.polynomial.polynomial.polyline
numpy.poly... | python | numpy/polynomial/chebyshev.py | 474 | [
"off",
"scl"
] | false | 3 | 7.04 | numpy/numpy | 31,054 | numpy | false | |
bulkSeparator | byte bulkSeparator(); | @return a {@link byte} that separates items in a bulk request that uses this {@link XContent}.
@throws RuntimeException if this {@link XContent} does not support a delimited bulk format. See {@link #hasBulkSeparator()}. | java | libs/x-content/src/main/java/org/elasticsearch/xcontent/XContent.java | 42 | [] | true | 1 | 6.48 | elastic/elasticsearch | 75,680 | javadoc | false | |
exclusiveBetween | public static void exclusiveBetween(final double start, final double end, final double value, final String message) {
// TODO when breaking BC, consider returning value
if (value <= start || value >= end) {
throw new IllegalArgumentException(message);
}
} | Validate that the specified primitive value falls between the two
exclusive values specified; otherwise, throws an exception with the
specified message.
<pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
@param start the exclusive start value.
@param end the exclusive end value.
@param value the val... | java | src/main/java/org/apache/commons/lang3/Validate.java | 114 | [
"start",
"end",
"value",
"message"
] | void | true | 3 | 6.56 | apache/commons-lang | 2,896 | javadoc | false |
listCacheDelete | function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--... | Removes `key` and its value from the list cache.
@private
@name delete
@memberOf ListCache
@param {string} key The key of the value to remove.
@returns {boolean} Returns `true` if the entry was removed, else `false`. | javascript | lodash.js | 2,082 | [
"key"
] | false | 4 | 6.08 | lodash/lodash | 61,490 | jsdoc | false | |
equals | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Ansi8BitColor other = (Ansi8BitColor) obj;
return this.prefix.equals(other.prefix) && this.code == other.code;
} | Create a new {@link Ansi8BitColor} instance.
@param prefix the prefix escape chars
@param code color code (must be 0-255)
@throws IllegalArgumentException if color code is not between 0 and 255. | java | core/spring-boot/src/main/java/org/springframework/boot/ansi/Ansi8BitColor.java | 48 | [
"obj"
] | true | 5 | 6.72 | spring-projects/spring-boot | 79,428 | javadoc | false | |
processEvent | public void processEvent(ApplicationEvent event) {
@Nullable Object[] args = resolveArguments(event);
if (shouldHandle(event, args)) {
Object result = doInvoke(args);
if (result != null) {
handleResult(result);
}
else {
logger.trace("No result object given - no result to handle");
}
}
} | Process the specified {@link ApplicationEvent}, checking if the condition
matches and handling a non-null result, if any.
@param event the event to process through the listener method | java | spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java | 249 | [
"event"
] | void | true | 3 | 6.56 | spring-projects/spring-framework | 59,386 | javadoc | false |
value_counts | def value_counts(self, dropna: bool = True) -> Series:
"""
Return a Series containing counts of each unique value.
Parameters
----------
dropna : bool, default True
Don't include counts of missing values.
Returns
-------
counts : Series
... | Return a Series containing counts of each unique value.
Parameters
----------
dropna : bool, default True
Don't include counts of missing values.
Returns
-------
counts : Series
See Also
--------
Series.value_counts | python | pandas/core/arrays/arrow/array.py | 1,773 | [
"self",
"dropna"
] | Series | true | 3 | 6.72 | pandas-dev/pandas | 47,362 | numpy | false |
nullToEmpty | public static <T> T[] nullToEmpty(final T[] array, final Class<T[]> type) {
if (type == null) {
throw new IllegalArgumentException("The type must not be null");
}
if (array == null) {
return type.cast(Array.newInstance(type.getComponentType(), 0));
}
retur... | 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>
@param array the array to check for {@code null} or empty.
@param type the class representation of the desired array.
@param <T> the class type.
@return the... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 4,640 | [
"array",
"type"
] | true | 3 | 8.08 | apache/commons-lang | 2,896 | javadoc | false | |
textOrNull | String textOrNull() 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 | 110 | [] | String | true | 1 | 6.32 | elastic/elasticsearch | 75,680 | javadoc | false |
calculate_tensor_size | def calculate_tensor_size(tensor: torch.Tensor) -> float:
"""
Calculate the size of a PyTorch tensor in megabytes (MB).
Args:
tensor (torch.Tensor): Input tensor
Returns:
float: Memory size in MB
"""
# Get number of elements and size per element
num_elements = tensor.numel(... | Calculate the size of a PyTorch tensor in megabytes (MB).
Args:
tensor (torch.Tensor): Input tensor
Returns:
float: Memory size in MB | python | torch/_functorch/partitioners.py | 536 | [
"tensor"
] | float | true | 1 | 6.72 | pytorch/pytorch | 96,034 | google | false |
appendPossibility | static void appendPossibility(StringBuilder description) {
if (!description.toString().endsWith(System.lineSeparator())) {
description.append("%n".formatted());
}
description.append("%n%s".formatted(POSSIBILITY));
} | Analyze the given failure for missing parameter name exceptions.
@param failure the failure to analyze
@return a failure analysis or {@code null} | java | core/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MissingParameterNamesFailureAnalyzer.java | 111 | [
"description"
] | void | true | 2 | 7.92 | spring-projects/spring-boot | 79,428 | javadoc | false |
on_pre_execution | def on_pre_execution(**kwargs):
"""
Call callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None
"""
logger.debug("Calling callbacks: %s", __pre_exec_callbacks)
for callback in __pre_exec_callbacks:
... | Call callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None | python | airflow-core/src/airflow/utils/cli_action_loggers.py | 70 | [] | false | 2 | 7.44 | apache/airflow | 43,597 | sphinx | false | |
to_coo | def to_coo(self) -> spmatrix:
"""
Return the contents of the frame as a sparse SciPy COO matrix.
Returns
-------
scipy.sparse.spmatrix
If the caller is heterogeneous and contains booleans or objects,
the result will be of dtype=object. See Notes.
... | Return the contents of the frame as a sparse SciPy COO matrix.
Returns
-------
scipy.sparse.spmatrix
If the caller is heterogeneous and contains booleans or objects,
the result will be of dtype=object. See Notes.
See Also
--------
DataFrame.sparse.to_dense : Convert a DataFrame with sparse values to dense.
N... | python | pandas/core/arrays/sparse/accessor.py | 396 | [
"self"
] | spmatrix | true | 3 | 7.28 | pandas-dev/pandas | 47,362 | unknown | false |
_is_valid_na_for | def _is_valid_na_for(self, dtype: DtypeObj) -> bool:
"""
Check that we are all-NA of a type/dtype that is compatible with this dtype.
Augments `self.is_na` with an additional check of the type of NA values.
"""
if not self.is_na:
return False
blk = self.block... | Check that we are all-NA of a type/dtype that is compatible with this dtype.
Augments `self.is_na` with an additional check of the type of NA values. | python | pandas/core/internals/concat.py | 308 | [
"self",
"dtype"
] | bool | true | 8 | 6 | pandas-dev/pandas | 47,362 | unknown | false |
atleast_nd | def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType | None = None) -> Array:
"""
Recursively expand the dimension of an array to at least `ndim`.
Parameters
----------
x : array
Input array.
ndim : int
The minimum number of dimensions for the result.
xp : array_namespac... | Recursively expand the dimension of an array to at least `ndim`.
Parameters
----------
x : array
Input array.
ndim : int
The minimum number of dimensions for the result.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
array
An array with ``res.... | python | sklearn/externals/array_api_extra/_lib/_funcs.py | 178 | [
"x",
"ndim",
"xp"
] | Array | true | 3 | 8.32 | scikit-learn/scikit-learn | 64,340 | numpy | false |
parseBuckets | private static void parseBuckets(Map<String, List<Number>> serializedBuckets, BiConsumer<Long, Long> bucketSetter) {
List<Number> indices = serializedBuckets.getOrDefault(BUCKET_INDICES_FIELD, Collections.emptyList());
List<Number> counts = serializedBuckets.getOrDefault(BUCKET_COUNTS_FIELD, Collections... | Parses an {@link ExponentialHistogram} from a {@link Map}.
This method is neither optimized, nor does it do any validation of the parsed content.
No estimation for missing sum/min/max is done.
Therefore only intended for testing!
@param xContent the serialized histogram as a map
@return the deserialized histogram | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramXContent.java | 169 | [
"serializedBuckets",
"bucketSetter"
] | void | true | 2 | 7.92 | elastic/elasticsearch | 75,680 | javadoc | false |
forCurrentThread | static SpringBootExceptionHandler forCurrentThread() {
return handler.get();
} | Check if the exception is a log configuration message, i.e. the log call might not
have actually output anything.
@param ex the source exception
@return {@code true} if the exception contains a log configuration message | java | core/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java | 121 | [] | SpringBootExceptionHandler | true | 1 | 6.96 | spring-projects/spring-boot | 79,428 | javadoc | false |
onMemberEpochUpdated | @Override
public void onMemberEpochUpdated(Optional<Integer> memberEpoch, String memberId) {
if (memberEpoch.isEmpty() && memberInfo.memberEpoch.isPresent()) {
log.info("Member {} won't include epoch in following offset " +
"commit/fetch requests because it has left the group.", ... | Update latest member epoch used by the member.
@param memberEpoch New member epoch received. To be included in the new request.
@param memberId Current member ID. To be included in the new request. | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java | 596 | [
"memberEpoch",
"memberId"
] | void | true | 4 | 6.88 | apache/kafka | 31,560 | javadoc | false |
create | static Admin create(Map<String, Object> conf) {
return KafkaAdminClient.createInternal(new AdminClientConfig(conf, true), null, null);
} | Create a new Admin with the given configuration.
@param conf The configuration.
@return The new KafkaAdminClient. | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 143 | [
"conf"
] | Admin | true | 1 | 6.32 | apache/kafka | 31,560 | javadoc | false |
ofEntries | @SafeVarargs
@SuppressWarnings("unchecked")
public static <K,V> ManagedMap<K,V> ofEntries(Entry<? extends K, ? extends V>... entries) {
ManagedMap<K,V > map = new ManagedMap<>();
for (Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
} | Return a new instance containing keys and values extracted from the
given entries. The entries themselves are not stored in the map.
@param entries {@code Map.Entry}s containing the keys and values
from which the map is populated
@param <K> the {@code Map}'s key type
@param <V> the {@code Map}'s value type
@return a {@... | java | spring-beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java | 68 | [] | true | 1 | 7.04 | spring-projects/spring-framework | 59,386 | javadoc | false | |
containsBeanDefinition | boolean containsBeanDefinition(String beanName); | Check if this bean factory contains a bean definition with the given name.
<p>Does not consider any hierarchy this factory may participate in,
and ignores any singleton beans that have been registered by
other means than bean definitions.
@param beanName the name of the bean to look for
@return if this bean factory con... | java | spring-beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java | 71 | [
"beanName"
] | true | 1 | 6.32 | spring-projects/spring-framework | 59,386 | javadoc | false | |
pin_min_versions_to_ci_deps | def pin_min_versions_to_ci_deps() -> int:
"""
Pin minimum versions to CI dependencies.
Pip dependencies are not pinned.
"""
all_yaml_files = list(YAML_PATH.iterdir())
all_yaml_files.append(ENV_PATH)
toml_dependencies = {}
with open(SETUP_PATH, "rb") as toml_f:
toml_dependencies ... | Pin minimum versions to CI dependencies.
Pip dependencies are not pinned. | python | scripts/validate_min_versions_in_sync.py | 49 | [] | int | true | 3 | 6.88 | pandas-dev/pandas | 47,362 | unknown | false |
sortedUniq | function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
} | This method is like `_.uniq` except that it's designed and optimized
for sorted arrays.
@static
@memberOf _
@since 4.0.0
@category Array
@param {Array} array The array to inspect.
@returns {Array} Returns the new duplicate free array.
@example
_.sortedUniq([1, 1, 2]);
// => [1, 2] | javascript | lodash.js | 8,200 | [
"array"
] | false | 3 | 7.52 | lodash/lodash | 61,490 | jsdoc | false | |
parseIso8601 | private static Duration parseIso8601(String value) {
try {
return Duration.parse(value);
}
catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
}
} | Detect the style then parse the value to return a duration.
@param value the value to parse
@param unit the duration unit to use if the value doesn't specify one ({@code null}
will default to ms)
@return the parsed duration
@throws IllegalArgumentException if the value is not a known style or cannot be
parsed | java | spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java | 151 | [
"value"
] | Duration | true | 2 | 7.76 | spring-projects/spring-framework | 59,386 | javadoc | false |
existsSync | function existsSync(path) {
try {
path = getValidatedPath(path);
} catch (err) {
if (showExistsDeprecation && err?.code === 'ERR_INVALID_ARG_TYPE') {
process.emitWarning(
'Passing invalid argument types to fs.existsSync is deprecated', 'DeprecationWarning', 'DEP0187',
);
showExists... | Synchronously tests whether or not the given path exists.
@param {string | Buffer | URL} path
@returns {boolean} | javascript | lib/fs.js | 273 | [
"path"
] | false | 4 | 6.24 | nodejs/node | 114,839 | jsdoc | false | |
packAsBinary | public static void packAsBinary(int[] vector, byte[] packed) {
if (packed.length * Byte.SIZE < vector.length) {
throw new IllegalArgumentException("packed array is too small: " + packed.length * Byte.SIZE + " < " + vector.length);
}
IMPL.packAsBinary(vector, packed);
} | Packs the provided int array populated with "0" and "1" values into a byte array.
@param vector the int array to pack, must contain only "0" and "1" values.
@param packed the byte array to store the packed result, must be large enough to hold the packed data. | java | libs/simdvec/src/main/java/org/elasticsearch/simdvec/ESVectorUtil.java | 389 | [
"vector",
"packed"
] | void | true | 2 | 7.04 | elastic/elasticsearch | 75,680 | javadoc | false |
addAndGet | public double addAndGet(final Number operand) {
this.value += operand.doubleValue();
return value;
} | Increments this instance's value by {@code operand}; this method returns the value associated with the instance
immediately after the addition operation. This method is not thread safe.
@param operand the quantity to add, not null.
@throws NullPointerException if {@code operand} is null.
@return the value associated wi... | java | src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java | 127 | [
"operand"
] | true | 1 | 6.64 | apache/commons-lang | 2,896 | javadoc | false | |
getStrategy | static Strategy getStrategy(final int tokenLen) {
switch (tokenLen) {
case 1:
return ISO_8601_1_STRATEGY;
case 2:
return ISO_8601_2_STRATEGY;
case 3:
return ISO_8601_3_STRATEGY;
default:
throw new... | Factory method for ISO8601TimeZoneStrategies.
@param tokenLen a token indicating the length of the TimeZone String to be formatted.
@return a ISO8601TimeZoneStrategy that can format TimeZone String of length {@code tokenLen}. If no such strategy exists, an IllegalArgumentException
will be thrown. | java | src/main/java/org/apache/commons/lang3/time/FastDateParser.java | 212 | [
"tokenLen"
] | Strategy | true | 1 | 6.4 | apache/commons-lang | 2,896 | javadoc | false |
valueOf | public static String valueOf(final char[] value) {
return value == null ? null : String.valueOf(value);
} | Returns the string representation of the {@code char} array or null.
@param value the character array.
@return a String or null.
@see String#valueOf(char[])
@since 3.9 | java | src/main/java/org/apache/commons/lang3/StringUtils.java | 9,049 | [
"value"
] | String | true | 2 | 8 | apache/commons-lang | 2,896 | javadoc | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.