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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
read_magic | def read_magic(fp):
""" Read the magic string to get the version of the file format.
Parameters
----------
fp : filelike object
Returns
-------
major : int
minor : int
"""
magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
if magic_str[:-2] != MAGIC_PREFIX:
msg ... | Read the magic string to get the version of the file format.
Parameters
----------
fp : filelike object
Returns
-------
major : int
minor : int | python | numpy/lib/_format_impl.py | 230 | [
"fp"
] | false | 2 | 6.24 | numpy/numpy | 31,054 | numpy | false | |
timestamp | public long timestamp() {
if (magic() == RecordBatch.MAGIC_VALUE_V0)
return RecordBatch.NO_TIMESTAMP;
else {
// case 2
if (wrapperRecordTimestampType == TimestampType.LOG_APPEND_TIME && wrapperRecordTimestamp != null)
return wrapperRecordTimestamp;
... | When magic value is greater than 0, the timestamp of a record is determined in the following way:
1. wrapperRecordTimestampType = null and wrapperRecordTimestamp is null - Uncompressed message, timestamp is in the message.
2. wrapperRecordTimestampType = LOG_APPEND_TIME and WrapperRecordTimestamp is not null - Compress... | java | clients/src/main/java/org/apache/kafka/common/record/LegacyRecord.java | 217 | [] | true | 4 | 7.6 | apache/kafka | 31,560 | javadoc | false | |
triu_indices_from | def triu_indices_from(arr, k=0):
"""
Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for detail... | Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for details).
Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shap... | python | numpy/lib/_twodim_base_impl.py | 1,142 | [
"arr",
"k"
] | false | 2 | 7.68 | numpy/numpy | 31,054 | numpy | false | |
_create_method | def _create_method(cls, op, coerce_to_dtype: bool = True, result_dtype=None):
"""
A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionAr... | A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionArray.
Parameters
----------
op : function
An operator that takes arguments op(a, b)
coerce_to_dtype : bool, default Tr... | python | pandas/core/arrays/base.py | 2,892 | [
"cls",
"op",
"coerce_to_dtype",
"result_dtype"
] | true | 9 | 6.64 | pandas-dev/pandas | 47,362 | numpy | false | |
add | @Override
@CanIgnoreReturnValue
public Builder<E> add(E element) {
checkNotNull(element);
if (hashTable != null && chooseTableSize(size) <= hashTable.length) {
addDeduping(element);
return this;
} else {
hashTable = null;
super.add(element);
return this;... | Adds {@code element} to the {@code ImmutableSet}. If the {@code ImmutableSet} already
contains {@code element}, then {@code add} has no effect (only the previously added element
is retained).
@param element the element to add
@return this {@code Builder} object
@throws NullPointerException if {@code element} is null | java | android/guava/src/com/google/common/collect/ImmutableSet.java | 484 | [
"element"
] | true | 3 | 7.76 | google/guava | 51,352 | javadoc | false | |
configure | @Override
protected void configure(ServletRegistration.Dynamic registration) {
super.configure(registration);
String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
if (urlMapping.length == 0 && this.alwaysMapUrl) {
urlMapping = DEFAULT_MAPPINGS;
}
if (!ObjectUtils.isEmpty(urlMapping)) {
re... | Configure registration settings. Subclasses can override this method to perform
additional configuration if required.
@param registration the registration | java | core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java | 188 | [
"registration"
] | void | true | 5 | 6.24 | spring-projects/spring-boot | 79,428 | javadoc | false |
clearAll | public Iterable<NetworkClient.InFlightRequest> clearAll(String node) {
Deque<NetworkClient.InFlightRequest> reqs = requests.get(node);
if (reqs == null) {
return Collections.emptyList();
} else {
final Deque<NetworkClient.InFlightRequest> clearedRequests = requests.remove... | Clear out all the in-flight requests for the given node and return them
@param node The node
@return All the in-flight requests for that node that have been removed | java | clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java | 144 | [
"node"
] | true | 2 | 7.76 | apache/kafka | 31,560 | javadoc | false | |
base_repr | def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system... | Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system. The valid range is 2-36,
the default value is 2.
padding : int, optional... | python | numpy/_core/numeric.py | 2,097 | [
"number",
"base",
"padding"
] | false | 7 | 7.68 | numpy/numpy | 31,054 | numpy | false | |
check_docker_permission_denied | def check_docker_permission_denied() -> bool:
"""
Checks if we have permission to write to docker socket. By default, on Linux you need to add your user
to docker group and some new users do not realize that. We help those users if we have
permission to run docker commands.
:return: True if permis... | Checks if we have permission to write to docker socket. By default, on Linux you need to add your user
to docker group and some new users do not realize that. We help those users if we have
permission to run docker commands.
:return: True if permission is denied | python | dev/breeze/src/airflow_breeze/utils/docker_command_utils.py | 133 | [] | bool | true | 4 | 8.08 | apache/airflow | 43,597 | unknown | false |
_get_combined_index | def _get_combined_index(
indexes: list[Index],
intersect: bool = False,
sort: bool | lib.NoDefault = False,
) -> Index:
"""
Return the union or intersection of indexes.
Parameters
----------
indexes : list of Index or list objects
When intersect=True, do not accept list of lists... | Return the union or intersection of indexes.
Parameters
----------
indexes : list of Index or list objects
When intersect=True, do not accept list of lists.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
sort : bool, default False
Wh... | python | pandas/core/indexes/api.py | 109 | [
"indexes",
"intersect",
"sort"
] | Index | true | 9 | 6.88 | pandas-dev/pandas | 47,362 | numpy | false |
nop | @SuppressWarnings("unchecked")
static <E extends Throwable> FailableDoubleConsumer<E> nop() {
return NOP;
} | Gets the NOP singleton.
@param <E> The kind of thrown exception or error.
@return The NOP singleton. | java | src/main/java/org/apache/commons/lang3/function/FailableDoubleConsumer.java | 42 | [] | true | 1 | 6.96 | apache/commons-lang | 2,896 | javadoc | false | |
isSystemEnvironmentPropertySource | private static boolean isSystemEnvironmentPropertySource(PropertySource<?> source) {
String name = source.getName();
return (source instanceof SystemEnvironmentPropertySource)
&& (StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME.equals(name)
|| name.endsWith("-" + StandardEnvironment.SYSTEM_ENV... | Create a new {@link SpringConfigurationPropertySource} for the specified
{@link PropertySource}.
@param source the source Spring {@link PropertySource}
@return a {@link SpringConfigurationPropertySource} or
{@link SpringIterableConfigurationPropertySource} instance | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java | 181 | [
"source"
] | true | 3 | 7.12 | spring-projects/spring-boot | 79,428 | javadoc | false | |
get_name_and_dir_from_output_file_path | def get_name_and_dir_from_output_file_path(
file_path: str,
) -> tuple[str, str]:
"""
This function help prepare parameters to new cpp_builder.
Example:
input_code: /tmp/tmpof1n5g7t/5c/c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc.cpp
name, dir = get_name_and_dir_from_output_file_... | This function help prepare parameters to new cpp_builder.
Example:
input_code: /tmp/tmpof1n5g7t/5c/c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc.cpp
name, dir = get_name_and_dir_from_output_file_path(input_code)
Run result:
name = c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc
dir = /tmp/tm... | python | torch/_inductor/cpp_builder.py | 1,839 | [
"file_path"
] | tuple[str, str] | true | 1 | 6.48 | pytorch/pytorch | 96,034 | unknown | false |
getCacheOperations | @Override
public @Nullable Collection<CacheOperation> getCacheOperations(Method method, @Nullable Class<?> targetClass) {
// look for direct name match
String methodName = method.getName();
Collection<CacheOperation> ops = this.nameMap.get(methodName);
if (ops == null) {
// Look for most specific name matc... | Add an attribute for a cacheable method.
<p>Method names can be exact matches, or of the pattern "xxx*",
"*xxx" or "*xxx*" for matching multiple methods.
@param methodName the name of the method
@param ops operation associated with the method | java | spring-context/src/main/java/org/springframework/cache/interceptor/NameMatchCacheOperationSource.java | 77 | [
"method",
"targetClass"
] | true | 5 | 6.88 | spring-projects/spring-framework | 59,386 | javadoc | false | |
kill_child_processes_by_pids | def kill_child_processes_by_pids(pids_to_kill: list[int], timeout: int = 5) -> None:
"""
Kills child processes for the current process.
First, it sends the SIGTERM signal, and after the time specified by the `timeout` parameter, sends
the SIGKILL signal, if the process is still alive.
:param pids_... | Kills child processes for the current process.
First, it sends the SIGTERM signal, and after the time specified by the `timeout` parameter, sends
the SIGKILL signal, if the process is still alive.
:param pids_to_kill: List of PID to be killed.
:param timeout: The time to wait before sending the SIGKILL signal. | python | airflow-core/src/airflow/utils/process_utils.py | 285 | [
"pids_to_kill",
"timeout"
] | None | true | 6 | 7.2 | apache/airflow | 43,597 | sphinx | false |
ones | def ones(shape, dtype=None, order='C'):
"""
Matrix of ones.
Return a matrix of given shape and type, filled with ones.
Parameters
----------
shape : {sequence of ints, int}
Shape of the matrix
dtype : data-type, optional
The desired data-type for the matrix, default is np.f... | Matrix of ones.
Return a matrix of given shape and type, filled with ones.
Parameters
----------
shape : {sequence of ints, int}
Shape of the matrix
dtype : data-type, optional
The desired data-type for the matrix, default is np.float64.
order : {'C', 'F'}, optional
Whether to store matrix in C- or Fortra... | python | numpy/matlib.py | 66 | [
"shape",
"dtype",
"order"
] | false | 1 | 6.48 | numpy/numpy | 31,054 | numpy | false | |
isBeforeAdvice | @Override
public boolean isBeforeAdvice() {
if (this.isBeforeAdvice == null) {
determineAdviceType();
}
return this.isBeforeAdvice;
} | Return the AspectJ AspectMetadata for this advisor. | java | spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java | 196 | [] | true | 2 | 6.08 | spring-projects/spring-framework | 59,386 | javadoc | false | |
onResponse | private void onResponse(final StreamsGroupHeartbeatResponse response, long currentTimeMs) {
if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
onSuccessResponse(response, currentTimeMs);
} else {
onErrorResponse(response, currentTimeMs);
}
} | A heartbeat should be sent without waiting for the heartbeat interval to expire if:
- the member is leaving the group
or
- the member is joining the group or acknowledging the assignment and for both cases there is no heartbeat request
in flight.
@return true if a heartbeat should be sent before the interval expires,... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java | 519 | [
"response",
"currentTimeMs"
] | void | true | 2 | 6.56 | apache/kafka | 31,560 | javadoc | false |
substituteShorthandPropertyAssignment | function substituteShorthandPropertyAssignment(node: ShorthandPropertyAssignment): ObjectLiteralElementLike {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports) {
const name = node.name;
const exportedName = trySubstituteNamespaceExportedName(name);
... | Hooks node substitutions.
@param hint A hint as to the intended usage of the node.
@param node The node to substitute. | typescript | src/compiler/transformers/ts.ts | 2,649 | [
"node"
] | true | 4 | 6.88 | microsoft/TypeScript | 107,154 | jsdoc | false | |
baseIsNative | function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
} | The base implementation of `_.isNative` without bad shim checks.
@private
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is a native function,
else `false`. | javascript | lodash.js | 3,451 | [
"value"
] | false | 4 | 6.08 | lodash/lodash | 61,490 | jsdoc | false | |
invoke | @Nullable Object invoke(MethodInvocation invocation) throws Throwable; | Implement this method to perform extra treatments before and
after the invocation. Polite implementations would certainly
like to invoke {@link Joinpoint#proceed()}.
@param invocation the method invocation joinpoint
@return the result of the call to {@link Joinpoint#proceed()};
might be intercepted by the interceptor
@... | java | spring-aop/src/main/java/org/aopalliance/intercept/MethodInterceptor.java | 57 | [
"invocation"
] | Object | true | 1 | 6.16 | spring-projects/spring-framework | 59,386 | javadoc | false |
warnTypelessPackageJsonFile | function warnTypelessPackageJsonFile(pjsonPath, url) {
typelessPackageJsonFilesWarnedAbout ??= new SafeSet();
if (!underNodeModules(url) && !typelessPackageJsonFilesWarnedAbout.has(pjsonPath)) {
const warning = `Module type of ${url} is not specified and it doesn't parse as CommonJS.\n` +
'Reparsing as ES... | Determine whether the given file URL is under a `node_modules` folder.
This function assumes that the input has already been verified to be a `file:` URL,
and is a file rather than a folder.
@param {URL} url
@returns {boolean} | javascript | lib/internal/modules/esm/get_format.js | 94 | [
"pjsonPath",
"url"
] | false | 3 | 6.24 | nodejs/node | 114,839 | jsdoc | false | |
rdb_handler | def rdb_handler(*args):
"""Signal handler setting a rdb breakpoint at the current frame."""
with in_sighandler():
from celery.contrib.rdb import _frame, set_trace
# gevent does not pass standard signal handler args
frame = args[1] if args else _frame().f_back
... | Signal handler setting a rdb breakpoint at the current frame. | python | celery/apps/worker.py | 499 | [] | false | 2 | 6.4 | celery/celery | 27,741 | unknown | false | |
createCacheKeyInvocationContext | protected CacheKeyInvocationContext<A> createCacheKeyInvocationContext(CacheOperationInvocationContext<O> context) {
return new DefaultCacheKeyInvocationContext<>(context.getOperation(), context.getTarget(), context.getArgs());
} | Create a {@link CacheKeyInvocationContext} based on the specified invocation.
@param context the context of the invocation.
@return the related {@code CacheKeyInvocationContext} | java | spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractKeyCacheInterceptor.java | 63 | [
"context"
] | true | 1 | 6 | spring-projects/spring-framework | 59,386 | javadoc | false | |
hash_tuples | def hash_tuples(
vals: MultiIndex | Iterable[tuple[Hashable, ...]],
encoding: str = "utf8",
hash_key: str = _default_hash_key,
) -> npt.NDArray[np.uint64]:
"""
Hash a MultiIndex / listlike-of-tuples efficiently.
Parameters
----------
vals : MultiIndex or listlike-of-tuples
encoding ... | Hash a MultiIndex / listlike-of-tuples efficiently.
Parameters
----------
vals : MultiIndex or listlike-of-tuples
encoding : str, default 'utf8'
hash_key : str, default _default_hash_key
Returns
-------
ndarray[np.uint64] of hashed values | python | pandas/core/util/hashing.py | 185 | [
"vals",
"encoding",
"hash_key"
] | npt.NDArray[np.uint64] | true | 4 | 6.08 | pandas-dev/pandas | 47,362 | numpy | false |
comparePrecedenceWithinAspect | private int comparePrecedenceWithinAspect(Advisor advisor1, Advisor advisor2) {
boolean oneOrOtherIsAfterAdvice =
(AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2));
int adviceDeclarationOrderDelta = getAspectDeclarationOrder(advisor1) - getAspectDeclarationOrder(advisor2);
... | Create an {@code AspectJPrecedenceComparator}, using the given {@link Comparator}
for comparing {@link org.springframework.aop.Advisor} instances.
@param advisorComparator the {@code Comparator} to use for advisors | java | spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java | 90 | [
"advisor1",
"advisor2"
] | true | 7 | 6.4 | spring-projects/spring-framework | 59,386 | javadoc | false | |
loadBeanDefinitions | @Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
} | Load bean definitions from the specified Groovy script or XML file.
<p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
of resources will be parsed as Groovy scripts.
@param resource the resource descriptor for the Groovy script or XML file
@return the number of bean definitions found
@thro... | java | spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java | 223 | [
"resource"
] | true | 1 | 6.8 | spring-projects/spring-framework | 59,386 | javadoc | false | |
put | public JSONArray put(int index, Object value) throws JSONException {
if (value instanceof Number) {
// deviate from the original by checking all Numbers, not just floats &
// doubles
JSON.checkDouble(((Number) value).doubleValue());
}
while (this.values.size() <= index) {
this.values.add(null);
}
... | Sets the value at {@code index} to {@code value}, null padding this array to the
required length if necessary. If a value already exists at {@code
index}, it will be replaced.
@param index the index to set the value to
@param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer,
Long, Double, {@link ... | java | cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java | 247 | [
"index",
"value"
] | JSONArray | true | 3 | 8.24 | spring-projects/spring-boot | 79,428 | javadoc | false |
asReversedList | private List<String> asReversedList(@Nullable List<String> list) {
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyList();
}
List<String> reversed = new ArrayList<>(list);
Collections.reverse(reversed);
return reversed;
} | Create a new {@link Profiles} instance based on the {@link Environment} and
{@link Binder}.
@param environment the source environment
@param binder the binder for profile properties
@param additionalProfiles any additional active profiles | java | core/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java | 152 | [
"list"
] | true | 2 | 6.08 | spring-projects/spring-boot | 79,428 | javadoc | false | |
entrySetIterator | Iterator<Entry<K, V>> entrySetIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().iterator();
}
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> getOutput(int entry) {
return new MapEntry(entry);
}
};
} | Updates the index an iterator is pointing to after a call to remove: returns the index of the
entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
index that *was* the next entry that would be looked at. | java | android/guava/src/com/google/common/collect/CompactHashMap.java | 799 | [] | true | 2 | 6.4 | google/guava | 51,352 | javadoc | false | |
xp_assert_equal | def xp_assert_equal(
actual: Array,
desired: Array,
*,
err_msg: str = "",
check_dtype: bool = True,
check_shape: bool = True,
check_scalar: bool = False,
) -> None:
"""
Array-API compatible version of `np.testing.assert_array_equal`.
Parameters
----------
actual : Array
... | Array-API compatible version of `np.testing.assert_array_equal`.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected array (typically hardcoded).
err_msg : str, optional
Error message to display on failure.
check_dtype, check_shape : bool, default: T... | python | sklearn/externals/array_api_extra/_lib/_testing.py | 137 | [
"actual",
"desired",
"err_msg",
"check_dtype",
"check_shape",
"check_scalar"
] | None | true | 2 | 6.24 | scikit-learn/scikit-learn | 64,340 | numpy | false |
getCentroids | private static ArrayList<Double> getCentroids(
String mappedFieldName,
XContentParser parser,
BiFunction<XContentLocation, String, RuntimeException> documentParsingExceptionProvider,
ParsingExceptionProvider parsingExceptionProvider
) throws IOException {
XContentParser.Token... | Parses an XContent object into a histogram.
The parser is expected to point at the next token after {@link XContentParser.Token#START_OBJECT}.
@param mappedFieldName the name of the field being parsed, used for error messages
@param parser the parser to use
@param documentParsingExceptionProvider factory function for g... | java | libs/tdigest/src/main/java/org/elasticsearch/tdigest/parsing/TDigestParser.java | 216 | [
"mappedFieldName",
"parser",
"documentParsingExceptionProvider",
"parsingExceptionProvider"
] | true | 3 | 7.6 | elastic/elasticsearch | 75,680 | javadoc | false | |
resolveCandidate | public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
throws BeansException {
try {
// Need to provide required type for SmartFactoryBean
return beanFactory.getBean(beanName, requiredType);
}
catch (BeanNotOfRequiredTypeException ex) {
// Probably a null bean... | Resolve the specified bean name, as a candidate result of the matching
algorithm for this dependency, to a bean instance from the given factory.
<p>The default implementation calls {@link BeanFactory#getBean(String, Class)}.
Subclasses may provide additional arguments or other customizations.
@param beanName the bean n... | java | spring-beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java | 224 | [
"beanName",
"requiredType",
"beanFactory"
] | Object | true | 2 | 7.6 | spring-projects/spring-framework | 59,386 | javadoc | false |
deselect | def deselect(self, exclude):
"""Deselect queues so that they won't be consumed from.
Arguments:
exclude (Sequence[str], str): Names of queues to avoid
consuming from.
"""
if exclude:
exclude = maybe_list(exclude)
if self._consume_from ... | Deselect queues so that they won't be consumed from.
Arguments:
exclude (Sequence[str], str): Names of queues to avoid
consuming from. | python | celery/app/amqp.py | 179 | [
"self",
"exclude"
] | false | 4 | 6.08 | celery/celery | 27,741 | google | false | |
ndim | def ndim(self) -> int:
"""
Return an int representing the number of axes / array dimensions.
Return 1 if Series. Otherwise return 2 if DataFrame.
See Also
--------
numpy.ndarray.ndim : Number of array dimensions.
Examples
--------
>>> s = pd.Ser... | Return an int representing the number of axes / array dimensions.
Return 1 if Series. Otherwise return 2 if DataFrame.
See Also
--------
numpy.ndarray.ndim : Number of array dimensions.
Examples
--------
>>> s = pd.Series({"a": 1, "b": 2, "c": 3})
>>> s.ndim
1
>>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})... | python | pandas/core/generic.py | 645 | [
"self"
] | int | true | 1 | 6.08 | pandas-dev/pandas | 47,362 | unknown | false |
toString | @Override
public @Nullable String toString() {
return (this.value != null) ? this.value.toString() : null;
} | Return the tracked value.
@return the tracked value | java | core/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java | 70 | [] | String | true | 2 | 8.16 | spring-projects/spring-boot | 79,428 | javadoc | false |
loadFinalizer | private static Class<?> loadFinalizer(FinalizerLoader... loaders) {
for (FinalizerLoader loader : loaders) {
Class<?> finalizer = loader.loadFinalizer();
if (finalizer != null) {
return finalizer;
}
}
throw new AssertionError();
} | Iterates through the given loaders until it finds one that can load Finalizer.
@return Finalizer.class | java | android/guava/src/com/google/common/base/FinalizableReferenceQueue.java | 261 | [] | true | 2 | 7.92 | google/guava | 51,352 | javadoc | false | |
createSpringApplicationBuilder | protected SpringApplicationBuilder createSpringApplicationBuilder() {
return new SpringApplicationBuilder();
} | Returns the {@code SpringApplicationBuilder} that is used to configure and create
the {@link SpringApplication}. The default implementation returns a new
{@code SpringApplicationBuilder} in its default state.
@return the {@code SpringApplicationBuilder}. | java | core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java | 195 | [] | SpringApplicationBuilder | true | 1 | 6.16 | spring-projects/spring-boot | 79,428 | javadoc | false |
checkHealthy | @GuardedBy("monitor")
void checkHealthy() {
if (states.count(RUNNING) != numberOfServices) {
IllegalStateException exception =
new IllegalStateException(
"Expected to be healthy after starting. The following services are not running: "
+ Multimaps.filter... | Attempts to execute all the listeners in {@link #listeners}. | java | android/guava/src/com/google/common/util/concurrent/ServiceManager.java | 763 | [] | void | true | 2 | 6.88 | google/guava | 51,352 | javadoc | false |
toString | @Override
public String toString() {
return "FastDatePrinter[" + pattern + "," + locale + "," + timeZone.getID() + "]";
} | Gets a debugging string version of this formatter.
@return a debugging string. | java | src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java | 1,561 | [] | String | true | 1 | 6.8 | apache/commons-lang | 2,896 | javadoc | false |
findIntersectionPoint | private Vec2d findIntersectionPoint(Vec2d orig2d0, Vec2d orig2d1, int adjRes, int faceDir) {
// find the appropriate icosa face edge vertexes
final Vec2d edge0;
final Vec2d edge1;
switch (faceDir) {
case IJ -> {
edge0 = maxDimByCIIVec2d[adjRes][0];
... | Generates the cell boundary in spherical coordinates for a cell given by this
FaceIJK address at a specified resolution.
@param res The H3 resolution of the cell. | java | libs/h3/src/main/java/org/elasticsearch/h3/FaceIJK.java | 643 | [
"orig2d0",
"orig2d1",
"adjRes",
"faceDir"
] | Vec2d | true | 3 | 6.72 | elastic/elasticsearch | 75,680 | javadoc | false |
setbufsize | def setbufsize(size):
"""
Set the size of the buffer used in ufuncs.
.. versionchanged:: 2.0
The scope of setting the buffer is tied to the `numpy.errstate`
context. Exiting a ``with errstate():`` will also restore the bufsize.
Parameters
----------
size : int
Size of ... | Set the size of the buffer used in ufuncs.
.. versionchanged:: 2.0
The scope of setting the buffer is tied to the `numpy.errstate`
context. Exiting a ``with errstate():`` will also restore the bufsize.
Parameters
----------
size : int
Size of buffer.
Returns
-------
bufsize : int
Previous size of uf... | python | numpy/_core/_ufunc_config.py | 162 | [
"size"
] | false | 2 | 7.68 | numpy/numpy | 31,054 | numpy | false | |
toString | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Configuration problem: ");
sb.append(getMessage());
sb.append("\nOffending resource: ").append(getResourceDescription());
if (getParseState() != null) {
sb.append('\n').append(getParseState());
}
return sb.toString... | Get the underlying exception that caused the error (may be {@code null}). | java | spring-beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java | 119 | [] | String | true | 2 | 7.04 | spring-projects/spring-framework | 59,386 | javadoc | false |
getRootNode | function getRootNode() {
if (rootNode) {
return rootNode;
}
const usePartialParsing = vscode.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
if (editor.selections.length === 1 && isStyleSheet(editor.document.languageId) && usePartialParsing && editor.document.lineCount > 1000) {
... | Short circuit the parsing. If previous character is space, do not expand. | typescript | extensions/emmet/src/abbreviationActions.ts | 355 | [] | false | 8 | 6.24 | microsoft/vscode | 179,840 | jsdoc | false | |
saturatedCast | public static byte saturatedCast(long value) {
if (value > Byte.MAX_VALUE) {
return Byte.MAX_VALUE;
}
if (value < Byte.MIN_VALUE) {
return Byte.MIN_VALUE;
}
return (byte) value;
} | Returns the {@code byte} nearest in value to {@code value}.
@param value any {@code long} value
@return the same value cast to {@code byte} if it is in the range of the {@code byte} type,
{@link Byte#MAX_VALUE} if it is too large, or {@link Byte#MIN_VALUE} if it is too small | java | android/guava/src/com/google/common/primitives/SignedBytes.java | 70 | [
"value"
] | true | 3 | 7.92 | google/guava | 51,352 | javadoc | false | |
paused | @Override
public Set<TopicPartition> paused() {
return delegate.paused();
} | Get the set of partitions that were previously paused by a call to {@link #pause(Collection)}.
@return The set of paused partitions | java | clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java | 1,560 | [] | true | 1 | 6.96 | apache/kafka | 31,560 | javadoc | false | |
ensureNoSelfReferences | private static void ensureNoSelfReferences(Object value) {
Iterable<?> it = convert(value);
if (it != null) {
ensureNoSelfReferences(it, value, Collections.newSetFromMap(new IdentityHashMap<>()));
}
} | Returns a version used for serialising a response.
@return a compatible version | java | libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java | 1,309 | [
"value"
] | void | true | 2 | 6.72 | elastic/elasticsearch | 75,680 | javadoc | false |
describe_processing_job | def describe_processing_job(self, name: str) -> dict:
"""
Get the processing job info associated with the name.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_processing_job`
:param name: the name of the processing job
:return: A dict contains all... | Get the processing job info associated with the name.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_processing_job`
:param name: the name of the processing job
:return: A dict contains all the processing job info | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py | 676 | [
"self",
"name"
] | dict | true | 1 | 6.24 | apache/airflow | 43,597 | sphinx | false |
getContextPairs | private ContextPairs getContextPairs(@Nullable StructuredLoggingJsonProperties properties) {
Context contextProperties = (properties != null) ? properties.context() : null;
contextProperties = (contextProperties != null) ? contextProperties : new Context(true, null);
return new ContextPairs(contextProperties.incl... | Create a new {@link StructuredLogFormatterFactory} instance.
@param logEventType the log event type
@param environment the Spring {@link Environment}
@param availableParameters callback used to configure available parameters for the
specific logging system
@param commonFormatters callback used to define supported commo... | java | core/spring-boot/src/main/java/org/springframework/boot/logging/structured/StructuredLogFormatterFactory.java | 110 | [
"properties"
] | ContextPairs | true | 3 | 6.08 | spring-projects/spring-boot | 79,428 | javadoc | false |
maybeRecordDeprecatedBytesFetched | @Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedBytesFetched(String name, String topic, int bytes) {
if (shouldReportDeprecatedMetric(topic)) {
Sensor deprecatedBytesFetched = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicTags(topic))
... | This method is called by the {@link Fetch fetch} logic before it requests fetches in order to update the
internal set of metrics that are tracked.
@param subscription {@link SubscriptionState} that contains the set of assigned partitions
@see SubscriptionState#assignmentId() | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchMetricsManager.java | 200 | [
"name",
"topic",
"bytes"
] | void | true | 2 | 6.24 | apache/kafka | 31,560 | javadoc | false |
boxedTypeIsInstanceOf | private boolean boxedTypeIsInstanceOf(T existingValue) {
Class<?> resolved = this.boxedType.resolve();
return resolved != null && resolved.isInstance(existingValue);
} | Create an updated {@link Bindable} instance with an existing value. Implies that
Java Bean binding will be used.
@param existingValue the existing value
@return an updated {@link Bindable} | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Bindable.java | 204 | [
"existingValue"
] | true | 2 | 7.68 | spring-projects/spring-boot | 79,428 | javadoc | false | |
areNeighborCells | public static boolean areNeighborCells(String origin, String destination) {
return areNeighborCells(stringToH3(origin), stringToH3(destination));
} | returns whether or not the provided hexagons border
@param origin the first index
@param destination the second index
@return whether or not the provided hexagons border | java | libs/h3/src/main/java/org/elasticsearch/h3/H3.java | 427 | [
"origin",
"destination"
] | true | 1 | 6.16 | elastic/elasticsearch | 75,680 | javadoc | false | |
run | protected ExitStatus run(OptionSet options) throws Exception {
return ExitStatus.OK;
} | Run the command using the specified parsed {@link OptionSet}.
@param options the parsed option set
@return an ExitStatus
@throws Exception in case of errors | java | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java | 115 | [
"options"
] | ExitStatus | true | 1 | 6.48 | spring-projects/spring-boot | 79,428 | javadoc | false |
addConstructorReferences | function addConstructorReferences(referenceLocation: Node, sourceFile: SourceFile, search: Search, state: State): void {
if (isNewExpressionTarget(referenceLocation)) {
addReference(referenceLocation, search.symbol, state);
}
const pusher = () => state.referenceAdder(search.sym... | Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. | typescript | src/services/findAllReferences.ts | 2,133 | [
"referenceLocation",
"sourceFile",
"search",
"state"
] | true | 6 | 6 | microsoft/TypeScript | 107,154 | jsdoc | false | |
__call__ | def __call__(self, X, Y=None, eval_gradient=False):
"""Return the kernel k(X, Y) and optionally its gradient.
Parameters
----------
X : ndarray of shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y)
Y : ndarray of shape (n_samples_Y, n_featu... | Return the kernel k(X, Y) and optionally its gradient.
Parameters
----------
X : ndarray of shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y)
Y : ndarray of shape (n_samples_Y, n_features), default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X)
if evaluated... | python | sklearn/gaussian_process/kernels.py | 1,879 | [
"self",
"X",
"Y",
"eval_gradient"
] | false | 11 | 6 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
getReducedFraction | public static Fraction getReducedFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (numerator == 0) {
return ZERO; // normalize zero.
}
// allow 2^k/-2^31 as a valid f... | Creates a reduced {@link Fraction} instance with the 2 parts of a fraction Y/Z.
<p>
For example, if the input parameters represent 2/4, then the created fraction will be 1/2.
</p>
<p>
Any negative signs are resolved to be on the numerator.
</p>
@param numerator the numerator, for example the three in 'three sevenths'... | java | src/main/java/org/apache/commons/lang3/math/Fraction.java | 312 | [
"numerator",
"denominator"
] | Fraction | true | 8 | 7.92 | apache/commons-lang | 2,896 | javadoc | false |
inspect_excel_format | def inspect_excel_format(
content_or_path: FilePath | ReadBuffer[bytes],
storage_options: StorageOptions | None = None,
) -> str | None:
"""
Inspect the path or content of an excel file and get its format.
Adopted from xlrd: https://github.com/python-excel/xlrd.
Parameters
----------
c... | Inspect the path or content of an excel file and get its format.
Adopted from xlrd: https://github.com/python-excel/xlrd.
Parameters
----------
content_or_path : str or file-like object
Path to file or content of file to inspect. May be a URL.
storage_options : dict, optional
Extra options that make sense for... | python | pandas/io/excel/_base.py | 1,417 | [
"content_or_path",
"storage_options"
] | str | None | true | 7 | 6.48 | pandas-dev/pandas | 47,362 | numpy | false |
list_training_jobs | def list_training_jobs(
self, name_contains: str | None = None, max_results: int | None = None, **kwargs
) -> list[dict]:
"""
Call boto3's ``list_training_jobs``.
The training job name and max results are configurable via arguments.
Other arguments are not, and should be pro... | Call boto3's ``list_training_jobs``.
The training job name and max results are configurable via arguments.
Other arguments are not, and should be provided via kwargs. Note that
boto3 expects these in CamelCase, for example:
.. code-block:: python
list_training_jobs(name_contains="myjob", StatusEquals="Failed")
... | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py | 859 | [
"self",
"name_contains",
"max_results"
] | list[dict] | true | 1 | 6.24 | apache/airflow | 43,597 | sphinx | false |
merge_to_set | def merge_to_set(self, existing_node: fx.Node, new_node: fx.Node) -> None:
"""
Merge new_node into existing_node's set. The new node must be a singleton set.
"""
existing_set = self.merge_sets[existing_node]
new_set = self.merge_sets[new_node]
assert len(new_set) == 1
... | Merge new_node into existing_node's set. The new node must be a singleton set. | python | torch/_inductor/augmented_graph_helper.py | 45 | [
"self",
"existing_node",
"new_node"
] | None | true | 2 | 6 | pytorch/pytorch | 96,034 | unknown | false |
preparedTransactionState | public ProducerIdAndEpoch preparedTransactionState() {
return this.preparedTxnState;
} | Returns a ProducerIdAndEpoch object containing the producer ID and epoch
of the ongoing transaction.
This is used when preparing a transaction for a two-phase commit.
@return a ProducerIdAndEpoch with the current producer ID and epoch. | java | clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java | 1,978 | [] | ProducerIdAndEpoch | true | 1 | 6.48 | apache/kafka | 31,560 | javadoc | false |
getExitCodeFromExitCodeGeneratorException | private int getExitCodeFromExitCodeGeneratorException(@Nullable Throwable exception) {
if (exception == null) {
return 0;
}
if (exception instanceof ExitCodeGenerator generator) {
return generator.getExitCode();
}
return getExitCodeFromExitCodeGeneratorException(exception.getCause());
} | 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 | 912 | [
"exception"
] | true | 3 | 7.04 | spring-projects/spring-boot | 79,428 | javadoc | false | |
initializeNextAcquired | private void initializeNextAcquired() {
if (nextAcquired == null) {
if (acquiredRecordIterator == null) {
acquiredRecordIterator = acquiredRecordList.listIterator();
}
if (acquiredRecordIterator.hasNext()) {
nextAcquired = acquiredRecordIterato... | The {@link RecordBatch batch} of {@link Record records} is converted to a {@link List list} of
{@link ConsumerRecord consumer records} and returned. {@link BufferSupplier Decompression} and
{@link Deserializer deserialization} of the {@link Record record's} key and value are performed in
this step.
@param deserializers... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareCompletedFetch.java | 264 | [] | void | true | 4 | 7.6 | apache/kafka | 31,560 | javadoc | false |
close | @Override
public void close() {
if (closed == false) {
closed = true;
arrays.adjustBreaker(-SHALLOW_SIZE);
Releasables.close(summary);
}
} | Returns an upper bound on the number bytes that will be required to represent this histogram. | java | libs/tdigest/src/main/java/org/elasticsearch/tdigest/AVLTreeDigest.java | 381 | [] | void | true | 2 | 6.88 | elastic/elasticsearch | 75,680 | javadoc | false |
setAccessible | static Field setAccessible(final Field field, final boolean forceAccess) {
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
MemberUtils.setAccessibleWorkaround(field);
}
return field;
} | Removes the final modifier from a {@link Field}.
@param field
to remove the final modifier.
@param forceAccess
whether to break scope restrictions using the
{@link AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@throws Nu... | java | src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java | 608 | [
"field",
"forceAccess"
] | Field | true | 3 | 6.24 | apache/commons-lang | 2,896 | javadoc | false |
normalizeScale | static int normalizeScale(long index, int scale) {
return Math.max(MIN_SCALE, scale - Long.numberOfTrailingZeros(index));
} | Returns a scale at to which the given index can be scaled down without changing the exponentially scaled number it represents.
@param index the index of the number
@param scale the current scale of the number
@return the new scale | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialScaleUtils.java | 194 | [
"index",
"scale"
] | true | 1 | 6.96 | elastic/elasticsearch | 75,680 | javadoc | false | |
deleteStreamsGroups | DeleteStreamsGroupsResult deleteStreamsGroups(Collection<String> groupIds, DeleteStreamsGroupsOptions options); | Delete streams groups from the cluster.
<em>Note</em>: this method effectively does the same as the corresponding consumer group method {@link Admin#deleteConsumerGroups} does.
@param options The options to use when deleting a streams group.
@return The DeleteStreamsGroupsResult. | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 1,003 | [
"groupIds",
"options"
] | DeleteStreamsGroupsResult | true | 1 | 6 | apache/kafka | 31,560 | javadoc | false |
ravel | def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> Self:
"""
Return a flattened view on this array.
Parameters
----------
order : {None, 'C', 'F', 'A', 'K'}, default 'C'
Returns
-------
ExtensionArray
A flattened view on the ... | Return a flattened view on this array.
Parameters
----------
order : {None, 'C', 'F', 'A', 'K'}, default 'C'
Returns
-------
ExtensionArray
A flattened view on the array.
See Also
--------
ExtensionArray.tolist: Return a list of the values.
Notes
-----
- Because ExtensionArrays are 1D-only, this is a no-op.
- T... | python | pandas/core/arrays/base.py | 2,109 | [
"self",
"order"
] | Self | true | 1 | 7.12 | pandas-dev/pandas | 47,362 | numpy | false |
_get_inductor_debug_symbol_cflags | def _get_inductor_debug_symbol_cflags() -> tuple[list[str], list[str]]:
"""
When we turn on generate debug symbol.
On Windows, it should create a [module_name].pdb file. It helps debug by WinDBG.
On Linux, it should create some debug sections in binary file.
"""
cflags: list[str] = []
ldflag... | When we turn on generate debug symbol.
On Windows, it should create a [module_name].pdb file. It helps debug by WinDBG.
On Linux, it should create some debug sections in binary file. | python | torch/_inductor/cpp_builder.py | 860 | [] | tuple[list[str], list[str]] | true | 3 | 6.88 | pytorch/pytorch | 96,034 | unknown | false |
toZoneId | private static ZoneId toZoneId(final Calendar calendar) {
return calendar.getTimeZone().toZoneId();
} | Converts a Calendar to a ZonedDateTime.
@param calendar the Calendar to convert.
@return a ZonedDateTime.
@since 3.17.0 | java | src/main/java/org/apache/commons/lang3/time/CalendarUtils.java | 100 | [
"calendar"
] | ZoneId | true | 1 | 6.32 | apache/commons-lang | 2,896 | javadoc | false |
isBalanced | private boolean isBalanced() {
int min = currentAssignment.get(sortedCurrentSubscriptions.first()).size();
int max = currentAssignment.get(sortedCurrentSubscriptions.last()).size();
if (min >= max - 1)
// if minimum and maximum numbers of partitions assigned to consum... | determine if the current assignment is a balanced one
@return true if the given assignment is balanced; false otherwise | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractStickyAssignor.java | 1,170 | [] | true | 7 | 7.76 | apache/kafka | 31,560 | javadoc | false | |
removeAt | static Object removeAt(final Object array, final BitSet indices) {
if (array == null) {
return null;
}
final int srcLength = getLength(array);
// No need to check maxIndex here, because method only currently called from removeElements()
// which guarantee to generate ... | Removes multiple array elements specified by indices.
@param array the input array, will not be modified, and may be {@code null}.
@param indices to remove.
@return new array of same type minus elements specified by the set bits in {@code indices}. | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 5,585 | [
"array",
"indices"
] | Object | true | 5 | 8.4 | apache/commons-lang | 2,896 | javadoc | false |
changeState | protected void changeState(final State newState) {
if (state.compareAndSet(newState.oppositeState(), newState)) {
changeSupport.firePropertyChange(PROPERTY_NAME, !isOpen(newState), isOpen(newState));
}
} | Changes the internal state of this circuit breaker. If there is actually a change
of the state value, all registered change listeners are notified.
@param newState the new state to be set | java | src/main/java/org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.java | 116 | [
"newState"
] | void | true | 2 | 6.72 | apache/commons-lang | 2,896 | javadoc | false |
createCollection | @Override
Collection<V> createCollection(@ParametricNullness K key) {
return new ValueSet(key, valueSetCapacity);
} | {@inheritDoc}
<p>Creates a decorated insertion-ordered set that also keeps track of the order in which
key-value pairs are added to the multimap.
@param key key to associate with values in the collection
@return a new decorated set containing a collection of values for one key | java | android/guava/src/com/google/common/collect/LinkedHashMultimap.java | 192 | [
"key"
] | true | 1 | 6.48 | google/guava | 51,352 | javadoc | false | |
deleteFilesIgnoringExceptions | public static void deleteFilesIgnoringExceptions(final Path... files) {
for (final Path name : files) {
if (name != null) {
// noinspection EmptyCatchBlock
try {
Files.delete(name);
} catch (final IOException ignored) {
... | Deletes all given files, suppressing all thrown {@link IOException}s. Some of the files may be null, if so they are ignored.
@param files the paths of files to delete | java | libs/core/src/main/java/org/elasticsearch/core/IOUtils.java | 178 | [] | void | true | 3 | 7.04 | elastic/elasticsearch | 75,680 | javadoc | false |
getInternalBeanFactoryForBean | protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) {
synchronized (this.internalBeanFactories) {
return this.internalBeanFactories.computeIfAbsent(beanName,
name -> buildInternalBeanFactory(getConfigurableBeanFactory()));
}
} | Return the internal BeanFactory to be used for the specified bean.
@param beanName the name of the target bean
@return the internal BeanFactory to be used | java | spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java | 130 | [
"beanName"
] | DefaultListableBeanFactory | true | 1 | 6.56 | spring-projects/spring-framework | 59,386 | javadoc | false |
transitionToStale | private void transitionToStale() {
transitionTo(MemberState.STALE);
// Release assignment
CompletableFuture<Void> callbackResult = signalPartitionsLost(subscriptions.assignedPartitions());
staleMemberAssignmentRelease = callbackResult.whenComplete((result, error) -> {
if (er... | Transition to STALE to release assignments because the member has left the group due to
expired poll timer. This will trigger the onPartitionsLost callback. Once the callback
completes, the member will remain stale until the poll timer is reset by an application
poll event. See {@link #maybeRejoinStaleMember()}. | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java | 791 | [] | void | true | 2 | 6.88 | apache/kafka | 31,560 | javadoc | false |
get | T get(Supplier<T> factory, UnaryOperator<T> refreshAction) {
T value = getValue();
if (value == null) {
value = refreshAction.apply(factory.get());
setValue(value);
}
else if (hasExpired()) {
value = refreshAction.apply(value);
setValue(value);
}
if (!this.neverExpire) {
this.lastAccessed = n... | Get a value from the cache, creating it if necessary.
@param factory a factory used to create the item if there is no reference to it.
@param refreshAction action called to refresh the value if it has expired
@return the value from the cache | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SoftReferenceConfigurationPropertyCache.java | 99 | [
"factory",
"refreshAction"
] | T | true | 4 | 7.92 | spring-projects/spring-boot | 79,428 | javadoc | false |
partitionsFor | @Override
public List<PartitionInfo> partitionsFor(String topic) {
return delegate.partitionsFor(topic);
} | Get metadata about the partitions for a given topic. This method will issue a remote call to the server if it
does not already have any metadata about the given topic.
@param topic The topic to get partition metadata for
@return The list of partitions, which will be empty when the given topic is not found
@throws org.a... | java | clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java | 1,420 | [
"topic"
] | true | 1 | 6.16 | apache/kafka | 31,560 | javadoc | false | |
estimate_peak_memory | def estimate_peak_memory(
nodes: list[BaseSchedulerNode],
name_to_freeable_input_buf: dict[str, FreeableInputBuffer],
graph_outputs: OrderedSet[str],
) -> tuple[int, list[int]]:
"""
Given a list of nodes in their execution order, estimate the peak memory, by
keeping track of the liveliness of Sc... | Given a list of nodes in their execution order, estimate the peak memory, by
keeping track of the liveliness of SchedulerBuffers and FreeableInputBuffers.
Returns:
int: peak memory
List[int]: memory usage at each node (or each step). | python | torch/_inductor/memory.py | 435 | [
"nodes",
"name_to_freeable_input_buf",
"graph_outputs"
] | tuple[int, list[int]] | true | 3 | 7.92 | pytorch/pytorch | 96,034 | unknown | false |
maybeRecordDeprecatedRecordsFetched | @Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedRecordsFetched(String name, String topic, int records) {
if (shouldReportDeprecatedMetric(topic)) {
Sensor deprecatedRecordsFetched = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicTags(topic)... | This method is called by the {@link Fetch fetch} logic before it requests fetches in order to update the
internal set of metrics that are tracked.
@param subscription {@link SubscriptionState} that contains the set of assigned partitions
@see SubscriptionState#assignmentId() | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchMetricsManager.java | 212 | [
"name",
"topic",
"records"
] | void | true | 2 | 6.24 | apache/kafka | 31,560 | javadoc | false |
splitMultilineString | function splitMultilineString(source: nbformat.MultilineString): string[] {
if (Array.isArray(source)) {
return source as string[];
}
const str = source.toString();
if (str.length > 0) {
// Each line should be a separate entry, but end with a \n if not last entry
const arr = str.split('\n');
return arr
.... | Splits the source of a cell into an array of strings, each representing a line.
Also normalizes line endings to use LF (`\n`) instead of CRLF (`\r\n`).
Same is done in deserializer as well. | typescript | extensions/ipynb/src/serializers.ts | 141 | [
"source"
] | true | 4 | 6 | microsoft/vscode | 179,840 | jsdoc | false | |
ipByteBit | public static int ipByteBit(byte[] q, byte[] d) {
if (q.length != d.length * Byte.SIZE) {
throw new IllegalArgumentException("vector dimensions incompatible: " + q.length + "!= " + Byte.SIZE + " x " + d.length);
}
return IMPL.ipByteBit(q, d);
} | Compute the inner product of two vectors, where the query vector is a byte vector and the document vector is a bit vector.
This will return the sum of the query vector values using the document vector as a mask.
When comparing the bits with the bytes, they are done in "big endian" order. For example, if the byte vector... | java | libs/simdvec/src/main/java/org/elasticsearch/simdvec/ESVectorUtil.java | 85 | [
"q",
"d"
] | true | 2 | 8.24 | elastic/elasticsearch | 75,680 | javadoc | false | |
uniqueIndex | @CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values, keyFunction, ImmutableMap.builder());
} | Returns a map with the given {@code values}, indexed by keys derived from those values. In
other words, each input value produces an entry in the map whose key is the result of applying
{@code keyFunction} to that value. These entries appear in the same order as the input values.
Example usage:
{@snippet :
Color red = ... | java | android/guava/src/com/google/common/collect/Maps.java | 1,331 | [
"values",
"keyFunction"
] | true | 1 | 6.56 | google/guava | 51,352 | javadoc | false | |
collectActiveRouteConfigs | function collectActiveRouteConfigs(
activatedRoute: ActivatedRoute,
activeRoutes: Set<AngularRoute> = new Set(),
): Set<AngularRoute> {
// Get the routeConfig for this ActivatedRoute
const routeConfig = activatedRoute.routeConfig;
if (routeConfig) {
activeRoutes.add(routeConfig);
}
// Recursively pro... | Recursively traverses the ActivatedRoute tree and collects all routeConfig objects.
@param activatedRoute - The ActivatedRoute to start traversal from
@param activeRoutes - Set to collect active Route configuration objects
@returns Set of active Route configuration objects | typescript | devtools/projects/ng-devtools-backend/src/lib/router-tree.ts | 33 | [
"activatedRoute",
"activeRoutes"
] | true | 3 | 7.44 | angular/angular | 99,544 | jsdoc | false | |
forIn | function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
} | Iterates over own and inherited enumerable string keyed properties of an
object and invokes `iteratee` for each property. The iteratee is invoked
with three arguments: (value, key, object). Iteratee functions may exit
iteration early by explicitly returning `false`.
@static
@memberOf _
@since 0.3.0
@category Object
@pa... | javascript | lodash.js | 13,054 | [
"object",
"iteratee"
] | false | 2 | 7.04 | lodash/lodash | 61,490 | jsdoc | false | |
open | static JarUrlConnection open(URL url) throws IOException {
String spec = url.getFile();
if (spec.startsWith("nested:")) {
int separator = spec.indexOf("!/");
boolean specHasEntry = (separator != -1) && (separator + 2 != spec.length());
if (specHasEntry) {
URL jarFileUrl = new URL(spec.substring(0, sepa... | The {@link URLClassLoader} connects often to check if a resource exists, we can
save some object allocations by using the cached copy if we have one.
@param jarFileURL the jar file to check
@param entryName the entry name to check
@throws FileNotFoundException on a missing entry | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrlConnection.java | 334 | [
"url"
] | JarUrlConnection | true | 6 | 6.72 | spring-projects/spring-boot | 79,428 | javadoc | false |
intersection | public static MethodMatcher intersection(MethodMatcher mm1, MethodMatcher mm2) {
return (mm1 instanceof IntroductionAwareMethodMatcher || mm2 instanceof IntroductionAwareMethodMatcher ?
new IntersectionIntroductionAwareMethodMatcher(mm1, mm2) : new IntersectionMethodMatcher(mm1, mm2));
} | Match all methods that <i>both</i> of the given MethodMatchers match.
@param mm1 the first MethodMatcher
@param mm2 the second MethodMatcher
@return a distinct MethodMatcher that matches all methods that both
of the given MethodMatchers match | java | spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java | 81 | [
"mm1",
"mm2"
] | MethodMatcher | true | 3 | 7.84 | spring-projects/spring-framework | 59,386 | javadoc | false |
toString | @Override
public String toString() {
return topicId + ":" + topic() + "-" + partition();
} | @return Topic partition representing this instance. | java | clients/src/main/java/org/apache/kafka/common/TopicIdPartition.java | 102 | [] | String | true | 1 | 6.32 | apache/kafka | 31,560 | javadoc | false |
substring | public String substring(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
return new String(buffer, startIndex, endIndex - startIndex);
} | Extracts a portion of this string builder as a string.
<p>
Note: This method treats an endIndex greater than the length of the
builder as equal to the length of the builder, and continues
without error, unlike StringBuffer or String.
</p>
@param startIndex the start index, inclusive, must be valid
@param endIndex the... | java | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | 2,926 | [
"startIndex",
"endIndex"
] | String | true | 1 | 6.48 | apache/commons-lang | 2,896 | javadoc | false |
createPointcut | protected AbstractRegexpMethodPointcut createPointcut() {
return new JdkRegexpMethodPointcut();
} | Create the actual pointcut: By default, a {@link JdkRegexpMethodPointcut}
will be used.
@return the Pointcut instance (never {@code null}) | java | spring-aop/src/main/java/org/springframework/aop/support/RegexpMethodPointcutAdvisor.java | 138 | [] | AbstractRegexpMethodPointcut | true | 1 | 6.16 | spring-projects/spring-framework | 59,386 | javadoc | false |
allclose | def allclose(a, b, masked_equal=True, rtol=1e-5, atol=1e-8):
"""
Returns True if two arrays are element-wise equal within a tolerance.
This function is equivalent to `allclose` except that masked values
are treated as equal (default) or unequal, depending on the `masked_equal`
argument.
Parame... | Returns True if two arrays are element-wise equal within a tolerance.
This function is equivalent to `allclose` except that masked values
are treated as equal (default) or unequal, depending on the `masked_equal`
argument.
Parameters
----------
a, b : array_like
Input arrays to compare.
masked_equal : bool, optio... | python | numpy/ma/core.py | 8,446 | [
"a",
"b",
"masked_equal",
"rtol",
"atol"
] | false | 6 | 7.76 | numpy/numpy | 31,054 | numpy | false | |
copyArrayGrow1 | private static Object copyArrayGrow1(final Object array, final Class<?> newArrayComponentType) {
if (array != null) {
final int arrayLength = Array.getLength(array);
final Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
System.arrayc... | Returns a copy of the given array of size 1 greater than the argument.
The last value of the array is left to the default value.
@param array The array to copy, must not be {@code null}.
@param newArrayComponentType If {@code array} is {@code null}, create a
size 1 array of this type.
@return A new copy of the array of... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 1,793 | [
"array",
"newArrayComponentType"
] | Object | true | 2 | 8.08 | apache/commons-lang | 2,896 | javadoc | false |
addEventListener | public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
try {
MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
} catch (final ReflectiveOperationException e) {
throw new IllegalArgume... | Adds an event listener to the specified source. This looks for an "add" method corresponding to the event
type (addActionListener, for example).
@param eventSource the event source.
@param listenerType the event listener type.
@param listener the listener.
@param <L> the event listener type.
@throws ... | java | src/main/java/org/apache/commons/lang3/event/EventUtils.java | 97 | [
"eventSource",
"listenerType",
"listener"
] | void | true | 2 | 6.4 | apache/commons-lang | 2,896 | javadoc | false |
buildDefaultBeanName | protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
String shortClassName = ClassUtils.getShortName(beanClassName);
return StringUtils.uncapitalizeAsProperty(shortClassName);
} | Derive a default bean name from the given bean definition.
<p>The default implementation simply builds a decapitalized version
of the short class name: for example, "mypackage.MyJdbcDao" → "myJdbcDao".
<p>Note that inner classes will thus have names of the form
"outerClassName.InnerClassName", which because of the... | java | spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java | 247 | [
"definition"
] | String | true | 1 | 6.72 | spring-projects/spring-framework | 59,386 | javadoc | false |
getExitCodeFromException | private int getExitCodeFromException(@Nullable ConfigurableApplicationContext context, Throwable exception) {
int exitCode = getExitCodeFromMappedException(context, exception);
if (exitCode == 0) {
exitCode = getExitCodeFromExitCodeGeneratorException(exception);
}
return exitCode;
} | 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 | 894 | [
"context",
"exception"
] | true | 2 | 7.04 | spring-projects/spring-boot | 79,428 | javadoc | false | |
json_serialize_legacy | def json_serialize_legacy(value: Any) -> str | None:
"""
JSON serializer replicating legacy watchtower behavior.
The legacy `watchtower@2.0.1` json serializer function that serialized
datetime objects as ISO format and all other non-JSON-serializable to `null`.
:param value: the object to serializ... | JSON serializer replicating legacy watchtower behavior.
The legacy `watchtower@2.0.1` json serializer function that serialized
datetime objects as ISO format and all other non-JSON-serializable to `null`.
:param value: the object to serialize
:return: string representation of `value` if it is an instance of datetime ... | python | providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py | 55 | [
"value"
] | str | None | true | 2 | 7.76 | apache/airflow | 43,597 | sphinx | false |
poke | def poke(self, context: Context):
"""
Check if the object exists in the bucket to pull key.
:param self: the object itself
:param context: the context of the object
:returns: True if the object exists, False otherwise
"""
parsed_url = urlsplit(self.bucket_key)
... | Check if the object exists in the bucket to pull key.
:param self: the object itself
:param context: the context of the object
:returns: True if the object exists, False otherwise | python | providers/alibaba/src/airflow/providers/alibaba/cloud/sensors/oss_key.py | 66 | [
"self",
"context"
] | true | 6 | 8.24 | apache/airflow | 43,597 | sphinx | false | |
toApiVersion | public static ApiVersion toApiVersion(ApiKeys apiKey) {
return new ApiVersion()
.setApiKey(apiKey.id)
.setMinVersion(apiKey.oldestVersion())
.setMaxVersion(apiKey.latestVersion());
} | Find the common range of supported API versions between the locally
known range and that of another set.
@param listenerType the listener type which constrains the set of exposed APIs
@param activeControllerApiVersions controller ApiVersions
@param enableUnstableLastVersion whether unstable versions should be advertise... | java | clients/src/main/java/org/apache/kafka/common/requests/ApiVersionsResponse.java | 327 | [
"apiKey"
] | ApiVersion | true | 1 | 6.08 | apache/kafka | 31,560 | javadoc | false |
resetJoinGroupFuture | private synchronized void resetJoinGroupFuture() {
this.joinFuture = null;
} | Joins the group without starting the heartbeat thread.
If this function returns true, the state must always be in STABLE and heartbeat enabled.
If this function returns false, the state can be in one of the following:
* UNJOINED: got error response but times out before being able to re-join, heartbeat disabled
* PREP... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java | 562 | [] | void | true | 1 | 6.64 | apache/kafka | 31,560 | javadoc | false |
putmask | def putmask(a, mask, values): # , mode='raise'):
"""
Changes elements of an array based on conditional and input values.
This is the masked array version of `numpy.putmask`, for details see
`numpy.putmask`.
See Also
--------
numpy.putmask
Notes
-----
Using a masked array as `... | Changes elements of an array based on conditional and input values.
This is the masked array version of `numpy.putmask`, for details see
`numpy.putmask`.
See Also
--------
numpy.putmask
Notes
-----
Using a masked array as `values` will **not** transform a `ndarray` into
a `MaskedArray`.
Examples
--------
>>> import... | python | numpy/ma/core.py | 7,535 | [
"a",
"mask",
"values"
] | false | 8 | 6.64 | numpy/numpy | 31,054 | unknown | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.