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 = "the magic string is not correct; expected %r, got %r" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:] return major, minor
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; // Case 1, 3 else return buffer.getLong(TIMESTAMP_OFFSET); } }
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 - Compressed message using LOG_APPEND_TIME 3. wrapperRecordTimestampType = CREATE_TIME and wrapperRecordTimestamp is not null - Compressed message using CREATE_TIME @return the timestamp as determined above
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 details). Returns ------- triu_indices_from : tuple, shape(2) of ndarray, shape(N) Indices for the upper-triangle of `arr`. Examples -------- >>> import numpy as np Create a 4 by 4 array >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Pass the array to get the indices of the upper triangular elements. >>> triui = np.triu_indices_from(a) >>> triui (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) >>> a[triui] array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) This is syntactic sugar for triu_indices(). >>> np.triu_indices(a.shape[0]) (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) Use the `k` parameter to return the indices for the upper triangular array from the k-th diagonal. >>> triuim1 = np.triu_indices_from(a, k=1) >>> a[triuim1] array([ 1, 2, 3, 6, 7, 11]) See Also -------- triu_indices, triu, tril_indices_from """ if arr.ndim != 2: raise ValueError("input array must be 2-d") return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])
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, shape(N) Indices for the upper-triangle of `arr`. Examples -------- >>> import numpy as np Create a 4 by 4 array >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Pass the array to get the indices of the upper triangular elements. >>> triui = np.triu_indices_from(a) >>> triui (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) >>> a[triui] array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) This is syntactic sugar for triu_indices(). >>> np.triu_indices(a.shape[0]) (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) Use the `k` parameter to return the indices for the upper triangular array from the k-th diagonal. >>> triuim1 = np.triu_indices_from(a, k=1) >>> a[triuim1] array([ 1, 2, 3, 6, 7, 11]) See Also -------- triu_indices, triu, tril_indices_from
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 ExtensionArray. Parameters ---------- op : function An operator that takes arguments op(a, b) coerce_to_dtype : bool, default True boolean indicating whether to attempt to convert the result to the underlying ExtensionArray dtype. If it's not possible to create a new ExtensionArray with the values, an ndarray is returned instead. Returns ------- Callable[[Any, Any], Union[ndarray, ExtensionArray]] A method that can be bound to a class. When used, the method receives the two arguments, one of which is the instance of this class, and should return an ExtensionArray or an ndarray. Returning an ndarray may be necessary when the result of the `op` cannot be stored in the ExtensionArray. The dtype of the ndarray uses NumPy's normal inference rules. Examples -------- Given an ExtensionArray subclass called MyExtensionArray, use __add__ = cls._create_method(operator.add) in the class definition of MyExtensionArray to create the operator for addition, that will be based on the operator implementation of the underlying elements of the ExtensionArray """ def _binop(self, other): def convert_values(param): if isinstance(param, ExtensionArray) or is_list_like(param): ovalues = param else: # Assume its an object ovalues = [param] * len(self) return ovalues if isinstance(other, (ABCSeries, ABCIndex, ABCDataFrame)): # rely on pandas to unbox and dispatch to us return NotImplemented lvalues = self rvalues = convert_values(other) # If the operator is not defined for the underlying objects, # a TypeError should be raised res = [op(a, b) for (a, b) in zip(lvalues, rvalues, strict=True)] def _maybe_convert(arr): if coerce_to_dtype: # https://github.com/pandas-dev/pandas/issues/22850 # We catch all regular exceptions here, and fall back # to an ndarray. res = self._cast_pointwise_result(arr) if not isinstance(res, type(self)): # exception raised in _from_sequence; ensure we have ndarray res = np.asarray(arr) else: res = np.asarray(arr, dtype=result_dtype) return res if op.__name__ in {"divmod", "rdivmod"}: a, b = zip(*res, strict=True) return _maybe_convert(a), _maybe_convert(b) return _maybe_convert(res) op_name = f"__{op.__name__}__" return set_function_name(_binop, op_name, cls)
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 True boolean indicating whether to attempt to convert the result to the underlying ExtensionArray dtype. If it's not possible to create a new ExtensionArray with the values, an ndarray is returned instead. Returns ------- Callable[[Any, Any], Union[ndarray, ExtensionArray]] A method that can be bound to a class. When used, the method receives the two arguments, one of which is the instance of this class, and should return an ExtensionArray or an ndarray. Returning an ndarray may be necessary when the result of the `op` cannot be stored in the ExtensionArray. The dtype of the ndarray uses NumPy's normal inference rules. Examples -------- Given an ExtensionArray subclass called MyExtensionArray, use __add__ = cls._create_method(operator.add) in the class definition of MyExtensionArray to create the operator for addition, that will be based on the operator implementation of the underlying elements of the ExtensionArray
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)) { registration.addMapping(urlMapping); } registration.setLoadOnStartup(this.loadOnStartup); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } }
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(node); inFlightRequestCount.getAndAdd(-clearedRequests.size()); return clearedRequests::descendingIterator; } }
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. The valid range is 2-36, the default value is 2. padding : int, optional Number of zeros padded on the left. Default is 0 (no padding). Returns ------- out : str String representation of `number` in `base` system. See Also -------- binary_repr : Faster version of `base_repr` for base 2. Examples -------- >>> import numpy as np >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20' """ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if base > len(digits): raise ValueError("Bases greater than 36 not handled in base_repr.") elif base < 2: raise ValueError("Bases less than 2 not handled in base_repr.") num = abs(int(number)) res = [] while num: res.append(digits[num % base]) num //= base if padding: res.append('0' * padding) if number < 0: res.append('-') return ''.join(reversed(res or '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. The valid range is 2-36, the default value is 2. padding : int, optional Number of zeros padded on the left. Default is 0 (no padding). Returns ------- out : str String representation of `number` in `base` system. See Also -------- binary_repr : Faster version of `base_repr` for base 2. Examples -------- >>> import numpy as np >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20'
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 permission is denied """ permission_denied = False docker_permission_command = ["docker", "info"] command_result = run_command( docker_permission_command, no_output_dump_on_exception=True, capture_output=True, text=True, check=False, ) if command_result.returncode != 0: permission_denied = True if command_result.stdout and "Got permission denied while trying to connect" in command_result.stdout: get_console().print( "ERROR: You have `permission denied` error when trying to communicate with docker." ) get_console().print( "Most likely you need to add your user to `docker` group: \ https://docs.docker.com/ engine/install/linux-postinstall/ ." ) return permission_denied
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. intersect : bool, default False If True, calculate the intersection between indexes. Otherwise, calculate the union. sort : bool, default False Whether the result index should come out sorted or not. NoDefault used for deprecation of GH#57335 Returns ------- Index """ # TODO: handle index names! indexes = _get_distinct_objs(indexes) if len(indexes) == 0: index: Index = default_index(0) elif len(indexes) == 1: index = indexes[0] elif intersect: index = indexes[0] for other in indexes[1:]: index = index.intersection(other) else: index = union_indexes(indexes, sort=sort if sort is lib.no_default else False) index = ensure_index(index) if sort and sort is not lib.no_default: index = safe_sort_index(index) return 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. intersect : bool, default False If True, calculate the intersection between indexes. Otherwise, calculate the union. sort : bool, default False Whether the result index should come out sorted or not. NoDefault used for deprecation of GH#57335 Returns ------- Index
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_ENVIRONMENT_PROPERTY_SOURCE_NAME)); }
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_path(input_code) Run result: name = c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc dir = /tmp/tmpof1n5g7t/5c/ put 'name' and 'dir' to CppBuilder's 'name' and 'output_dir'. CppBuilder --> get_target_file_path will format output path according OS: Linux: /tmp/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.so Windows: [Windows temp path]/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.dll """ name_and_ext = os.path.basename(file_path) name, _ext = os.path.splitext(name_and_ext) dir = os.path.dirname(file_path) return name, dir
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/tmpof1n5g7t/5c/ put 'name' and 'dir' to CppBuilder's 'name' and 'output_dir'. CppBuilder --> get_target_file_path will format output path according OS: Linux: /tmp/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.so Windows: [Windows temp path]/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.dll
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 match. String bestNameMatch = null; for (String mappedName : this.nameMap.keySet()) { if (isMatch(methodName, mappedName) && (bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) { ops = this.nameMap.get(mappedName); bestNameMatch = mappedName; } } } return ops; }
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_to_kill: List of PID to be killed. :param timeout: The time to wait before sending the SIGKILL signal. """ this_process = psutil.Process(os.getpid()) # Only check child processes to ensure that we don't have a case # where we kill the wrong process because a child process died # but the PID got reused. child_processes = [ x for x in this_process.children(recursive=True) if x.is_running() and x.pid in pids_to_kill ] # First try SIGTERM for child in child_processes: log.info("Terminating child PID: %s", child.pid) child.terminate() log.info("Waiting up to %s seconds for processes to exit...", timeout) try: psutil.wait_procs( child_processes, timeout=timeout, callback=lambda x: log.info("Terminated PID %s", x.pid) ) except psutil.TimeoutExpired: log.debug("Ran out of time while waiting for processes to exit") # Then SIGKILL child_processes = [ x for x in this_process.children(recursive=True) if x.is_running() and x.pid in pids_to_kill ] if child_processes: log.info("SIGKILL processes that did not terminate gracefully") for child in child_processes: log.info("Killing child PID: %s", child.pid) child.kill() child.wait()
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.float64. order : {'C', 'F'}, optional Whether to store matrix in C- or Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Matrix of ones of given shape, dtype, and order. See Also -------- ones : Array of ones. matlib.zeros : Zero matrix. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> np.matlib.ones((2,3)) matrix([[1., 1., 1.], [1., 1., 1.]]) >>> np.matlib.ones(2) matrix([[1., 1.]]) """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(1) return a
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 Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Matrix of ones of given shape, dtype, and order. See Also -------- ones : Array of ones. matlib.zeros : Zero matrix. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> np.matlib.ones((2,3)) matrix([[1., 1., 1.], [1., 1., 1.]]) >>> np.matlib.ones(2) matrix([[1., 1.]])
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, false otherwise
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); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { const initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer); return setTextRange(factory.createPropertyAssignment(name, initializer), node); } return setTextRange(factory.createPropertyAssignment(name, exportedName), node); } } return node; }
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 @throws Throwable if the interceptors or the target object throws an exception
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 module because module syntax was detected. This incurs a performance overhead.\n' + `To eliminate this warning, add "type": "module" to ${pjsonPath}.`; process.emitWarning(warning, { code: 'MODULE_TYPELESS_PACKAGE_JSON', }); typelessPackageJsonFilesWarnedAbout.add(pjsonPath); } }
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 set_trace(frame)
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 : str, default 'utf8' hash_key : str, default _default_hash_key Returns ------- ndarray[np.uint64] of hashed values """ if not is_list_like(vals): raise TypeError("must be convertible to a list-of-tuples") from pandas import ( Categorical, MultiIndex, ) if not isinstance(vals, ABCMultiIndex): mi = MultiIndex.from_tuples(vals) else: mi = vals # create a list-of-Categoricals cat_vals = [ Categorical._simple_new( mi.codes[level], CategoricalDtype(categories=mi.levels[level], ordered=False), ) for level in range(mi.nlevels) ] # hash the list-of-ndarrays hashes = ( cat._hash_pandas_object(encoding=encoding, hash_key=hash_key, categorize=False) for cat in cat_vals ) h = combine_hash_arrays(hashes, len(cat_vals)) return h
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); if (oneOrOtherIsAfterAdvice) { // the advice declared last has higher precedence if (adviceDeclarationOrderDelta < 0) { // advice1 was declared before advice2 // so advice1 has lower precedence return LOWER_PRECEDENCE; } else if (adviceDeclarationOrderDelta == 0) { return SAME_PRECEDENCE; } else { return HIGHER_PRECEDENCE; } } else { // the advice declared first has higher precedence if (adviceDeclarationOrderDelta < 0) { // advice1 was declared before advice2 // so advice1 has higher precedence return HIGHER_PRECEDENCE; } else if (adviceDeclarationOrderDelta == 0) { return SAME_PRECEDENCE; } else { return LOWER_PRECEDENCE; } } }
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 @throws BeanDefinitionStoreException in case of loading or parsing errors
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); } this.values.set(index, value); return this; }
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 JSONObject#NULL}, or {@code null}. May not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}. @return this array. @throws JSONException if processing of json failed
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 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: True Whether to check agreement between actual and desired dtypes and shapes check_scalar : bool, default: False NumPy only: whether to check agreement between actual and desired types - 0d array vs scalar. See Also -------- xp_assert_close : Similar function for inexact equality checks. numpy.testing.assert_array_equal : Similar function for NumPy arrays. """ xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar) if not _is_materializable(actual): return actual_np = as_numpy_array(actual, xp=xp) desired_np = as_numpy_array(desired, xp=xp) np.testing.assert_array_equal(actual_np, desired_np, err_msg=err_msg)
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: True Whether to check agreement between actual and desired dtypes and shapes check_scalar : bool, default: False NumPy only: whether to check agreement between actual and desired types - 0d array vs scalar. See Also -------- xp_assert_close : Similar function for inexact equality checks. numpy.testing.assert_array_equal : Similar function for NumPy arrays.
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 token; ArrayList<Double> centroids; token = parser.nextToken(); // should be an array ensureExpectedToken(XContentParser.Token.START_ARRAY, token, parser, parsingExceptionProvider); centroids = new ArrayList<>(); token = parser.nextToken(); double previousVal = -Double.MAX_VALUE; while (token != XContentParser.Token.END_ARRAY) { // should be a number ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser, parsingExceptionProvider); double val = parser.doubleValue(); if (val < previousVal) { // centroids must be in increasing order throw documentParsingExceptionProvider.apply( parser.getTokenLocation(), "error parsing field [" + mappedFieldName + "], [" + CENTROIDS_FIELD + "] centroids must be in increasing order, got [" + val + "] but previous value was [" + previousVal + "]" ); } centroids.add(val); previousVal = val; token = parser.nextToken(); } return centroids; }
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 generating document parsing exceptions. Required for visibility. @return the parsed histogram
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... return beanFactory.getBean(beanName); } }
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 name, as a candidate result for this dependency @param requiredType the expected type of the bean (as an assertion) @param beanFactory the associated factory @return the bean instance (never {@code null}) @throws BeansException if the bean could not be obtained @since 4.3.2 @see BeanFactory#getBean(String)
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 is None: # using all queues return self.select(k for k in self if k not in exclude) # using selection for queue in exclude: self._consume_from.pop(queue, None)
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.Series({"a": 1, "b": 2, "c": 3}) >>> s.ndim 1 >>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}) >>> df.ndim 2 """ return self._mgr.ndim
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]}) >>> df.ndim 2
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.filterKeys(servicesByState, not(equalTo(RUNNING)))); for (Service service : servicesByState.get(State.FAILED)) { exception.addSuppressed(new FailedService(service)); } throw exception; } }
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]; edge1 = maxDimByCIIVec2d[adjRes][1]; } case JK -> { edge0 = maxDimByCIIVec2d[adjRes][1]; edge1 = maxDimByCIIVec2d[adjRes][2]; } // case KI: default -> { assert (faceDir == KI); edge0 = maxDimByCIIVec2d[adjRes][2]; edge1 = maxDimByCIIVec2d[adjRes][0]; } } // find the intersection and add the lat/lng point to the result final Vec2d inter = Vec2d.v2dIntersect(orig2d0, orig2d1, edge0, edge1); /* If a point of intersection occurs at a hexagon vertex, then each adjacent hexagon edge will lie completely on a single icosahedron face, and no additional vertex is required. */ return orig2d0.numericallyIdentical(inter) || orig2d1.numericallyIdentical(inter) ? null : inter; }
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 buffer. Returns ------- bufsize : int Previous size of ufunc buffer in bytes. Notes ----- **Concurrency note:** see :doc:`/reference/routines.err` Examples -------- When exiting a `numpy.errstate` context manager the bufsize is restored: >>> import numpy as np >>> with np.errstate(): ... np.setbufsize(4096) ... print(np.getbufsize()) ... 8192 4096 >>> np.getbufsize() 8192 """ if size < 0: raise ValueError("buffer size must be non-negative") old = _get_extobj_dict()["bufsize"] extobj = _make_extobj(bufsize=size) _extobj_contextvar.set(extobj) return old
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 ufunc buffer in bytes. Notes ----- **Concurrency note:** see :doc:`/reference/routines.err` Examples -------- When exiting a `numpy.errstate` context manager the bufsize is restored: >>> import numpy as np >>> with np.errstate(): ... np.setbufsize(4096) ... print(np.getbufsize()) ... 8192 4096 >>> np.getbufsize() 8192
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) { rootNode = parsePartialStylesheet(editor.document, editor.selection.isReversed ? editor.selection.anchor : editor.selection.active); } else { rootNode = parseDocument(editor.document, true); } return rootNode; }
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 the processing job info """ return self.get_conn().describe_processing_job(ProcessingJobName=name)
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.include(), contextProperties.prefix()); }
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 common formatters
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)) .withAvg(metricsRegistry.topicFetchSizeAvg) .withMax(metricsRegistry.topicFetchSizeMax) .withMeter(metricsRegistry.topicBytesConsumedRate, metricsRegistry.topicBytesConsumedTotal) .build(); deprecatedBytesFetched.record(bytes); } }
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.symbol); if (isClassLike(referenceLocation.parent)) { Debug.assert(referenceLocation.kind === SyntaxKind.DefaultKeyword || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { // If this class appears in `extends C`, then the extending class' "super" calls are references. const classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); findInheritedConstructorReferences(classExtending, state); } } }
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_features), default=None Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool, default=False Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Only supported when Y is None. Returns ------- K : ndarray of shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True. """ if len(np.atleast_1d(self.length_scale)) > 1: raise AttributeError( "RationalQuadratic kernel only supports isotropic version, " "please use a single scalar for length_scale" ) X = np.atleast_2d(X) if Y is None: dists = squareform(pdist(X, metric="sqeuclidean")) tmp = dists / (2 * self.alpha * self.length_scale**2) base = 1 + tmp K = base**-self.alpha np.fill_diagonal(K, 1) else: if eval_gradient: raise ValueError("Gradient can only be evaluated when Y is None.") dists = cdist(X, Y, metric="sqeuclidean") K = (1 + dists / (2 * self.alpha * self.length_scale**2)) ** -self.alpha if eval_gradient: # gradient with respect to length_scale if not self.hyperparameter_length_scale.fixed: length_scale_gradient = dists * K / (self.length_scale**2 * base) length_scale_gradient = length_scale_gradient[:, :, np.newaxis] else: # l is kept fixed length_scale_gradient = np.empty((K.shape[0], K.shape[1], 0)) # gradient with respect to alpha if not self.hyperparameter_alpha.fixed: alpha_gradient = K * ( -self.alpha * np.log(base) + dists / (2 * self.length_scale**2 * base) ) alpha_gradient = alpha_gradient[:, :, np.newaxis] else: # alpha is kept fixed alpha_gradient = np.empty((K.shape[0], K.shape[1], 0)) return K, np.dstack((alpha_gradient, length_scale_gradient)) else: return K
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 instead. eval_gradient : bool, default=False Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Only supported when Y is None. Returns ------- K : ndarray of shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
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 fraction (where k>0) if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) { numerator /= 2; denominator /= 2; } if (denominator < 0) { if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) { throw new ArithmeticException("overflow: can't negate"); } numerator = -numerator; denominator = -denominator; } // simplify fraction. final int gcd = greatestCommonDivisor(numerator, denominator); numerator /= gcd; denominator /= gcd; return new Fraction(numerator, denominator); }
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' @param denominator the denominator, for example the seven in 'three sevenths' @return a new fraction instance, with the numerator and denominator reduced @throws ArithmeticException if the denominator is {@code zero}
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 ---------- 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 a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. Returns ------- str or None Format of file if it can be determined. Raises ------ ValueError If resulting stream is empty. BadZipFile If resulting stream does not have an XLS signature and is not a valid zipfile. """ with get_handle( content_or_path, "rb", storage_options=storage_options, is_text=False ) as handle: stream = handle.handle stream.seek(0) buf = stream.read(PEEK_SIZE) if buf is None: raise ValueError("stream is empty") assert isinstance(buf, bytes) peek = buf stream.seek(0) if any(peek.startswith(sig) for sig in XLS_SIGNATURES): return "xls" elif not peek.startswith(ZIP_SIGNATURE): return None with zipfile.ZipFile(stream) as zf: # Workaround for some third party files that use forward slashes and # lower case names. component_names = { name.replace("\\", "/").lower() for name in zf.namelist() } if "xl/workbook.xml" in component_names: return "xlsx" if "xl/workbook.bin" in component_names: return "xlsb" if "content.xml" in component_names: return "ods" return "zip"
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 a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. Returns ------- str or None Format of file if it can be determined. Raises ------ ValueError If resulting stream is empty. BadZipFile If resulting stream does not have an XLS signature and is not a valid zipfile.
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 provided via kwargs. Note that boto3 expects these in CamelCase, for example: .. code-block:: python list_training_jobs(name_contains="myjob", StatusEquals="Failed") .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.list_training_jobs` :param name_contains: (optional) partial name to match :param max_results: (optional) maximum number of results to return. None returns infinite results :param kwargs: (optional) kwargs to boto3's list_training_jobs method :return: results of the list_training_jobs request """ config, max_results = self._preprocess_list_request_args(name_contains, max_results, **kwargs) list_training_jobs_request = partial(self.get_conn().list_training_jobs, **config) results = self._list_request( list_training_jobs_request, "TrainingJobSummaries", max_results=max_results ) return results
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") .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.list_training_jobs` :param name_contains: (optional) partial name to match :param max_results: (optional) maximum number of results to return. None returns infinite results :param kwargs: (optional) kwargs to boto3's list_training_jobs method :return: results of the list_training_jobs request
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 # Add all nodes from new_set to existing_set existing_set.update(new_set) # Update all nodes from new_set to point to existing_set for node in new_set: self.merge_sets[node] = existing_set
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 = acquiredRecordIterator.next(); } } }
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 {@link Deserializer}s to use to convert the raw bytes to the expected key and value types @param maxRecords The number of records to return; the number returned may be {@code 0 <= maxRecords} @param checkCrcs Whether to check the CRC of fetched records @return {@link ShareInFlightBatch The ShareInFlightBatch containing records and their acknowledgements}
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 NullPointerException if the field is {@code null}. @throws SecurityException if an underlying accessible object's method denies the request. @see SecurityManager#checkPermission @deprecated As of Java 12, we can no longer drop the {@code final} modifier, thus rendering this method obsolete. The JDK discussion about this change can be found here: https://mail.openjdk.java.net/pipermail/core-libs-dev/2018-November/056486.html @since 3.3
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 array. See Also -------- ExtensionArray.tolist: Return a list of the values. Notes ----- - Because ExtensionArrays are 1D-only, this is a no-op. - The "order" argument is ignored, is for compatibility with NumPy. Examples -------- >>> pd.array([1, 2, 3]).ravel() <IntegerArray> [1, 2, 3] Length: 3, dtype: Int64 """ return self
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. - The "order" argument is ignored, is for compatibility with NumPy. Examples -------- >>> pd.array([1, 2, 3]).ravel() <IntegerArray> [1, 2, 3] Length: 3, dtype: Int64
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] = [] ldflags: list[str] = [] if _IS_WINDOWS: cflags = ["ZI", "_DEBUG"] ldflags = ["DEBUG", "ASSEMBLYDEBUG ", "OPT:REF", "OPT:ICF"] else: cflags.append("g") return cflags, ldflags
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 consumers differ by at most one return true return true; // create a mapping from partitions to the consumer assigned to them final Map<TopicPartition, String> allPartitions = new HashMap<>(); Set<Entry<String, List<TopicPartition>>> assignments = currentAssignment.entrySet(); for (Map.Entry<String, List<TopicPartition>> entry: assignments) { List<TopicPartition> topicPartitions = entry.getValue(); for (TopicPartition topicPartition: topicPartitions) { if (allPartitions.containsKey(topicPartition)) log.error("{} is assigned to more than one consumer.", topicPartition); allPartitions.put(topicPartition, entry.getKey()); } } // for each consumer that does not have all the topic partitions it can get make sure none of the topic partitions it // could but did not get cannot be moved to it (because that would break the balance) for (String consumer: sortedCurrentSubscriptions) { List<TopicPartition> consumerPartitions = currentAssignment.get(consumer); int consumerPartitionCount = consumerPartitions.size(); // skip if this consumer already has all the topic partitions it can get List<String> allSubscribedTopics = consumer2AllPotentialTopics.get(consumer); int maxAssignmentSize = getMaxAssignmentSize(allSubscribedTopics); if (consumerPartitionCount == maxAssignmentSize) continue; // otherwise make sure it cannot get any more for (String topic: allSubscribedTopics) { int partitionCount = partitionsPerTopic.get(topic).size(); for (int i = 0; i < partitionCount; i++) { TopicPartition topicPartition = new TopicPartition(topic, i); if (!currentAssignment.get(consumer).contains(topicPartition)) { String otherConsumer = allPartitions.get(topicPartition); int otherConsumerPartitionCount = currentAssignment.get(otherConsumer).size(); if (consumerPartitionCount + 1 < otherConsumerPartitionCount) { log.debug("{} can be moved from consumer {} to consumer {} for a more balanced assignment.", topicPartition, otherConsumer, consumer); return false; } } } } } return true; }
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 only valid bit entries. // final int maxIndex = indices.length(); // if (maxIndex > srcLength) { // throw new IndexOutOfBoundsException("Index: " + (maxIndex-1) + ", Length: " + srcLength); // } final int removals = indices.cardinality(); // true bits are items to remove final Object result = Array.newInstance(array.getClass().getComponentType(), srcLength - removals); int srcIndex = 0; int destIndex = 0; int count; int set; while ((set = indices.nextSetBit(srcIndex)) != -1) { count = set - srcIndex; if (count > 0) { System.arraycopy(array, srcIndex, result, destIndex, count); destIndex += count; } srcIndex = indices.nextClearBit(set); } count = srcLength - srcIndex; if (count > 0) { System.arraycopy(array, srcIndex, result, destIndex, count); } return result; }
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 (error != null) { log.error("onPartitionsLost callback invocation failed while releasing assignment " + "after member left group due to expired poll timer.", error); } clearAssignment(); log.debug("Member {} sent leave group heartbeat and released its assignment. It will remain " + "in {} state until the poll timer is reset, and it will then rejoin the group", memberId, MemberState.STALE); }); }
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 = now(); } return value; }
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.apache.kafka.common.errors.WakeupException if {@link #wakeup()} is called before or while this function is called @throws org.apache.kafka.common.errors.InterruptException if the calling thread is interrupted before or while this function is called @throws org.apache.kafka.common.errors.AuthenticationException if authentication fails. See the exception for more details @throws org.apache.kafka.common.errors.AuthorizationException if not authorized to the specified topic. See the exception for more details @throws org.apache.kafka.common.KafkaException for any other unrecoverable errors @throws org.apache.kafka.common.errors.TimeoutException if the offset metadata could not be fetched before the amount of time allocated by {@code default.api.timeout.ms} expires.
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 SchedulerBuffers and FreeableInputBuffers. Returns: int: peak memory List[int]: memory usage at each node (or each step). """ buf_info_list, _, _ = compute_memory_timeline( nodes, name_to_freeable_input_buf, graph_outputs ) # incremental memory changes at each step memory = [0 for _ in range(len(nodes) + 1)] # for each buffer, update memory when created and when freed for buf_info in buf_info_list: memory[buf_info.start_step] += buf_info.size_alloc memory[buf_info.end_step + 1] -= buf_info.size_free # get peak memory by compute the cumulative memories max_memory = 0 cur_memory = 0 memories_at_nodes = [] for t in range(len(nodes) + 1): cur_memory += memory[t] memories_at_nodes.append(cur_memory) max_memory = max(max_memory, cur_memory) return (max_memory, memories_at_nodes)
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)) .withAvg(metricsRegistry.topicRecordsPerRequestAvg) .withMeter(metricsRegistry.topicRecordsConsumedRate, metricsRegistry.topicRecordsConsumedTotal) .build(); deprecatedRecordsFetched.record(records); } }
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 .map((s, i) => { if (i < arr.length - 1) { return `${s}\n`; } return s; }) .filter(s => s.length > 0); // Skip last one if empty (it's the only one that could be length 0) } return []; }
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 is [1, 2, 3, 4, 5, 6, 7, 8] and the bit vector is [0b10000000], the inner product will be 1.0. @param q the query vector @param d the document vector @return the inner product of the two vectors
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 = new Color("red", 255, 0, 0); ... Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator(); Map<String, Color> colorForName = uniqueIndex(allColors, toStringFunction()); assertThat(colorForName).containsEntry("red", red); } <p>If your index may associate multiple values with each key, use {@link Multimaps#index(Iterator, Function) Multimaps.index}. @param values the values to use when constructing the {@code Map} @param keyFunction the function used to produce the key for each value @return a map mapping the result of evaluating the function {@code keyFunction} on each value in the input collection to that value @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one value in the input collection @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code keyFunction} produces {@code null} for any value @since 10.0
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 process all children const children = activatedRoute.children || []; for (const child of children) { collectActiveRouteConfigs(child, activeRoutes); } return activeRoutes; }
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 @param {Object} object The object to iterate over. @param {Function} [iteratee=_.identity] The function invoked per iteration. @returns {Object} Returns `object`. @see _.forInRight @example function Foo() { this.a = 1; this.b = 2; } Foo.prototype.c = 3; _.forIn(new Foo, function(value, key) { console.log(key); }); // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
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, separator)); if ("runtime".equals(url.getRef())) { jarFileUrl = new URL(jarFileUrl, "#runtime"); } String entryName = UrlDecoder.decode(spec.substring(separator + 2)); JarFile jarFile = jarFiles.getOrCreate(true, jarFileUrl); jarFiles.cacheIfAbsent(true, jarFileUrl, jarFile); if (!hasEntry(jarFile, entryName)) { return notFoundConnection(jarFile.getName(), entryName); } } } return new JarUrlConnection(url); }
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 end index, exclusive, must be valid except that if too large it is treated as end of string @return the new string @throws IndexOutOfBoundsException if the index is invalid
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. Parameters ---------- a, b : array_like Input arrays to compare. masked_equal : bool, optional Whether masked values in `a` and `b` are considered equal (True) or not (False). They are considered equal by default. rtol : float, optional Relative tolerance. The relative difference is equal to ``rtol * b``. Default is 1e-5. atol : float, optional Absolute tolerance. The absolute difference is equal to `atol`. Default is 1e-8. Returns ------- y : bool Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. See Also -------- all, any numpy.allclose : the non-masked `allclose`. Notes ----- If the following equation is element-wise True, then `allclose` returns True:: absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Return True if all elements of `a` and `b` are equal subject to given tolerances. Examples -------- >>> import numpy as np >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) >>> a masked_array(data=[10000000000.0, 1e-07, --], mask=[False, False, True], fill_value=1e+20) >>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) False >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) True >>> np.ma.allclose(a, b, masked_equal=False) False Masked values are not compared directly. >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) True >>> np.ma.allclose(a, b, masked_equal=False) False """ x = masked_array(a, copy=False) y = masked_array(b, copy=False) # make sure y is an inexact type to avoid abs(MIN_INT); will cause # casting of x later. # NOTE: We explicitly allow timedelta, which used to work. This could # possibly be deprecated. See also gh-18286. # timedelta works if `atol` is an integer or also a timedelta. # Although, the default tolerances are unlikely to be useful if y.dtype.kind != "m": dtype = np.result_type(y, 1.) if y.dtype != dtype: y = masked_array(y, dtype=dtype, copy=False) m = mask_or(getmask(x), getmask(y)) xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False) # If we have some infs, they should fall at the same place. if not np.all(xinf == filled(np.isinf(y), False)): return False # No infs at all if not np.any(xinf): d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), masked_equal) return np.all(d) if not np.all(filled(x[xinf] == y[xinf], masked_equal)): return False x = x[~xinf] y = y[~xinf] d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), masked_equal) return np.all(d)
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, optional Whether masked values in `a` and `b` are considered equal (True) or not (False). They are considered equal by default. rtol : float, optional Relative tolerance. The relative difference is equal to ``rtol * b``. Default is 1e-5. atol : float, optional Absolute tolerance. The absolute difference is equal to `atol`. Default is 1e-8. Returns ------- y : bool Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. See Also -------- all, any numpy.allclose : the non-masked `allclose`. Notes ----- If the following equation is element-wise True, then `allclose` returns True:: absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Return True if all elements of `a` and `b` are equal subject to given tolerances. Examples -------- >>> import numpy as np >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) >>> a masked_array(data=[10000000000.0, 1e-07, --], mask=[False, False, True], fill_value=1e+20) >>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) False >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) True >>> np.ma.allclose(a, b, masked_equal=False) False Masked values are not compared directly. >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1]) >>> np.ma.allclose(a, b) True >>> np.ma.allclose(a, b, masked_equal=False) False
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.arraycopy(array, 0, newArray, 0, arrayLength); return newArray; } return Array.newInstance(newArrayComponentType, 1); }
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 size 1 greater than the input.
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 IllegalArgumentException("Unable to add listener for class " + eventSource.getClass().getName() + " and public add" + listenerType.getSimpleName() + " method which takes a parameter of type " + listenerType.getName() + "."); } }
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 IllegalArgumentException if the object doesn't support the listener type.
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" &rarr; "myJdbcDao". <p>Note that inner classes will thus have names of the form "outerClassName.InnerClassName", which because of the period in the name may be an issue if you are autowiring by name. @param definition the bean definition to build a bean name for @return the default bean name (never {@code null})
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 serialize :return: string representation of `value` if it is an instance of datetime or `None` otherwise """ if isinstance(value, (date, datetime)): return value.isoformat() return 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 serialize :return: string representation of `value` if it is an instance of datetime or `None` otherwise
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) if self.bucket_name is None: if parsed_url.netloc == "": message = "If key is a relative path from root, please provide a bucket_name" raise AirflowException(message) self.bucket_name = parsed_url.netloc self.bucket_key = parsed_url.path.lstrip("/") else: if parsed_url.scheme != "" or parsed_url.netloc != "": message = ( "If bucket_name is provided, bucket_key" " should be relative path from root" " level, rather than a full oss:// url" ) raise AirflowException(message) self.log.info("Poking for key : oss://%s/%s", self.bucket_name, self.bucket_key) return self.hook.object_exists(key=self.bucket_key, bucket_name=self.bucket_name)
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 advertised or not @param clientTelemetryEnabled whether client telemetry is enabled or not @return commonly agreed ApiVersion collection
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 * PREPARING_REBALANCE: not yet received join-group response before timeout, heartbeat disabled * COMPLETING_REBALANCE: not yet received sync-group response before timeout, heartbeat enabled Visible for testing. @param timer Timer bounding how long this method can block @throws KafkaException if the callback throws exception @return true iff the operation succeeded
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 `values` will **not** transform a `ndarray` into a `MaskedArray`. Examples -------- >>> import numpy as np >>> arr = [[1, 2], [3, 4]] >>> mask = [[1, 0], [0, 0]] >>> x = np.ma.array(arr, mask=mask) >>> np.ma.putmask(x, x < 4, 10*x) >>> x masked_array( data=[[--, 20], [30, 4]], mask=[[ True, False], [False, False]], fill_value=999999) >>> x.data array([[10, 20], [30, 4]]) """ # We can't use 'frommethod', the order of arguments is different if not isinstance(a, MaskedArray): a = a.view(MaskedArray) (valdata, valmask) = (getdata(values), getmask(values)) if getmask(a) is nomask: if valmask is not nomask: a._sharedmask = True a._mask = make_mask_none(a.shape, a.dtype) np.copyto(a._mask, valmask, where=mask) elif a._hardmask: if valmask is not nomask: m = a._mask.copy() np.copyto(m, valmask, where=mask) a.mask |= m else: if valmask is nomask: valmask = getmaskarray(values) np.copyto(a._mask, valmask, where=mask) np.copyto(a._data, valdata, where=mask)
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 numpy as np >>> arr = [[1, 2], [3, 4]] >>> mask = [[1, 0], [0, 0]] >>> x = np.ma.array(arr, mask=mask) >>> np.ma.putmask(x, x < 4, 10*x) >>> x masked_array( data=[[--, 20], [30, 4]], mask=[[ True, False], [False, False]], fill_value=999999) >>> x.data array([[10, 20], [30, 4]])
python
numpy/ma/core.py
7,535
[ "a", "mask", "values" ]
false
8
6.64
numpy/numpy
31,054
unknown
false