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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
_categorize_entities
|
def _categorize_entities(
self,
entities: Sequence[str | BulkTaskInstanceBody],
results: BulkActionResponse,
) -> tuple[set[tuple[str, str, str, int]], set[tuple[str, str, str]]]:
"""
Validate entities and categorize them into specific and all map index update sets.
:param entities: Sequence of entities to validate
:param results: BulkActionResponse object to track errors
:return: tuple of (specific_map_index_task_keys, all_map_index_task_keys)
"""
specific_map_index_task_keys = set()
all_map_index_task_keys = set()
for entity in entities:
dag_id, dag_run_id, task_id, map_index = self._extract_task_identifiers(entity)
# Validate that we have specific values, not wildcards
if dag_id == "~" or dag_run_id == "~":
if isinstance(entity, str):
error_msg = f"When using wildcard in path, dag_id and dag_run_id must be specified in BulkTaskInstanceBody object, not as string for task_id: {entity}"
else:
error_msg = f"When using wildcard in path, dag_id and dag_run_id must be specified in request body for task_id: {entity.task_id}"
results.errors.append(
{
"error": error_msg,
"status_code": status.HTTP_400_BAD_REQUEST,
}
)
continue
# Separate logic for "update all" vs "update specific"
if map_index is not None:
specific_map_index_task_keys.add((dag_id, dag_run_id, task_id, map_index))
else:
all_map_index_task_keys.add((dag_id, dag_run_id, task_id))
return specific_map_index_task_keys, all_map_index_task_keys
|
Validate entities and categorize them into specific and all map index update sets.
:param entities: Sequence of entities to validate
:param results: BulkActionResponse object to track errors
:return: tuple of (specific_map_index_task_keys, all_map_index_task_keys)
|
python
|
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py
| 194
|
[
"self",
"entities",
"results"
] |
tuple[set[tuple[str, str, str, int]], set[tuple[str, str, str]]]
| true
| 8
| 7.44
|
apache/airflow
| 43,597
|
sphinx
| false
|
_fetch_from_db
|
def _fetch_from_db(model_reference: Mapped, session=None, **conditions) -> datetime | None:
"""
Fetch a datetime value from the database using the provided model reference and filtering conditions.
For example, to fetch a TaskInstance's start_date:
_fetch_from_db(
TaskInstance.start_date, dag_id='example_dag', task_id='example_task', run_id='example_run'
)
This generates SQL equivalent to:
SELECT start_date
FROM task_instance
WHERE dag_id = 'example_dag'
AND task_id = 'example_task'
AND run_id = 'example_run'
:param model_reference: SQLAlchemy Column to select (e.g., DagRun.logical_date, TaskInstance.start_date)
:param conditions: Filtering conditions applied as equality comparisons in the WHERE clause.
Multiple conditions are combined with AND.
:param session: SQLAlchemy session (auto-provided by decorator)
"""
query = select(model_reference)
for key, value in conditions.items():
inspected = inspect(model_reference)
if inspected is not None:
query = query.where(getattr(inspected.class_, key) == value)
compiled_query = query.compile(compile_kwargs={"literal_binds": True})
pretty_query = "\n ".join(str(compiled_query).splitlines())
logger.debug(
"Executing query:\n %r\nAs SQL:\n %s",
query,
pretty_query,
)
try:
result = session.scalar(query)
except SQLAlchemyError:
logger.exception("Database query failed.")
raise
if result is None:
message = f"No matching record found in the database for query:\n {pretty_query}"
logger.error(message)
raise ValueError(message)
return result
|
Fetch a datetime value from the database using the provided model reference and filtering conditions.
For example, to fetch a TaskInstance's start_date:
_fetch_from_db(
TaskInstance.start_date, dag_id='example_dag', task_id='example_task', run_id='example_run'
)
This generates SQL equivalent to:
SELECT start_date
FROM task_instance
WHERE dag_id = 'example_dag'
AND task_id = 'example_task'
AND run_id = 'example_run'
:param model_reference: SQLAlchemy Column to select (e.g., DagRun.logical_date, TaskInstance.start_date)
:param conditions: Filtering conditions applied as equality comparisons in the WHERE clause.
Multiple conditions are combined with AND.
:param session: SQLAlchemy session (auto-provided by decorator)
|
python
|
airflow-core/src/airflow/models/deadline.py
| 435
|
[
"model_reference",
"session"
] |
datetime | None
| true
| 4
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
getAndClearFatalError
|
public Optional<Throwable> getAndClearFatalError() {
Optional<Throwable> fatalError = this.fatalError;
this.fatalError = Optional.empty();
return fatalError;
}
|
Returns the current coordinator node.
@return the current coordinator node.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java
| 256
|
[] | true
| 1
| 6.4
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
bindLabeledStatement
|
function bindLabeledStatement(node: LabeledStatement): void {
const postStatementLabel = createBranchLabel();
activeLabelList = {
next: activeLabelList,
name: node.label.escapedText,
breakTarget: postStatementLabel,
continueTarget: undefined,
referenced: false,
};
bind(node.label);
bind(node.statement);
if (!activeLabelList.referenced) {
(node.label as Mutable<Node>).flags |= NodeFlags.Unreachable;
}
activeLabelList = activeLabelList.next;
addAntecedent(postStatementLabel, currentFlow);
currentFlow = finishFlowLabel(postStatementLabel);
}
|
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
@param symbolTable - The symbol table which node will be added to.
@param parent - node's parent declaration.
@param node - The declaration to be added to the symbol table
@param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
@param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
|
typescript
|
src/compiler/binder.ts
| 1,789
|
[
"node"
] | true
| 2
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
isActive
|
boolean isActive(@Nullable ConfigDataActivationContext activationContext) {
if (activationContext == null) {
return false;
}
CloudPlatform cloudPlatform = activationContext.getCloudPlatform();
boolean activate = isActive((cloudPlatform != null) ? cloudPlatform : CloudPlatform.NONE);
activate = activate && isActive(activationContext.getProfiles());
return activate;
}
|
Return {@code true} if the properties indicate that the config data property
source is active for the given activation context.
@param activationContext the activation context
@return {@code true} if the config data property source is active
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java
| 122
|
[
"activationContext"
] | true
| 4
| 7.6
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
_from_sequence_of_strings
|
def _from_sequence_of_strings(
cls, strings, *, dtype: ExtensionDtype, copy: bool = False
) -> Self:
"""
Construct a new ExtensionArray from a sequence of strings.
Parameters
----------
strings : Sequence
Each element will be an instance of the scalar type for this
array, ``cls.dtype.type``.
dtype : ExtensionDtype
Construct for this particular dtype. This should be a Dtype
compatible with the ExtensionArray.
copy : bool, default False
If True, copy the underlying data.
Returns
-------
ExtensionArray
See Also
--------
api.extensions.ExtensionArray._from_sequence : Construct a new ExtensionArray
from a sequence of scalars.
api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray
after factorization.
Examples
--------
>>> pd.arrays.IntegerArray._from_sequence_of_strings(
... ["1", "2", "3"], dtype=pd.Int64Dtype()
... )
<IntegerArray>
[1, 2, 3]
Length: 3, dtype: Int64
"""
raise AbstractMethodError(cls)
|
Construct a new ExtensionArray from a sequence of strings.
Parameters
----------
strings : Sequence
Each element will be an instance of the scalar type for this
array, ``cls.dtype.type``.
dtype : ExtensionDtype
Construct for this particular dtype. This should be a Dtype
compatible with the ExtensionArray.
copy : bool, default False
If True, copy the underlying data.
Returns
-------
ExtensionArray
See Also
--------
api.extensions.ExtensionArray._from_sequence : Construct a new ExtensionArray
from a sequence of scalars.
api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray
after factorization.
Examples
--------
>>> pd.arrays.IntegerArray._from_sequence_of_strings(
... ["1", "2", "3"], dtype=pd.Int64Dtype()
... )
<IntegerArray>
[1, 2, 3]
Length: 3, dtype: Int64
|
python
|
pandas/core/arrays/base.py
| 320
|
[
"cls",
"strings",
"dtype",
"copy"
] |
Self
| true
| 1
| 6.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
readBytes
|
@Deprecated
@InlineMe(
replacement = "Files.asByteSource(file).read(processor)",
imports = "com.google.common.io.Files")
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public
static <T extends @Nullable Object> T readBytes(File file, ByteProcessor<T> processor)
throws IOException {
return asByteSource(file).read(processor);
}
|
Process the bytes of a file.
<p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
@param file the file to read
@param processor the object to which the bytes of the file are passed.
@return the result of the byte processor
@throws IOException if an I/O error occurs
@deprecated Prefer {@code asByteSource(file).read(processor)}.
|
java
|
android/guava/src/com/google/common/io/Files.java
| 599
|
[
"file",
"processor"
] |
T
| true
| 1
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
getDefaultType
|
@Nullable ProjectType getDefaultType() {
if (this.projectTypes.getDefaultItem() != null) {
return this.projectTypes.getDefaultItem();
}
String defaultTypeId = getDefaults().get("type");
if (defaultTypeId != null) {
return this.projectTypes.getContent().get(defaultTypeId);
}
return null;
}
|
Return the default type to use or {@code null} if the metadata does not define any
default.
@return the default project type or {@code null}
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java
| 111
|
[] |
ProjectType
| true
| 3
| 8.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
ensureCapacity
|
private void ensureCapacity(int needed) {
if (buffer.remaining() >= needed) {
return;
}
int currentCapacity = buffer.capacity();
int requiredCapacity = buffer.position() + needed;
int newCapacity = Math.max(currentCapacity * 2, requiredCapacity);
ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity).order(ByteOrder.LITTLE_ENDIAN);
// We must switch the old buffer to read mode to extract data
Java8Compatibility.flip(buffer);
newBuffer.put(buffer);
// Swap references, newBuffer is already in write mode at the correct position
this.buffer = newBuffer;
}
|
Resizes the buffer if necessary. Guaranteed to leave `buffer` in Write Mode ready for new
data.
|
java
|
android/guava/src/com/google/common/hash/AbstractNonStreamingHashFunction.java
| 88
|
[
"needed"
] |
void
| true
| 2
| 6
|
google/guava
| 51,352
|
javadoc
| false
|
torch_version_hash
|
def torch_version_hash() -> str:
"""Get base64-encoded PyTorch version hash.
Returns:
A base64-encoded string representing the PyTorch version hash.
"""
from torch._inductor.codecache import torch_key
return b64encode(torch_key()).decode()
|
Get base64-encoded PyTorch version hash.
Returns:
A base64-encoded string representing the PyTorch version hash.
|
python
|
torch/_inductor/runtime/caching/context.py
| 144
|
[] |
str
| true
| 1
| 6.24
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
property
|
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
|
Creates a function that returns the value at `path` of a given object.
@static
@memberOf _
@since 2.4.0
@category Util
@param {Array|string} path The path of the property to get.
@returns {Function} Returns the new accessor function.
@example
var objects = [
{ 'a': { 'b': 2 } },
{ 'a': { 'b': 1 } }
];
_.map(objects, _.property('a.b'));
// => [2, 1]
_.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
// => [1, 2]
|
javascript
|
lodash.js
| 16,021
|
[
"path"
] | false
| 2
| 7.6
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
take
|
def take(
self: MultiIndex,
indices,
axis: Axis = 0,
allow_fill: bool = True,
fill_value=None,
**kwargs,
) -> MultiIndex:
"""
Return a new MultiIndex of the values selected by the indices.
For internal compatibility with numpy arrays.
Parameters
----------
indices : array-like
Indices to be taken.
axis : {0 or 'index'}, optional
The axis over which to select values, always 0 or 'index'.
allow_fill : bool, default True
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : scalar, default None
If allow_fill=True and fill_value is not None, indices specified by
-1 are regarded as NA. If Index doesn't hold NA, raise ValueError.
**kwargs
Required for compatibility with numpy.
Returns
-------
Index
An index formed of elements at the given indices. Will be the same
type as self, except for RangeIndex.
See Also
--------
numpy.ndarray.take: Return an array formed from the
elements of a at the given indices.
Examples
--------
>>> idx = pd.MultiIndex.from_arrays([["a", "b", "c"], [1, 2, 3]])
>>> idx
MultiIndex([('a', 1),
('b', 2),
('c', 3)],
)
>>> idx.take([2, 2, 1, 0])
MultiIndex([('c', 3),
('c', 3),
('b', 2),
('a', 1)],
)
"""
nv.validate_take((), kwargs)
indices = ensure_platform_int(indices)
# only fill if we are passing a non-None fill_value
allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices)
if indices.ndim == 1 and lib.is_range_indexer(indices, len(self)):
return self.copy()
na_value = -1
taken = [lab.take(indices) for lab in self.codes]
if allow_fill:
mask = indices == -1
if mask.any():
masked = []
for new_label in taken:
label_values = new_label
label_values[mask] = na_value
masked.append(np.asarray(label_values))
taken = masked
return MultiIndex(
levels=self.levels, codes=taken, names=self.names, verify_integrity=False
)
|
Return a new MultiIndex of the values selected by the indices.
For internal compatibility with numpy arrays.
Parameters
----------
indices : array-like
Indices to be taken.
axis : {0 or 'index'}, optional
The axis over which to select values, always 0 or 'index'.
allow_fill : bool, default True
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : scalar, default None
If allow_fill=True and fill_value is not None, indices specified by
-1 are regarded as NA. If Index doesn't hold NA, raise ValueError.
**kwargs
Required for compatibility with numpy.
Returns
-------
Index
An index formed of elements at the given indices. Will be the same
type as self, except for RangeIndex.
See Also
--------
numpy.ndarray.take: Return an array formed from the
elements of a at the given indices.
Examples
--------
>>> idx = pd.MultiIndex.from_arrays([["a", "b", "c"], [1, 2, 3]])
>>> idx
MultiIndex([('a', 1),
('b', 2),
('c', 3)],
)
>>> idx.take([2, 2, 1, 0])
MultiIndex([('c', 3),
('c', 3),
('b', 2),
('a', 1)],
)
|
python
|
pandas/core/indexes/multi.py
| 2,289
|
[
"self",
"indices",
"axis",
"allow_fill",
"fill_value"
] |
MultiIndex
| true
| 6
| 8.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
_get_module_class_registry
|
def _get_module_class_registry(
module_filepath: Path, module_name: str, class_extras: dict[str, Callable]
) -> dict[str, dict[str, Any]]:
"""
Extracts classes and its information from a Python module file.
The function parses the specified module file and registers all classes.
The registry for each class includes the module filename, methods, base classes
and any additional class extras provided.
:param module_filepath: The file path of the module.
:param class_extras: Additional information to include in each class's registry.
:return: A dictionary with class names as keys and their corresponding information.
"""
with open(module_filepath) as file:
ast_obj = ast.parse(file.read())
import_mappings = get_import_mappings(ast_obj)
module_class_registry = {
f"{module_name}.{node.name}": {
"methods": {n.name for n in ast.walk(node) if isinstance(n, ast.FunctionDef)},
"base_classes": [
import_mappings.get(b.id, f"{module_name}.{b.id}")
for b in node.bases
if isinstance(b, ast.Name)
],
**{
key: callable_(class_node=node, import_mappings=import_mappings)
for key, callable_ in class_extras.items()
},
}
for node in ast_obj.body
if isinstance(node, ast.ClassDef)
}
return module_class_registry
|
Extracts classes and its information from a Python module file.
The function parses the specified module file and registers all classes.
The registry for each class includes the module filename, methods, base classes
and any additional class extras provided.
:param module_filepath: The file path of the module.
:param class_extras: Additional information to include in each class's registry.
:return: A dictionary with class names as keys and their corresponding information.
|
python
|
devel-common/src/sphinx_exts/providers_extensions.py
| 150
|
[
"module_filepath",
"module_name",
"class_extras"
] |
dict[str, dict[str, Any]]
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
h3ToChildrenSize
|
public static long h3ToChildrenSize(long h3, int childRes) {
final int parentRes = H3Index.H3_get_resolution(h3);
if (childRes <= parentRes || childRes > MAX_H3_RES) {
throw new IllegalArgumentException("Invalid child resolution [" + childRes + "]");
}
final int n = childRes - parentRes;
if (H3Index.H3_is_pentagon(h3)) {
return (1L + 5L * (_ipow(7, n) - 1L) / 6L);
} else {
return _ipow(7, n);
}
}
|
h3ToChildrenSize returns the exact number of children for a cell at a
given child resolution.
@param h3 H3Index to find the number of children of
@param childRes The child resolution you're interested in
@return long Exact number of children (handles hexagons and pentagons
correctly)
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/H3.java
| 452
|
[
"h3",
"childRes"
] | true
| 4
| 7.76
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
_find_buffers_with_changed_last_use
|
def _find_buffers_with_changed_last_use(
candidate: BaseSchedulerNode,
gns: list[BaseSchedulerNode],
buf_to_snode_last_use: dict,
candidate_buffer_map: dict[BaseSchedulerNode, OrderedSet],
) -> dict[BaseSchedulerNode, list[Union[FreeableInputBuffer, Any]]]:
"""
Find buffers whose last use will change after swapping candidate with group.
When we swap [candidate [group]] to [[group] candidate], some buffers that
were last used by a group node will now be last used by candidate instead.
This affects memory deallocation timing.
Args:
candidate: The node being moved
gns: Group nodes being swapped with candidate
buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
candidate_buffer_map: Pre-computed map of node -> buffers using that node
Returns:
Dict mapping group nodes to buffers that will change their last-use node
"""
group_n_to_bufs_after_swap_dealloc_by_candidate: dict[
BaseSchedulerNode, list[Union[FreeableInputBuffer, Any]]
] = defaultdict(list)
# Optimization: only check buffers where candidate is a successor
# Reduces from O(all_buffers) to O(buffers_per_candidate)
candidate_bufs = candidate_buffer_map.get(candidate, OrderedSet())
gns_set = OrderedSet(gns) # O(1) membership testing
for buf in candidate_bufs:
snode_last_use = buf_to_snode_last_use[buf]
if snode_last_use in gns_set:
group_n_to_bufs_after_swap_dealloc_by_candidate[snode_last_use].append(buf)
return group_n_to_bufs_after_swap_dealloc_by_candidate
|
Find buffers whose last use will change after swapping candidate with group.
When we swap [candidate [group]] to [[group] candidate], some buffers that
were last used by a group node will now be last used by candidate instead.
This affects memory deallocation timing.
Args:
candidate: The node being moved
gns: Group nodes being swapped with candidate
buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
candidate_buffer_map: Pre-computed map of node -> buffers using that node
Returns:
Dict mapping group nodes to buffers that will change their last-use node
|
python
|
torch/_inductor/comms.py
| 687
|
[
"candidate",
"gns",
"buf_to_snode_last_use",
"candidate_buffer_map"
] |
dict[BaseSchedulerNode, list[Union[FreeableInputBuffer, Any]]]
| true
| 3
| 8.08
|
pytorch/pytorch
| 96,034
|
google
| false
|
compress_nd
|
def compress_nd(x, axis=None):
"""Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.
axis : tuple of ints or int, optional
Which dimensions to suppress slices from can be configured with this
parameter.
- If axis is a tuple of ints, those are the axes to suppress slices from.
- If axis is an int, then that is the only axis to suppress slices from.
- If axis is None, all axis are selected.
Returns
-------
compress_array : ndarray
The compressed array.
Examples
--------
>>> import numpy as np
>>> arr = [[1, 2], [3, 4]]
>>> mask = [[0, 1], [0, 0]]
>>> x = np.ma.array(arr, mask=mask)
>>> np.ma.compress_nd(x, axis=0)
array([[3, 4]])
>>> np.ma.compress_nd(x, axis=1)
array([[1],
[3]])
>>> np.ma.compress_nd(x)
array([[3]])
"""
x = asarray(x)
m = getmask(x)
# Set axis to tuple of ints
if axis is None:
axis = tuple(range(x.ndim))
else:
axis = normalize_axis_tuple(axis, x.ndim)
# Nothing is masked: return x
if m is nomask or not m.any():
return x._data
# All is masked: return empty
if m.all():
return nxarray([])
# Filter elements through boolean indexing
data = x._data
for ax in axis:
axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim)))
data = data[(slice(None),) * ax + (~m.any(axis=axes),)]
return data
|
Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.
axis : tuple of ints or int, optional
Which dimensions to suppress slices from can be configured with this
parameter.
- If axis is a tuple of ints, those are the axes to suppress slices from.
- If axis is an int, then that is the only axis to suppress slices from.
- If axis is None, all axis are selected.
Returns
-------
compress_array : ndarray
The compressed array.
Examples
--------
>>> import numpy as np
>>> arr = [[1, 2], [3, 4]]
>>> mask = [[0, 1], [0, 0]]
>>> x = np.ma.array(arr, mask=mask)
>>> np.ma.compress_nd(x, axis=0)
array([[3, 4]])
>>> np.ma.compress_nd(x, axis=1)
array([[1],
[3]])
>>> np.ma.compress_nd(x)
array([[3]])
|
python
|
numpy/ma/extras.py
| 841
|
[
"x",
"axis"
] | false
| 7
| 7.76
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
isKeyable
|
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
|
Checks if `value` is suitable for use as unique object key.
@private
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is suitable, else `false`.
|
javascript
|
lodash.js
| 6,425
|
[
"value"
] | false
| 5
| 6.24
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
resolveFilePath
|
@Nullable String resolveFilePath(String location, Resource resource);
|
Return the {@code path} of the given resource if it can also be represented as
a {@link FileSystemResource}.
@param location the location used to create the resource
@param resource the resource to check
@return the file path of the resource or {@code null} if the it is not possible
to represent the resource as a {@link FileSystemResource}.
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java
| 243
|
[
"location",
"resource"
] |
String
| true
| 1
| 6.32
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
copy
|
public static long copy(final InputStream in, final OutputStream out, byte[] buffer, boolean close) throws IOException {
Exception err = null;
try {
long byteCount = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
} catch (IOException | RuntimeException e) {
err = e;
throw e;
} finally {
if (close) {
IOUtils.close(err, in, out);
}
}
}
|
Copy the contents of the given InputStream to the given OutputStream. Optionally, closes both streams when done.
@param in the stream to copy from
@param out the stream to copy to
@param close whether to close both streams after copying
@param buffer buffer to use for copying
@return the number of bytes copied
@throws IOException in case of I/O errors
|
java
|
libs/core/src/main/java/org/elasticsearch/core/Streams.java
| 41
|
[
"in",
"out",
"buffer",
"close"
] | true
| 4
| 7.92
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
softmax
|
def softmax(X, copy=True):
"""
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
Parameters
----------
X : array-like of float of shape (M, N)
Argument to the logistic function.
copy : bool, default=True
Copy X or not.
Returns
-------
out : ndarray of shape (M, N)
Softmax function evaluated at every point in x.
"""
xp, is_array_api_compliant = get_namespace(X)
if copy:
X = xp.asarray(X, copy=True)
max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1))
X -= max_prob
if _is_numpy_namespace(xp):
# optimization for NumPy arrays
np.exp(X, out=np.asarray(X))
else:
# array_api does not have `out=`
X = xp.exp(X)
sum_prob = xp.reshape(xp.sum(X, axis=1), (-1, 1))
X /= sum_prob
return X
|
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
Parameters
----------
X : array-like of float of shape (M, N)
Argument to the logistic function.
copy : bool, default=True
Copy X or not.
Returns
-------
out : ndarray of shape (M, N)
Softmax function evaluated at every point in x.
|
python
|
sklearn/utils/extmath.py
| 981
|
[
"X",
"copy"
] | false
| 4
| 6.08
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
getProperty
|
@SuppressWarnings("unchecked")
private <T> @Nullable T getProperty(PropertyResolver resolver, String key, Class<T> type) {
try {
return resolver.getProperty(key, type);
}
catch (ConversionFailedException | ConverterNotFoundException ex) {
if (type != DataSize.class) {
throw ex;
}
String value = resolver.getProperty(key);
return (T) DataSize.ofBytes(FileSize.valueOf(value).getSize());
}
}
|
Create a new {@link LoggingSystemProperties} instance.
@param environment the source environment
@param defaultValueResolver function used to resolve default values or {@code null}
@param setter setter used to apply the property or {@code null} for system
properties
@since 3.2.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystemProperties.java
| 115
|
[
"resolver",
"key",
"type"
] |
T
| true
| 3
| 6.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
codes
|
def codes(self) -> FrozenList:
"""
Codes of the MultiIndex.
Codes are the position of the index value in the list of level values
for each level.
Returns
-------
tuple of numpy.ndarray
The codes of the MultiIndex. Each array in the tuple corresponds
to a level in the MultiIndex.
See Also
--------
MultiIndex.set_codes : Set new codes on MultiIndex.
Examples
--------
>>> arrays = [[1, 1, 2, 2], ["red", "blue", "red", "blue"]]
>>> mi = pd.MultiIndex.from_arrays(arrays, names=("number", "color"))
>>> mi.codes
FrozenList([[0, 0, 1, 1], [1, 0, 1, 0]])
"""
return self._codes
|
Codes of the MultiIndex.
Codes are the position of the index value in the list of level values
for each level.
Returns
-------
tuple of numpy.ndarray
The codes of the MultiIndex. Each array in the tuple corresponds
to a level in the MultiIndex.
See Also
--------
MultiIndex.set_codes : Set new codes on MultiIndex.
Examples
--------
>>> arrays = [[1, 1, 2, 2], ["red", "blue", "red", "blue"]]
>>> mi = pd.MultiIndex.from_arrays(arrays, names=("number", "color"))
>>> mi.codes
FrozenList([[0, 0, 1, 1], [1, 0, 1, 0]])
|
python
|
pandas/core/indexes/multi.py
| 1,107
|
[
"self"
] |
FrozenList
| true
| 1
| 6.08
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
getEnginesCommitHash
|
function getEnginesCommitHash(): string {
const npmEnginesVersion = dependenciesPrismaEnginesPkg['@prisma/engines-version']
const sha1Pattern = /\b[0-9a-f]{5,40}\b/
const commitHash = npmEnginesVersion.match(sha1Pattern)![0]
return commitHash
}
|
Only used when publishing to the `dev` and `integration` npm channels
(see `getNewDevVersion()` and `getNewIntegrationVersion()`)
@returns The next minor version for the `latest` channel
Example: If latest is `4.9.0` it will return `4.10.0`
|
typescript
|
scripts/ci/publish.ts
| 636
|
[] | true
| 1
| 6.08
|
prisma/prisma
| 44,834
|
jsdoc
| false
|
|
_decode32Bits
|
private int _decode32Bits() throws IOException {
int ptr = _inputPtr;
if ((ptr + 3) >= _inputEnd) {
return _slow32();
}
final byte[] b = _inputBuffer;
int v = (b[ptr++] << 24) + ((b[ptr++] & 0xFF) << 16) + ((b[ptr++] & 0xFF) << 8) + (b[ptr++] & 0xFF);
_inputPtr = ptr;
return v;
}
|
Method used to decode explicit length of a variable-length value
(or, for indefinite/chunked, indicate that one is not known).
Note that long (64-bit) length is only allowed if it fits in
32-bit signed int, for now; expectation being that longer values
are always encoded as chunks.
|
java
|
libs/x-content/impl/src/main/java/org/elasticsearch/xcontent/provider/cbor/ESCborParser.java
| 167
|
[] | true
| 2
| 6.88
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
createCollection
|
@Override
Set<V> createCollection() {
return Platform.newLinkedHashSetWithExpectedSize(valueSetCapacity);
}
|
{@inheritDoc}
<p>Creates an empty {@code LinkedHashSet} for a collection of values for one key.
@return a new {@code LinkedHashSet} containing a collection of values for one key
|
java
|
android/guava/src/com/google/common/collect/LinkedHashMultimap.java
| 178
|
[] | true
| 1
| 6.48
|
google/guava
| 51,352
|
javadoc
| false
|
|
close
|
@Override
public void close() {
if (closed == false) {
closed = true;
arrays.adjustBreaker(-SHALLOW_SIZE);
Releasables.close(values);
}
}
|
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/SortingDigest.java
| 164
|
[] |
void
| true
| 2
| 6.88
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
isAutowireCandidate
|
protected boolean isAutowireCandidate(
String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
throws NoSuchBeanDefinitionException {
String bdName = transformedBeanName(beanName);
if (containsBeanDefinition(bdName)) {
return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(bdName), descriptor, resolver);
}
else if (containsSingleton(beanName)) {
return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
}
BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory dlbf) {
// No bean definition found in this factory -> delegate to parent.
return dlbf.isAutowireCandidate(beanName, descriptor, resolver);
}
else if (parent instanceof ConfigurableListableBeanFactory clbf) {
// If no DefaultListableBeanFactory, can't pass the resolver along.
return clbf.isAutowireCandidate(beanName, descriptor);
}
else {
return true;
}
}
|
Determine whether the specified bean definition qualifies as an autowire candidate,
to be injected into other beans which declare a dependency of matching type.
@param beanName the name of the bean definition to check
@param descriptor the descriptor of the dependency to resolve
@param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
@return whether the bean should be considered as autowire candidate
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
| 914
|
[
"beanName",
"descriptor",
"resolver"
] | true
| 5
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
get_rocm_bundler
|
def get_rocm_bundler() -> str:
"""
Get path to clang-offload-bundler.
Uses PyTorch's ROCM_HOME detection.
Returns:
Path to bundler
Raises:
RuntimeError: If bundler is not found
"""
if ROCM_HOME is None:
raise RuntimeError(
"ROCm installation not found. "
"PyTorch was not built with ROCm support or ROCM_HOME is not set."
)
# Bundler is at <ROCM_HOME>/llvm/bin/clang-offload-bundler
bundler_path = _join_rocm_home("llvm", "bin", "clang-offload-bundler")
if not os.path.exists(bundler_path):
raise RuntimeError(
f"clang-offload-bundler not found at {bundler_path}. "
f"ROCM_HOME is set to {ROCM_HOME}"
)
return bundler_path
|
Get path to clang-offload-bundler.
Uses PyTorch's ROCM_HOME detection.
Returns:
Path to bundler
Raises:
RuntimeError: If bundler is not found
|
python
|
torch/_inductor/rocm_multiarch_utils.py
| 42
|
[] |
str
| true
| 3
| 7.76
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
getDefaultEditor
|
public @Nullable PropertyEditor getDefaultEditor(Class<?> requiredType) {
if (!this.defaultEditorsActive) {
return null;
}
if (this.overriddenDefaultEditors == null && this.defaultEditorRegistrar != null) {
this.defaultEditorRegistrar.registerCustomEditors(this);
}
if (this.overriddenDefaultEditors != null) {
PropertyEditor editor = this.overriddenDefaultEditors.get(requiredType);
if (editor != null) {
return editor;
}
}
if (this.defaultEditors == null) {
createDefaultEditors();
}
return this.defaultEditors.get(requiredType);
}
|
Retrieve the default editor for the given property type, if any.
<p>Lazily registers the default editors, if they are active.
@param requiredType type of the property
@return the default editor, or {@code null} if none found
@see #registerDefaultEditors
|
java
|
spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java
| 190
|
[
"requiredType"
] |
PropertyEditor
| true
| 7
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
send
|
default void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException {
try {
List<MimeMessage> mimeMessages = new ArrayList<>(mimeMessagePreparators.length);
for (MimeMessagePreparator preparator : mimeMessagePreparators) {
MimeMessage mimeMessage = createMimeMessage();
preparator.prepare(mimeMessage);
mimeMessages.add(mimeMessage);
}
send(mimeMessages.toArray(new MimeMessage[0]));
}
catch (MailException ex) {
throw ex;
}
catch (MessagingException ex) {
throw new MailParseException(ex);
}
catch (Exception ex) {
throw new MailPreparationException(ex);
}
}
|
Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.
<p>Alternative way to prepare MimeMessage instances, instead of
{@link #createMimeMessage()} and {@link #send(MimeMessage[])} calls.
Takes care of proper exception conversion.
@param mimeMessagePreparators the preparator to use
@throws org.springframework.mail.MailPreparationException
in case of failure when preparing a message
@throws org.springframework.mail.MailParseException
in case of failure when parsing a message
@throws org.springframework.mail.MailAuthenticationException
in case of authentication failure
@throws org.springframework.mail.MailSendException
in case of failure when sending a message
|
java
|
spring-context-support/src/main/java/org/springframework/mail/javamail/JavaMailSender.java
| 150
|
[] |
void
| true
| 4
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
findLibSSL
|
async function findLibSSL(directory: string) {
try {
const dirContents = await fs.readdir(directory)
return dirContents.find((value) => value.startsWith('libssl.so.') && !value.startsWith('libssl.so.0'))
} catch (e) {
if (e.code === 'ENOENT') {
return undefined
}
throw e
}
}
|
Looks for libssl in specific directory
@param directory
@returns
|
typescript
|
packages/get-platform/src/getPlatform.ts
| 425
|
[
"directory"
] | false
| 4
| 6.32
|
prisma/prisma
| 44,834
|
jsdoc
| true
|
|
lastIndexIn
|
public int lastIndexIn(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
|
Returns the index of the last matching BMP character in a character sequence, or {@code -1} if
no matching character is present.
<p>The default implementation iterates over the sequence in reverse order calling {@link
#matches} for each character.
@param sequence the character sequence to examine from the end
@return an index, or {@code -1} if no character matches
|
java
|
android/guava/src/com/google/common/base/CharMatcher.java
| 584
|
[
"sequence"
] | true
| 3
| 8.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
add
|
Headers add(String key, byte[] value) throws IllegalStateException;
|
Creates and adds a header, to the end, returning if the operation succeeded.
@param key of the header to be added; must not be null.
@param value of the header to be added; may be null.
@return this instance of the Headers, once the header is added.
@throws IllegalStateException is thrown if headers are in a read-only state.
|
java
|
clients/src/main/java/org/apache/kafka/common/header/Headers.java
| 44
|
[
"key",
"value"
] |
Headers
| true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
toString
|
@Override
public String toString() {
return Double.toString(get());
}
|
Returns the String representation of the current value.
@return the String representation of the current value
|
java
|
android/guava/src/com/google/common/util/concurrent/AtomicDouble.java
| 189
|
[] |
String
| true
| 1
| 6.8
|
google/guava
| 51,352
|
javadoc
| false
|
getCustomTargetSource
|
protected @Nullable TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
// We can't create fancy target sources for directly registered singletons.
if (this.customTargetSourceCreators != null &&
this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
TargetSource ts = tsc.getTargetSource(beanClass, beanName);
if (ts != null) {
// Found a matching TargetSource.
if (logger.isTraceEnabled()) {
logger.trace("TargetSourceCreator [" + tsc +
"] found custom TargetSource for bean with name '" + beanName + "'");
}
return ts;
}
}
}
// No custom TargetSource found.
return null;
}
|
Create a target source for bean instances. Uses any TargetSourceCreators if set.
Returns {@code null} if no custom TargetSource should be used.
<p>This implementation uses the "customTargetSourceCreators" property.
Subclasses can override this method to use a different mechanism.
@param beanClass the class of the bean to create a TargetSource for
@param beanName the name of the bean
@return a TargetSource for this bean
@see #setCustomTargetSourceCreators
|
java
|
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java
| 396
|
[
"beanClass",
"beanName"
] |
TargetSource
| true
| 6
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
getBeanDefinitionRegistry
|
private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) {
if (context instanceof BeanDefinitionRegistry registry) {
return registry;
}
if (context instanceof AbstractApplicationContext abstractApplicationContext) {
return (BeanDefinitionRegistry) abstractApplicationContext.getBeanFactory();
}
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
}
|
Get the bean definition registry.
@param context the application context
@return the BeanDefinitionRegistry if it can be determined
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
| 731
|
[
"context"
] |
BeanDefinitionRegistry
| true
| 3
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
decideClassloader
|
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
|
Loads the relocations from the classpath. Relocations are stored in files named
{@code META-INF/spring/full-qualified-annotation-name.replacements} on the
classpath. The file is loaded using {@link Properties#load(java.io.InputStream)}
with each entry containing an auto-configuration class name as the key and the
replacement class name as the value.
@param annotation annotation to load
@param classLoader class loader to use for loading
@return list of names of annotated classes
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationReplacements.java
| 106
|
[
"classLoader"
] |
ClassLoader
| true
| 2
| 7.44
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
toString
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append(": advice ");
if (this.adviceBeanName != null) {
sb.append("bean '").append(this.adviceBeanName).append('\'');
}
else {
sb.append(this.advice);
}
return sb.toString();
}
|
Specify a particular instance of the target advice directly,
avoiding lazy resolution in {@link #getAdvice()}.
@since 3.1
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AbstractBeanFactoryPointcutAdvisor.java
| 118
|
[] |
String
| true
| 2
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
addAll
|
@CanIgnoreReturnValue
public Builder<E> addAll(Iterator<? extends E> elements) {
while (elements.hasNext()) {
add(elements.next());
}
return this;
}
|
Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
<p>Note that each builder class overrides this method in order to covariantly return its own
type.
@param elements the elements to add
@return this {@code Builder} instance
@throws NullPointerException if {@code elements} is null or contains a null element
|
java
|
android/guava/src/com/google/common/collect/ImmutableCollection.java
| 477
|
[
"elements"
] | true
| 2
| 7.76
|
google/guava
| 51,352
|
javadoc
| false
|
|
getMainClass
|
private @Nullable String getMainClass(JarFile source, Manifest manifest) throws IOException {
if (this.mainClass != null) {
return this.mainClass;
}
String attributeValue = manifest.getMainAttributes().getValue(MAIN_CLASS_ATTRIBUTE);
if (attributeValue != null) {
return attributeValue;
}
return findMainMethodWithTimeoutWarning(source);
}
|
Writes a signature file if necessary for the given {@code writtenLibraries}.
@param writtenLibraries the libraries
@param writer the writer to use to write the signature file if necessary
@throws IOException if a failure occurs when writing the signature file
|
java
|
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java
| 332
|
[
"source",
"manifest"
] |
String
| true
| 3
| 6.56
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
nextInLineFetch
|
ShareCompletedFetch nextInLineFetch() {
lock.lock();
try {
return nextInLineFetch;
} finally {
lock.unlock();
}
}
|
Returns {@code true} if there are no completed fetches pending to return to the user.
@return {@code true} if the buffer is empty, {@code false} otherwise
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareFetchBuffer.java
| 86
|
[] |
ShareCompletedFetch
| true
| 1
| 7.04
|
apache/kafka
| 31,560
|
javadoc
| false
|
forBindables
|
public static BindableRuntimeHintsRegistrar forBindables(Bindable<?>... bindables) {
return new BindableRuntimeHintsRegistrar(bindables);
}
|
Create a new {@link BindableRuntimeHintsRegistrar} for the specified bindables.
@param bindables the bindables to process
@return a new {@link BindableRuntimeHintsRegistrar} instance
@since 3.0.8
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java
| 142
|
[] |
BindableRuntimeHintsRegistrar
| true
| 1
| 6.32
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
of
|
public static TaggedFieldsSection of(Object... fields) {
return new TaggedFieldsSection(TaggedFields.of(fields));
}
|
Create a new TaggedFieldsSection with the given tags and fields.
@param fields This is an array containing Integer tags followed
by associated Field objects.
@return The new {@link TaggedFieldsSection}
|
java
|
clients/src/main/java/org/apache/kafka/common/protocol/types/Field.java
| 60
|
[] |
TaggedFieldsSection
| true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
visitObjectLiteralExpression
|
function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression {
const properties = node.properties;
// Find the first computed property.
// Everything until that point can be emitted as part of the initial object literal.
let numInitialProperties = -1, hasComputed = false;
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (
(property.transformFlags & TransformFlags.ContainsYield &&
hierarchyFacts & HierarchyFacts.AsyncFunctionBody)
|| (hasComputed = Debug.checkDefined(property.name).kind === SyntaxKind.ComputedPropertyName)
) {
numInitialProperties = i;
break;
}
}
if (numInitialProperties < 0) {
return visitEachChild(node, visitor, context);
}
// For computed properties, we need to create a unique handle to the object
// literal so we can modify it without risking internal assignments tainting the object.
const temp = factory.createTempVariable(hoistVariableDeclaration);
// Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
const expressions: Expression[] = [];
const assignment = factory.createAssignment(
temp,
setEmitFlags(
factory.createObjectLiteralExpression(
visitNodes(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties),
node.multiLine,
),
hasComputed ? EmitFlags.Indented : 0,
),
);
if (node.multiLine) {
startOnNewLine(assignment);
}
expressions.push(assignment);
addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
// We need to clone the temporary identifier so that we can write it on a
// new line
expressions.push(node.multiLine ? startOnNewLine(setParent(setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
return factory.inlineExpressions(expressions);
}
|
Visits an ObjectLiteralExpression with computed property names.
@param node An ObjectLiteralExpression node.
|
typescript
|
src/compiler/transformers/es2015.ts
| 3,310
|
[
"node"
] | true
| 9
| 6.24
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
reorder_levels
|
def reorder_levels(self, order) -> MultiIndex:
"""
Rearrange levels using input order. May not drop or duplicate levels.
`reorder_levels` is useful when you need to change the order of levels in
a MultiIndex, such as when reordering levels for hierarchical indexing. It
maintains the integrity of the MultiIndex, ensuring that all existing levels
are present and no levels are duplicated. This method is helpful for aligning
the index structure with other data structures or for optimizing the order
for specific data operations.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
Returns
-------
MultiIndex
A new MultiIndex with levels rearranged according to the specified order.
See Also
--------
MultiIndex.swaplevel : Swap two levels of the MultiIndex.
MultiIndex.set_names : Set names for the MultiIndex levels.
DataFrame.reorder_levels : Reorder levels in a DataFrame with a MultiIndex.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"])
>>> mi
MultiIndex([(1, 3),
(2, 4)],
names=['x', 'y'])
>>> mi.reorder_levels(order=[1, 0])
MultiIndex([(3, 1),
(4, 2)],
names=['y', 'x'])
>>> mi.reorder_levels(order=["y", "x"])
MultiIndex([(3, 1),
(4, 2)],
names=['y', 'x'])
"""
order = [self._get_level_number(i) for i in order]
result = self._reorder_ilevels(order)
return result
|
Rearrange levels using input order. May not drop or duplicate levels.
`reorder_levels` is useful when you need to change the order of levels in
a MultiIndex, such as when reordering levels for hierarchical indexing. It
maintains the integrity of the MultiIndex, ensuring that all existing levels
are present and no levels are duplicated. This method is helpful for aligning
the index structure with other data structures or for optimizing the order
for specific data operations.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
Returns
-------
MultiIndex
A new MultiIndex with levels rearranged according to the specified order.
See Also
--------
MultiIndex.swaplevel : Swap two levels of the MultiIndex.
MultiIndex.set_names : Set names for the MultiIndex levels.
DataFrame.reorder_levels : Reorder levels in a DataFrame with a MultiIndex.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"])
>>> mi
MultiIndex([(1, 3),
(2, 4)],
names=['x', 'y'])
>>> mi.reorder_levels(order=[1, 0])
MultiIndex([(3, 1),
(4, 2)],
names=['y', 'x'])
>>> mi.reorder_levels(order=["y", "x"])
MultiIndex([(3, 1),
(4, 2)],
names=['y', 'x'])
|
python
|
pandas/core/indexes/multi.py
| 2,779
|
[
"self",
"order"
] |
MultiIndex
| true
| 1
| 7.12
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
equal
|
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
|
Returns true if the given files exist, are not directories, and contain the same bytes.
@throws IOException if an I/O error occurs
|
java
|
android/guava/src/com/google/common/io/Files.java
| 371
|
[
"file1",
"file2"
] | true
| 6
| 6
|
google/guava
| 51,352
|
javadoc
| false
|
|
predict
|
def predict(self, X):
"""Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
returned; in this case, points are not considered their own
neighbors.
Returns
-------
y : ndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int
Target values.
"""
if self.weights == "uniform":
# In that case, we do not need the distances to perform
# the weighting so we do not compute them.
neigh_ind = self.kneighbors(X, return_distance=False)
neigh_dist = None
else:
neigh_dist, neigh_ind = self.kneighbors(X)
weights = _get_weights(neigh_dist, self.weights)
_y = self._y
if _y.ndim == 1:
_y = _y.reshape((-1, 1))
if weights is None:
y_pred = np.mean(_y[neigh_ind], axis=1)
else:
y_pred = np.empty((neigh_dist.shape[0], _y.shape[1]), dtype=np.float64)
denom = np.sum(weights, axis=1)
for j in range(_y.shape[1]):
num = np.sum(_y[neigh_ind, j] * weights, axis=1)
y_pred[:, j] = num / denom
if self._y.ndim == 1:
y_pred = y_pred.ravel()
return y_pred
|
Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
returned; in this case, points are not considered their own
neighbors.
Returns
-------
y : ndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int
Target values.
|
python
|
sklearn/neighbors/_regression.py
| 229
|
[
"self",
"X"
] | false
| 8
| 6.08
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
getTargetClass
|
public static Class<?> getTargetClass(Object candidate) {
Assert.notNull(candidate, "Candidate object must not be null");
Class<?> result = null;
if (candidate instanceof TargetClassAware targetClassAware) {
result = targetClassAware.getTargetClass();
}
if (result == null) {
result = (isCglibProxy(candidate) ? candidate.getClass().getSuperclass() : candidate.getClass());
}
return result;
}
|
Determine the target class of the given bean instance which might be an AOP proxy.
<p>Returns the target class for an AOP proxy or the plain class otherwise.
@param candidate the instance to check (might be an AOP proxy)
@return the target class (or the plain class of the given object as fallback;
never {@code null})
@see org.springframework.aop.TargetClassAware#getTargetClass()
@see org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass(Object)
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
| 123
|
[
"candidate"
] | true
| 4
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
assignedState
|
private TopicPartitionState assignedState(TopicPartition tp) {
TopicPartitionState state = this.assignment.stateValue(tp);
if (state == null)
throw new IllegalStateException("No current assignment for partition " + tp);
return state;
}
|
Get the subscription topics for which metadata is required. For the leader, this will include
the union of the subscriptions of all group members. For followers, it is just that member's
subscription. This is used when querying topic metadata to detect the metadata changes which would
require rebalancing. The leader fetches metadata for all topics in the group so that it
can do the partition assignment (which requires at least partition counts for all topics
to be assigned).
@return The union of all subscribed topics in the group if this member is the leader
of the current generation; otherwise it returns the same set as {@link #subscription()}
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
| 426
|
[
"tp"
] |
TopicPartitionState
| true
| 2
| 6.72
|
apache/kafka
| 31,560
|
javadoc
| false
|
putIfAbsent
|
default @Nullable ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
ValueWrapper existingValue = get(key);
if (existingValue == null) {
put(key, value);
}
return existingValue;
}
|
Atomically associate the specified value with the specified key in this cache
if it is not set already.
<p>This is equivalent to:
<pre><code>
ValueWrapper existingValue = cache.get(key);
if (existingValue == null) {
cache.put(key, value);
}
return existingValue;
</code></pre>
except that the action is performed atomically. While all out-of-the-box
{@link CacheManager} implementations are able to perform the put atomically,
the operation may also be implemented in two steps, for example, with a check for
presence and a subsequent put, in a non-atomic way. Check the documentation
of the native cache implementation that you are using for more details.
<p>The default implementation delegates to {@link #get(Object)} and
{@link #put(Object, Object)} along the lines of the code snippet above.
@param key the key with which the specified value is to be associated
@param value the value to be associated with the specified key
@return the value to which this cache maps the specified key (which may be
{@code null} itself), or also {@code null} if the cache did not contain any
mapping for that key prior to this call. Returning {@code null} is therefore
an indicator that the given {@code value} has been associated with the key.
@since 4.1
@see #put(Object, Object)
|
java
|
spring-context/src/main/java/org/springframework/cache/Cache.java
| 213
|
[
"key",
"value"
] |
ValueWrapper
| true
| 2
| 7.92
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
_generate_range_overflow_safe
|
def _generate_range_overflow_safe(
endpoint: int, periods: int, stride: int, side: str = "start"
) -> int:
"""
Calculate the second endpoint for passing to np.arange, checking
to avoid an integer overflow. Catch OverflowError and re-raise
as OutOfBoundsDatetime.
Parameters
----------
endpoint : int
nanosecond timestamp of the known endpoint of the desired range
periods : int
number of periods in the desired range
stride : int
nanoseconds between periods in the desired range
side : {'start', 'end'}
which end of the range `endpoint` refers to
Returns
-------
other_end : int
Raises
------
OutOfBoundsDatetime
"""
# GH#14187 raise instead of incorrectly wrapping around
assert side in ["start", "end"]
i64max = np.uint64(i8max)
msg = f"Cannot generate range with {side}={endpoint} and periods={periods}"
with np.errstate(over="raise"):
# if periods * strides cannot be multiplied within the *uint64* bounds,
# we cannot salvage the operation by recursing, so raise
try:
addend = np.uint64(periods) * np.uint64(np.abs(stride))
except FloatingPointError as err:
raise OutOfBoundsDatetime(msg) from err
if np.abs(addend) <= i64max:
# relatively easy case without casting concerns
return _generate_range_overflow_safe_signed(endpoint, periods, stride, side)
elif (endpoint > 0 and side == "start" and stride > 0) or (
endpoint < 0 < stride and side == "end"
):
# no chance of not-overflowing
raise OutOfBoundsDatetime(msg)
elif side == "end" and endpoint - stride <= i64max < endpoint:
# in _generate_regular_range we added `stride` thereby overflowing
# the bounds. Adjust to fix this.
return _generate_range_overflow_safe(
endpoint - stride, periods - 1, stride, side
)
# split into smaller pieces
mid_periods = periods // 2
remaining = periods - mid_periods
assert 0 < remaining < periods, (remaining, periods, endpoint, stride)
midpoint = int(_generate_range_overflow_safe(endpoint, mid_periods, stride, side))
return _generate_range_overflow_safe(midpoint, remaining, stride, side)
|
Calculate the second endpoint for passing to np.arange, checking
to avoid an integer overflow. Catch OverflowError and re-raise
as OutOfBoundsDatetime.
Parameters
----------
endpoint : int
nanosecond timestamp of the known endpoint of the desired range
periods : int
number of periods in the desired range
stride : int
nanoseconds between periods in the desired range
side : {'start', 'end'}
which end of the range `endpoint` refers to
Returns
-------
other_end : int
Raises
------
OutOfBoundsDatetime
|
python
|
pandas/core/arrays/_ranges.py
| 99
|
[
"endpoint",
"periods",
"stride",
"side"
] |
int
| true
| 9
| 6.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
applyEditorRegistrars
|
private void applyEditorRegistrars(PropertyEditorRegistry registry, Set<PropertyEditorRegistrar> registrars) {
for (PropertyEditorRegistrar registrar : registrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException bce) {
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
return;
}
}
throw ex;
}
}
}
|
Initialize the given PropertyEditorRegistry with the custom editors
that have been registered with this BeanFactory.
<p>To be called for BeanWrappers that will create and populate bean
instances, and for SimpleTypeConverter used for constructor argument
and factory method type conversion.
@param registry the PropertyEditorRegistry to initialize
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
| 1,331
|
[
"registry",
"registrars"
] |
void
| true
| 6
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
applyNonNull
|
public static <T, R, E extends Throwable> R applyNonNull(final T value, final FailableFunction<? super T, ? extends R, E> mapper) throws E {
return value != null ? Objects.requireNonNull(mapper, "mapper").apply(value) : null;
}
|
Applies a value to a function if the value isn't {@code null}, otherwise the method returns {@code null}. If the value isn't {@code null} then return the
result of the applying function.
<pre>{@code
Failable.applyNonNull("a", String::toUpperCase) = "A"
Failable.applyNonNull(null, String::toUpperCase) = null
Failable.applyNonNull("a", s -> null) = null
}</pre>
<p>
Useful when working with expressions that may return {@code null} as it allows a single-line expression without using temporary local variables or
evaluating expressions twice. Provides an alternative to using {@link Optional} that is shorter and has less allocation.
</p>
@param <T> The type of the input of this method and the function.
@param <R> The type of the result of the function and this method.
@param <E> The type of thrown exception or error.
@param value The value to apply the function to, may be {@code null}.
@param mapper The function to apply, must not be {@code null}.
@return The result of the function (which may be {@code null}) or {@code null} if the input value is {@code null}.
@throws E Thrown by the given function.
@see #applyNonNull(Object, FailableFunction, FailableFunction)
@see #applyNonNull(Object, FailableFunction, FailableFunction, FailableFunction)
@since 3.19.0
|
java
|
src/main/java/org/apache/commons/lang3/function/Failable.java
| 204
|
[
"value",
"mapper"
] |
R
| true
| 2
| 7.84
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
unescapeHtml3
|
public static final String unescapeHtml3(final String input) {
return UNESCAPE_HTML3.translate(input);
}
|
Unescapes a string containing entity escapes to a string
containing the actual Unicode characters corresponding to the
escapes. Supports only HTML 3.0 entities.
@param input the {@link String} to unescape, may be null
@return a new unescaped {@link String}, {@code null} if null string input
@since 3.0
|
java
|
src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
| 709
|
[
"input"
] |
String
| true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
clear
|
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
this.firstEntry = ENDPOINT;
this.lastEntry = ENDPOINT;
if (links != null) {
Arrays.fill(links, 0, size(), 0);
}
super.clear();
}
|
Pointer to the last node in the linked list, or {@code ENDPOINT} if there are no entries.
|
java
|
android/guava/src/com/google/common/collect/CompactLinkedHashMap.java
| 225
|
[] |
void
| true
| 3
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
convert_conv_weights_to_channels_last
|
def convert_conv_weights_to_channels_last(gm: torch.fx.GraphModule):
"""
Convert 4d convolution weight tensor to channels last format.
This pass is performed before freezing so the added nodes can be constant
folded by freezing.
"""
with dynamo_timed("convert_conv_weights_to_channels_last"):
convs = [n for n in gm.graph.nodes if n.target is aten.convolution.default]
for conv in convs:
weight_node = conv.args[1]
if len(weight_node.meta["val"].size()) != 4 or weight_node.meta[
"val"
].is_contiguous(memory_format=torch.channels_last):
# not a 4d tensor or already channels last, skip
continue
with gm.graph.inserting_before(conv):
new_node = gm.graph.call_function(
aten.clone.default,
(weight_node,),
{"memory_format": torch.channels_last},
)
conv.replace_input_with(weight_node, new_node)
enforce_as_strided_input_layout(gm)
enforce_output_layout(gm)
|
Convert 4d convolution weight tensor to channels last format.
This pass is performed before freezing so the added nodes can be constant
folded by freezing.
|
python
|
torch/_inductor/freezing.py
| 266
|
[
"gm"
] | true
| 4
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
|
endSwitchBlock
|
function endSwitchBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Switch);
const block = endBlock() as SwitchBlock;
const breakLabel = block.breakLabel;
if (!block.isScript) {
markLabel(breakLabel);
}
}
|
Ends a code block that supports `break` statements that are defined in generated code.
|
typescript
|
src/compiler/transformers/generators.ts
| 2,379
|
[] | true
| 2
| 7.04
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
lockApplyUnlock
|
protected <T> T lockApplyUnlock(final Supplier<Lock> lockSupplier, final FailableFunction<O, T, ?> function) {
final Lock lock = Objects.requireNonNull(Suppliers.get(lockSupplier), "lock");
lock.lock();
try {
return Failable.apply(function, object);
} finally {
lock.unlock();
}
}
|
This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and
{@link #applyWriteLocked(FailableFunction)}.
@param <T> The result type (both the functions, and this method's.)
@param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used
internally.)
@param function The function, which is being invoked to compute the result object. This function will receive
The object to protect as a parameter.
@return The result object, which has been returned by the functions invocation.
@throws IllegalStateException The result object would be, in fact, the hidden object. This would extend
access to the hidden object beyond this methods lifetime and will therefore be prevented.
@see #applyReadLocked(FailableFunction)
@see #applyWriteLocked(FailableFunction)
|
java
|
src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
| 455
|
[
"lockSupplier",
"function"
] |
T
| true
| 1
| 6.4
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
_parse_secret_file
|
def _parse_secret_file(file_path: str) -> dict[str, Any]:
"""
Based on the file extension format, selects a parser, and parses the file.
:param file_path: The location of the file that will be processed.
:return: Map of secret key (e.g. connection ID) and value.
:raises AirflowUnsupportedFileTypeException: If the file type is not supported.
:raises AirflowFileParseException: If the file has syntax errors.
"""
log.debug("Parsing file: %s", file_path)
ext = Path(file_path).suffix.lstrip(".").lower()
if ext not in FILE_PARSERS:
extensions = " ".join([f".{ext}" for ext in sorted(FILE_PARSERS.keys())])
raise AirflowUnsupportedFileTypeException(
f"Unsupported file format. The file must have one of the following extensions: {extensions}"
)
secrets, parse_errors = FILE_PARSERS[ext](file_path)
log.debug("Parsed file: len(parse_errors)=%d, len(secrets)=%d", len(parse_errors), len(secrets))
if parse_errors:
raise AirflowFileParseException(
"Failed to load the secret file.", file_path=file_path, parse_errors=parse_errors
)
return secrets
|
Based on the file extension format, selects a parser, and parses the file.
:param file_path: The location of the file that will be processed.
:return: Map of secret key (e.g. connection ID) and value.
:raises AirflowUnsupportedFileTypeException: If the file type is not supported.
:raises AirflowFileParseException: If the file has syntax errors.
|
python
|
airflow-core/src/airflow/secrets/local_filesystem.py
| 165
|
[
"file_path"
] |
dict[str, Any]
| true
| 3
| 7.92
|
apache/airflow
| 43,597
|
sphinx
| false
|
millisFrac
|
public double millisFrac() {
return ((double) nanos()) / C2;
}
|
@return the number of {@link #timeUnit()} units this value contains
|
java
|
libs/core/src/main/java/org/elasticsearch/core/TimeValue.java
| 178
|
[] | true
| 1
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
tryGetLocalNamedExportCompletionSymbols
|
function tryGetLocalNamedExportCompletionSymbols(): GlobalsSearch {
const namedExports = contextToken && (contextToken.kind === SyntaxKind.OpenBraceToken || contextToken.kind === SyntaxKind.CommaToken)
? tryCast(contextToken.parent, isNamedExports)
: undefined;
if (!namedExports) {
return GlobalsSearch.Continue;
}
const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration))!;
completionKind = CompletionKind.None;
isNewIdentifierLocation = false;
localsContainer.locals?.forEach((symbol, name) => {
symbols.push(symbol);
if (localsContainer.symbol?.exports?.has(name)) {
symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember;
}
});
return GlobalsSearch.Success;
}
|
Adds local declarations for completions in named exports:
export { | };
Does not check for the absence of a module specifier (`export {} from "./other"`)
because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that,
preventing this function from running.
|
typescript
|
src/services/completions.ts
| 4,707
|
[] | true
| 6
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
toString
|
@Override
public String toString() {
return StringUtils.repeat(this.value.toString(), this.count);
}
|
Represents this token as a String.
@return String representation of the token
|
java
|
src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java
| 190
|
[] |
String
| true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
asFunction
|
public static <I, O> Function<I, O> asFunction(final FailableFunction<I, O, ?> function) {
return input -> apply(function, input);
}
|
Converts the given {@link FailableFunction} into a standard {@link Function}.
@param <I> the type of the input of the functions
@param <O> the type of the output of the functions
@param function a {code FailableFunction}
@return a standard {@link Function}
@since 3.10
|
java
|
src/main/java/org/apache/commons/lang3/Functions.java
| 416
|
[
"function"
] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
withFileNameLength
|
ZipCentralDirectoryFileHeaderRecord withFileNameLength(short fileNameLength) {
return (this.fileNameLength != fileNameLength) ? new ZipCentralDirectoryFileHeaderRecord(this.versionMadeBy,
this.versionNeededToExtract, this.generalPurposeBitFlag, this.compressionMethod, this.lastModFileTime,
this.lastModFileDate, this.crc32, this.compressedSize, this.uncompressedSize, fileNameLength,
this.extraFieldLength, this.fileCommentLength, this.diskNumberStart, this.internalFileAttributes,
this.externalFileAttributes, this.offsetToLocalHeader) : this;
}
|
Return a new {@link ZipCentralDirectoryFileHeaderRecord} with a new
{@link #fileNameLength()}.
@param fileNameLength the new file name length
@return a new {@link ZipCentralDirectoryFileHeaderRecord} instance
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipCentralDirectoryFileHeaderRecord.java
| 138
|
[
"fileNameLength"
] |
ZipCentralDirectoryFileHeaderRecord
| true
| 2
| 7.12
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
strerror
|
String strerror(int errno);
|
Return a string description for an error.
@param errno The error number
@return a String description for the error
@see <a href="https://man7.org/linux/man-pages/man3/strerror.3.html">strerror manpage</a>
|
java
|
libs/native/src/main/java/org/elasticsearch/nativeaccess/lib/PosixCLibrary.java
| 156
|
[
"errno"
] |
String
| true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
update
|
def update(
key: str,
value: Any,
serialize_json: bool = False,
team_name: str | None = None,
session: Session | None = None,
) -> None:
"""
Update a given Airflow Variable with the Provided value.
:param key: Variable Key
:param value: Value to set for the Variable
:param serialize_json: Serialize the value to a JSON string
:param team_name: Team name associated to the variable (if any)
:param session: optional session, use if provided or create a new one
"""
# TODO: This is not the best way of having compat, but it's "better than erroring" for now. This still
# means SQLA etc is loaded, but we can't avoid that unless/until we add import shims as a big
# back-compat layer
# If this is set it means are in some kind of execution context (Task, Dag Parse or Triggerer perhaps)
# and should use the Task SDK API server path
if hasattr(sys.modules.get("airflow.sdk.execution_time.task_runner"), "SUPERVISOR_COMMS"):
warnings.warn(
"Using Variable.update from `airflow.models` is deprecated."
"Please use `set` on Variable from sdk(`airflow.sdk.Variable`) instead as it is an upsert.",
DeprecationWarning,
stacklevel=1,
)
from airflow.sdk import Variable as TaskSDKVariable
# set is an upsert command, it can handle updates too
TaskSDKVariable.set(
key=key,
value=value,
serialize_json=serialize_json,
)
return
if team_name and not conf.getboolean("core", "multi_team"):
raise ValueError(
"Multi-team mode is not configured in the Airflow environment. To assign a team to a variable, multi-mode must be enabled."
)
Variable.check_for_write_conflict(key=key)
if Variable.get_variable_from_secrets(key=key, team_name=team_name) is None:
raise KeyError(f"Variable {key} does not exist")
ctx: contextlib.AbstractContextManager
if session is not None:
ctx = contextlib.nullcontext(session)
else:
ctx = create_session()
with ctx as session:
obj = session.scalar(
select(Variable).where(
Variable.key == key, or_(Variable.team_name == team_name, Variable.team_name.is_(None))
)
)
if obj is None:
raise AttributeError(f"Variable {key} does not exist in the Database and cannot be updated.")
Variable.set(
key=key,
value=value,
description=obj.description,
serialize_json=serialize_json,
session=session,
)
|
Update a given Airflow Variable with the Provided value.
:param key: Variable Key
:param value: Value to set for the Variable
:param serialize_json: Serialize the value to a JSON string
:param team_name: Team name associated to the variable (if any)
:param session: optional session, use if provided or create a new one
|
python
|
airflow-core/src/airflow/models/variable.py
| 325
|
[
"key",
"value",
"serialize_json",
"team_name",
"session"
] |
None
| true
| 8
| 6.8
|
apache/airflow
| 43,597
|
sphinx
| false
|
asFunction
|
public static <T, R> Function<T, R> asFunction(final FailableFunction<T, R, ?> function) {
return input -> apply(function, input);
}
|
Converts the given {@link FailableFunction} into a standard {@link Function}.
@param <T> the type of the input of the functions
@param <R> the type of the output of the functions
@param function a {code FailableFunction}
@return a standard {@link Function}
|
java
|
src/main/java/org/apache/commons/lang3/function/Failable.java
| 351
|
[
"function"
] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
intersect1d
|
def intersect1d(ar1, ar2, assume_unique=False):
"""
Returns the unique elements common to both arrays.
Masked values are considered equal one to the other.
The output is always a masked array.
See `numpy.intersect1d` for more details.
See Also
--------
numpy.intersect1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1])
>>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1])
>>> np.ma.intersect1d(x, y)
masked_array(data=[1, 3, --],
mask=[False, False, True],
fill_value=999999)
"""
if assume_unique:
aux = ma.concatenate((ar1, ar2))
else:
# Might be faster than unique( intersect1d( ar1, ar2 ) )?
aux = ma.concatenate((unique(ar1), unique(ar2)))
aux.sort()
return aux[:-1][aux[1:] == aux[:-1]]
|
Returns the unique elements common to both arrays.
Masked values are considered equal one to the other.
The output is always a masked array.
See `numpy.intersect1d` for more details.
See Also
--------
numpy.intersect1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1])
>>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1])
>>> np.ma.intersect1d(x, y)
masked_array(data=[1, 3, --],
mask=[False, False, True],
fill_value=999999)
|
python
|
numpy/ma/extras.py
| 1,317
|
[
"ar1",
"ar2",
"assume_unique"
] | false
| 3
| 6.64
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
initBsdSandbox
|
private void initBsdSandbox() {
RLimit limit = libc.newRLimit();
limit.rlim_cur(0);
limit.rlim_max(0);
// not a standard limit, means something different on linux, etc!
final int RLIMIT_NPROC = 7;
if (libc.setrlimit(RLIMIT_NPROC, limit) != 0) {
throw new UnsupportedOperationException("RLIMIT_NPROC unavailable: " + libc.strerror(libc.errno()));
}
logger.debug("BSD RLIMIT_NPROC initialization successful");
}
|
Installs exec system call filtering on MacOS.
<p>
Two different methods of filtering are used. Since MacOS is BSD based, process creation
is first restricted with {@code setrlimit(RLIMIT_NPROC)}.
<p>
Additionally, on Mac OS X Leopard or above, a custom {@code sandbox(7)} ("Seatbelt") profile is installed that
denies the following rules:
<ul>
<li>{@code process-fork}</li>
<li>{@code process-exec}</li>
</ul>
@see <a href="https://reverse.put.as/wp-content/uploads/2011/06/The-Apple-Sandbox-BHDC2011-Paper.pdf">
* https://reverse.put.as/wp-content/uploads/2011/06/The-Apple-Sandbox-BHDC2011-Paper.pdf</a>
|
java
|
libs/native/src/main/java/org/elasticsearch/nativeaccess/MacNativeAccess.java
| 130
|
[] |
void
| true
| 2
| 6.24
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
completeness_score
|
def completeness_score(labels_true, labels_pred):
"""Compute completeness metric of a cluster labeling given a ground truth.
A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`homogeneity_score` which will be different in
general.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters
----------
labels_true : array-like of shape (n_samples,)
Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,)
Cluster labels to evaluate.
Returns
-------
completeness : float
Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.
See Also
--------
homogeneity_score : Homogeneity metric of cluster labeling.
v_measure_score : V-Measure (NMI with arithmetic mean option).
References
----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
conditional entropy-based external cluster evaluation measure
<https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_
Examples
--------
Perfect labelings are complete::
>>> from sklearn.metrics.cluster import completeness_score
>>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Non-perfect labelings that assign all classes members to the same clusters
are still complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0]))
1.0
>>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1]))
0.999
If classes members are split across different clusters, the
assignment cannot be complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1]))
0.0
>>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3]))
0.0
"""
return homogeneity_completeness_v_measure(labels_true, labels_pred)[1]
|
Compute completeness metric of a cluster labeling given a ground truth.
A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`homogeneity_score` which will be different in
general.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters
----------
labels_true : array-like of shape (n_samples,)
Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,)
Cluster labels to evaluate.
Returns
-------
completeness : float
Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.
See Also
--------
homogeneity_score : Homogeneity metric of cluster labeling.
v_measure_score : V-Measure (NMI with arithmetic mean option).
References
----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
conditional entropy-based external cluster evaluation measure
<https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_
Examples
--------
Perfect labelings are complete::
>>> from sklearn.metrics.cluster import completeness_score
>>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Non-perfect labelings that assign all classes members to the same clusters
are still complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0]))
1.0
>>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1]))
0.999
If classes members are split across different clusters, the
assignment cannot be complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1]))
0.0
>>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3]))
0.0
|
python
|
sklearn/metrics/cluster/_supervised.py
| 649
|
[
"labels_true",
"labels_pred"
] | false
| 1
| 6
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
buildStatements
|
function buildStatements(): Statement[] {
if (operations) {
for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) {
writeOperation(operationIndex);
}
flushFinalLabel(operations.length);
}
else {
flushFinalLabel(0);
}
if (clauses) {
const labelExpression = factory.createPropertyAccessExpression(state, "label");
const switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
return [startOnNewLine(switchStatement)];
}
if (statements) {
return statements;
}
return [];
}
|
Builds the statements for the generator function body.
|
typescript
|
src/compiler/transformers/generators.ts
| 2,777
|
[] | true
| 6
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
value
|
public XContentBuilder value(Long value) throws IOException {
return (value == null) ? nullValue() : value(value.longValue());
}
|
@return the value of the "human readable" flag. When the value is equal to true,
some types of values are written in a format easier to read for a human.
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
| 611
|
[
"value"
] |
XContentBuilder
| true
| 2
| 6.96
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
seconds
|
public long seconds() {
return timeUnit.toSeconds(duration);
}
|
@return the number of {@link #timeUnit()} units this value contains
|
java
|
libs/core/src/main/java/org/elasticsearch/core/TimeValue.java
| 138
|
[] | true
| 1
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
chebsub
|
def chebsub(c1, c2):
"""
Subtract one Chebyshev series from another.
Returns the difference of two Chebyshev series `c1` - `c2`. The
sequences of coefficients are from lowest order term to highest, i.e.,
[1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Chebyshev series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Chebyshev series coefficients representing their difference.
See Also
--------
chebadd, chebmulx, chebmul, chebdiv, chebpow
Notes
-----
Unlike multiplication, division, etc., the difference of two Chebyshev
series is a Chebyshev series (without having to "reproject" the result
onto the basis set) so subtraction, just like that of "standard"
polynomials, is simply "component-wise."
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> C.chebsub(c1,c2)
array([-2., 0., 2.])
>>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
array([ 2., 0., -2.])
"""
return pu._sub(c1, c2)
|
Subtract one Chebyshev series from another.
Returns the difference of two Chebyshev series `c1` - `c2`. The
sequences of coefficients are from lowest order term to highest, i.e.,
[1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Chebyshev series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Chebyshev series coefficients representing their difference.
See Also
--------
chebadd, chebmulx, chebmul, chebdiv, chebpow
Notes
-----
Unlike multiplication, division, etc., the difference of two Chebyshev
series is a Chebyshev series (without having to "reproject" the result
onto the basis set) so subtraction, just like that of "standard"
polynomials, is simply "component-wise."
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> C.chebsub(c1,c2)
array([-2., 0., 2.])
>>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
array([ 2., 0., -2.])
|
python
|
numpy/polynomial/chebyshev.py
| 609
|
[
"c1",
"c2"
] | false
| 1
| 6.16
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
next
|
public String next(final int count, final char... chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, random());
}
return random(count, 0, chars.length, false, false, chars, random());
}
|
Creates a random string whose length is the number of characters specified.
<p>
Characters will be chosen from the set of characters specified.
</p>
@param count the length of random string to create.
@param chars the character array containing the set of characters to use, may be null.
@return the random string.
@throws IllegalArgumentException if {@code count} < 0.
@since 3.16.0
|
java
|
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
| 726
|
[
"count"
] |
String
| true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
_log_stream_to_parsed_log_stream
|
def _log_stream_to_parsed_log_stream(
log_stream: RawLogStream,
) -> ParsedLogStream:
"""
Turn a str log stream into a generator of parsed log lines.
:param log_stream: The stream to parse.
:return: A generator of parsed log lines.
"""
from airflow._shared.timezones.timezone import coerce_datetime
timestamp = None
next_timestamp = None
idx = 0
for line in log_stream:
if line:
try:
log = StructuredLogMessage.model_validate_json(line)
except ValidationError:
with suppress(Exception):
# If we can't parse the timestamp, don't attach one to the row
if isinstance(line, str):
next_timestamp = _parse_timestamp(line)
log = StructuredLogMessage(event=str(line), timestamp=next_timestamp)
if log.timestamp:
log.timestamp = coerce_datetime(log.timestamp)
timestamp = log.timestamp
yield timestamp, idx, log
idx += 1
|
Turn a str log stream into a generator of parsed log lines.
:param log_stream: The stream to parse.
:return: A generator of parsed log lines.
|
python
|
airflow-core/src/airflow/utils/log/file_task_handler.py
| 247
|
[
"log_stream"
] |
ParsedLogStream
| true
| 5
| 8.4
|
apache/airflow
| 43,597
|
sphinx
| false
|
connectionFailed
|
boolean connectionFailed(Node node);
|
Check if the connection of the node has failed, based on the connection state. Such connection failure are
usually transient and can be resumed in the next {@link #ready(org.apache.kafka.common.Node, long)}
call, but there are cases where transient failures needs to be caught and re-acted upon.
@param node the node to check
@return true iff the connection has failed and the node is disconnected
|
java
|
clients/src/main/java/org/apache/kafka/clients/KafkaClient.java
| 79
|
[
"node"
] | true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
read
|
def read(
self,
task_instance: TaskInstance | TaskInstanceHistory,
try_number: int | None = None,
metadata: LogMetadata | None = None,
) -> tuple[LogHandlerOutputStream, LogMetadata]:
"""
Read logs of given task instance from local machine.
:param task_instance: task instance object
:param try_number: task instance try_number to read logs from. If None
it returns the log of task_instance.try_number
:param metadata: log metadata, can be used for steaming log reading and auto-tailing.
:return: a list of listed tuples which order log string by host
"""
if try_number is None:
try_number = task_instance.try_number
if try_number == 0 and task_instance.state in (
TaskInstanceState.SKIPPED,
TaskInstanceState.UPSTREAM_FAILED,
):
logs = [StructuredLogMessage(event="Task was skipped, no logs available.")]
return chain(logs), {"end_of_log": True}
if try_number is None or try_number < 1:
logs = [
StructuredLogMessage( # type: ignore[call-arg]
level="error", event=f"Error fetching the logs. Try number {try_number} is invalid."
)
]
return chain(logs), {"end_of_log": True}
# compatibility for es_task_handler and os_task_handler
read_result = self._read(task_instance, try_number, metadata)
out_stream, metadata = read_result
# If the out_stream is None or empty, return the read result
if not out_stream:
out_stream = cast("Generator[StructuredLogMessage, None, None]", out_stream)
return out_stream, metadata
if _is_logs_stream_like(out_stream):
out_stream = cast("Generator[StructuredLogMessage, None, None]", out_stream)
return out_stream, metadata
if isinstance(out_stream, list) and isinstance(out_stream[0], StructuredLogMessage):
out_stream = cast("list[StructuredLogMessage]", out_stream)
return (log for log in out_stream), metadata
if isinstance(out_stream, list) and isinstance(out_stream[0], str):
# If the out_stream is a list of strings, convert it to a generator
out_stream = cast("list[str]", out_stream)
raw_stream = _stream_lines_by_chunk(io.StringIO("".join(out_stream)))
out_stream = (log for _, _, log in _log_stream_to_parsed_log_stream(raw_stream))
return out_stream, metadata
if isinstance(out_stream, str):
# If the out_stream is a string, convert it to a generator
raw_stream = _stream_lines_by_chunk(io.StringIO(out_stream))
out_stream = (log for _, _, log in _log_stream_to_parsed_log_stream(raw_stream))
return out_stream, metadata
raise TypeError(
"Invalid log stream type. Expected a generator of StructuredLogMessage, list of StructuredLogMessage, list of str or str."
f" Got {type(out_stream).__name__} instead."
f" Content type: {type(out_stream[0]).__name__ if isinstance(out_stream, (list, tuple)) and out_stream else 'empty'}"
)
|
Read logs of given task instance from local machine.
:param task_instance: task instance object
:param try_number: task instance try_number to read logs from. If None
it returns the log of task_instance.try_number
:param metadata: log metadata, can be used for steaming log reading and auto-tailing.
:return: a list of listed tuples which order log string by host
|
python
|
airflow-core/src/airflow/utils/log/file_task_handler.py
| 728
|
[
"self",
"task_instance",
"try_number",
"metadata"
] |
tuple[LogHandlerOutputStream, LogMetadata]
| true
| 15
| 8.16
|
apache/airflow
| 43,597
|
sphinx
| false
|
drainReferenceQueues
|
@GuardedBy("this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
|
Drain the key and value reference queues, cleaning up internal entries containing garbage
collected keys or values.
|
java
|
android/guava/src/com/google/common/cache/LocalCache.java
| 2,379
|
[] |
void
| true
| 3
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
notNull
|
public static <T> T notNull(final T object, final String message, final Object... values) {
return Objects.requireNonNull(object, toSupplier(message, values));
}
|
Validate that the specified argument is not {@code null};
otherwise throwing an exception with the specified message.
<pre>Validate.notNull(myObject, "The object must not be null");</pre>
@param <T> the object type.
@param object the object to check.
@param message the {@link String#format(String, Object...)} exception message if invalid, not null.
@param values the optional values for the formatted exception message.
@return the validated object (never {@code null} for method chaining).
@throws NullPointerException if the object is {@code null}.
@see Objects#requireNonNull(Object)
|
java
|
src/main/java/org/apache/commons/lang3/Validate.java
| 1,060
|
[
"object",
"message"
] |
T
| true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
add
|
public boolean add() {
if (root == NIL) {
root = nodeAllocator.newNode();
copy(root);
fixAggregates(root);
return true;
} else {
int node = root;
assert parent(root) == NIL;
int parent;
int cmp;
do {
cmp = compare(node);
if (cmp < 0) {
parent = node;
node = left(node);
} else if (cmp > 0) {
parent = node;
node = right(node);
} else {
merge(node);
return false;
}
} while (node != NIL);
node = nodeAllocator.newNode();
if (node >= capacity()) {
resize(oversize(node + 1));
}
copy(node);
parent(node, parent);
if (cmp < 0) {
left(parent, node);
} else {
right(parent, node);
}
rebalance(node);
return true;
}
}
|
Add current data to the tree and return <code>true</code> if a new node was added
to the tree or <code>false</code> if the node was merged into an existing node.
|
java
|
libs/tdigest/src/main/java/org/elasticsearch/tdigest/IntAVLTree.java
| 243
|
[] | true
| 6
| 7.04
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
shapes_symbolic
|
def shapes_symbolic(self) -> tuple[tuple[Any, ...], ...]:
"""
Get the symbolic shapes of all input nodes.
Returns:
A tuple of shape tuples for each input node
"""
return tuple(node.get_size() for node in self._input_nodes)
|
Get the symbolic shapes of all input nodes.
Returns:
A tuple of shape tuples for each input node
|
python
|
torch/_inductor/kernel_inputs.py
| 108
|
[
"self"
] |
tuple[tuple[Any, ...], ...]
| true
| 1
| 6.56
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
handleShareFetchFailure
|
private void handleShareFetchFailure(Node fetchTarget,
ShareFetchRequestData requestData,
Throwable error) {
try {
log.debug("Completed ShareFetch request from node {} unsuccessfully {}", fetchTarget.id(), Errors.forException(error));
final ShareSessionHandler handler = sessionHandler(fetchTarget.id());
if (handler != null) {
handler.handleError(error);
}
requestData.topics().forEach(topic -> topic.partitions().forEach(partition -> {
TopicIdPartition tip = lookupTopicId(topic.topicId(), partition.partitionIndex());
if (tip == null) {
return;
}
Map<TopicIdPartition, Acknowledgements> nodeAcknowledgementsInFlight = fetchAcknowledgementsInFlight.get(fetchTarget.id());
if (nodeAcknowledgementsInFlight != null) {
Acknowledgements acks = nodeAcknowledgementsInFlight.remove(tip);
if (acks != null) {
metricsManager.recordFailedAcknowledgements(acks.size());
if (error instanceof KafkaException) {
acks.complete((KafkaException) error);
} else {
acks.complete(Errors.UNKNOWN_SERVER_ERROR.exception());
}
Map<TopicIdPartition, Acknowledgements> acksMap = Map.of(tip, acks);
maybeSendShareAcknowledgementEvent(acksMap, requestData.isRenewAck(), Optional.empty());
}
}
}));
} finally {
log.debug("Removing pending request for node {} - failed", fetchTarget.id());
if (isShareAcquireModeRecordLimit()) {
fetchRecordsNodeId.compareAndSet(fetchTarget.id(), -1);
}
nodesWithPendingRequests.remove(fetchTarget.id());
}
}
|
The method checks whether the leader for a topicIdPartition has changed.
@param nodeId The previous leader for the partition.
@param topicIdPartition The TopicIdPartition to check.
@return Returns true if leader information is available and leader has changed.
If the leader information is not available or if the leader has not changed, it returns false.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumeRequestManager.java
| 894
|
[
"fetchTarget",
"requestData",
"error"
] |
void
| true
| 7
| 7.92
|
apache/kafka
| 31,560
|
javadoc
| false
|
unmodifiableNavigableMap
|
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) {
checkNotNull(map);
if (map instanceof UnmodifiableNavigableMap) {
@SuppressWarnings("unchecked") // covariant
NavigableMap<K, V> result = (NavigableMap<K, V>) map;
return result;
} else {
return new UnmodifiableNavigableMap<>(map);
}
}
|
Returns an unmodifiable view of the specified navigable map. Query operations on the returned
map read through to the specified map, and attempts to modify the returned map, whether direct
or via its views, result in an {@code UnsupportedOperationException}.
<p>The returned navigable map will be serializable if the specified navigable map is
serializable.
<p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K,
V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code
comparator()} method might return a {@code Comparator<? extends K>}, which works only on a
particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which
must work on any type of {@code K}.
@param map the navigable map for which an unmodifiable view is to be returned
@return an unmodifiable view of the specified navigable map
@since 12.0
|
java
|
android/guava/src/com/google/common/collect/Maps.java
| 3,293
|
[
"map"
] | true
| 2
| 7.92
|
google/guava
| 51,352
|
javadoc
| false
|
|
loadBeanDefinitions
|
public int loadBeanDefinitions(InputSource inputSource, @Nullable String resourceDescription)
throws BeanDefinitionStoreException {
return doLoadBeanDefinitions(inputSource, new DescriptiveResource(resourceDescription));
}
|
Load bean definitions from the specified XML file.
@param inputSource the SAX InputSource to read from
@param resourceDescription a description of the resource
(can be {@code null} or empty)
@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/xml/XmlBeanDefinitionReader.java
| 377
|
[
"inputSource",
"resourceDescription"
] | true
| 1
| 6.32
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
hasNext
|
@Override
public boolean hasNext() {
checkTokenized();
return tokenPos < tokens.length;
}
|
Checks whether there are any more tokens.
@return true if there are more tokens.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
| 567
|
[] | true
| 1
| 6.88
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getDefaultValueResolver
|
protected Function<@Nullable String, @Nullable String> getDefaultValueResolver(Environment environment) {
String defaultLogCorrelationPattern = getDefaultLogCorrelationPattern();
return (name) -> {
String applicationPropertyName = LoggingSystemProperty.CORRELATION_PATTERN.getApplicationPropertyName();
Assert.state(applicationPropertyName != null, "applicationPropertyName must not be null");
if (StringUtils.hasLength(defaultLogCorrelationPattern) && applicationPropertyName.equals(name)
&& environment.getProperty(LoggingSystem.EXPECT_CORRELATION_ID_PROPERTY, Boolean.class, false)) {
return defaultLogCorrelationPattern;
}
return null;
};
}
|
Return the default value resolver to use when resolving system properties.
@param environment the environment
@return the default value resolver
@since 3.2.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java
| 192
|
[
"environment"
] | true
| 4
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
count_nonzero
|
def count_nonzero(X, axis=None, sample_weight=None):
"""A variant of X.getnnz() with extension to weighting on axis 0.
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : sparse matrix of shape (n_samples, n_labels)
Input data. It should be of CSR format.
axis : {0, 1}, default=None
The axis on which the data is aggregated.
sample_weight : array-like of shape (n_samples,), default=None
Weight for each row of X.
Returns
-------
nnz : int, float, ndarray of shape (n_samples,) or ndarray of shape (n_features,)
Number of non-zero values in the array along a given axis. Otherwise,
the total number of non-zero values in the array is returned.
"""
if axis == -1:
axis = 1
elif axis == -2:
axis = 0
elif X.format != "csr":
raise TypeError("Expected CSR sparse format, got {0}".format(X.format))
# We rely here on the fact that np.diff(Y.indptr) for a CSR
# will return the number of nonzero entries in each row.
# A bincount over Y.indices will return the number of nonzeros
# in each column. See ``csr_matrix.getnnz`` in scipy >= 0.14.
if axis is None:
if sample_weight is None:
return X.nnz
else:
return np.dot(np.diff(X.indptr), sample_weight)
elif axis == 1:
out = np.diff(X.indptr)
if sample_weight is None:
# astype here is for consistency with axis=0 dtype
return out.astype("intp")
return out * sample_weight
elif axis == 0:
if sample_weight is None:
return np.bincount(X.indices, minlength=X.shape[1])
else:
weights = np.repeat(sample_weight, np.diff(X.indptr))
return np.bincount(X.indices, minlength=X.shape[1], weights=weights)
else:
raise ValueError("Unsupported axis: {0}".format(axis))
|
A variant of X.getnnz() with extension to weighting on axis 0.
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : sparse matrix of shape (n_samples, n_labels)
Input data. It should be of CSR format.
axis : {0, 1}, default=None
The axis on which the data is aggregated.
sample_weight : array-like of shape (n_samples,), default=None
Weight for each row of X.
Returns
-------
nnz : int, float, ndarray of shape (n_samples,) or ndarray of shape (n_features,)
Number of non-zero values in the array along a given axis. Otherwise,
the total number of non-zero values in the array is returned.
|
python
|
sklearn/utils/sparsefuncs.py
| 605
|
[
"X",
"axis",
"sample_weight"
] | false
| 13
| 6.08
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
future
|
CompletableFuture<T> future();
|
Returns the {@link CompletableFuture future} associated with this event. Any event will have some related
logic that is executed on its behalf. The event can complete in one of the following ways:
<ul>
<li>
Success: when the logic for the event completes successfully, the data generated by that event
(if applicable) is passed to {@link CompletableFuture#complete(Object)}. In the case where the generic
bound type is specified as {@link Void}, {@code null} is provided.</li>
<li>
Error: when the event logic generates an error, the error is passed to
{@link CompletableFuture#completeExceptionally(Throwable)}.
</li>
<li>
Timeout: when the time spent executing the event logic exceeds the {@link #deadlineMs() deadline}, an
instance of {@link TimeoutException} should be created and passed to
{@link CompletableFuture#completeExceptionally(Throwable)}. This also occurs when an event remains
incomplete when the consumer closes.
</li>
</ul>
@return Future on which the caller may block or query for completion
@see CompletableEventReaper
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEvent.java
| 63
|
[] | true
| 1
| 6
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
sanitizeNotificationText
|
function sanitizeNotificationText(text: string): string {
return text.replace(/`/g, '\''); // convert backticks to single quotes
}
|
Attempts to open a window and returns whether it succeeded. This technique is
not appropriate in certain contexts, like for example when the JS context is
executing inside a sandboxed iframe. If it is not necessary to know if the
browser blocked the new window, use {@link windowOpenNoOpener}.
See https://github.com/microsoft/monaco-editor/issues/601
See https://github.com/microsoft/monaco-editor/issues/2474
See https://mathiasbynens.github.io/rel-noopener/
@param url the url to open
@param noOpener whether or not to set the {@link window.opener} to null. You should leave the default
(true) unless you trust the url that is being opened.
@returns boolean indicating if the {@link window.open} call succeeded
|
typescript
|
src/vs/base/browser/dom.ts
| 1,599
|
[
"text"
] | true
| 1
| 6.32
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
codes
|
def codes(self) -> np.ndarray:
"""
The category codes of this categorical index.
Codes are an array of integers which are the positions of the actual
values in the categories array.
There is no setter, use the other categorical methods and the normal item
setter to change values in the categorical.
Returns
-------
ndarray[int]
A non-writable view of the ``codes`` array.
See Also
--------
Categorical.from_codes : Make a Categorical from codes.
CategoricalIndex : An Index with an underlying ``Categorical``.
Examples
--------
For :class:`pandas.Categorical`:
>>> cat = pd.Categorical(["a", "b"], ordered=True)
>>> cat.codes
array([0, 1], dtype=int8)
For :class:`pandas.CategoricalIndex`:
>>> ci = pd.CategoricalIndex(["a", "b", "c", "a", "b", "c"])
>>> ci.codes
array([0, 1, 2, 0, 1, 2], dtype=int8)
>>> ci = pd.CategoricalIndex(["a", "c"], categories=["c", "b", "a"])
>>> ci.codes
array([2, 0], dtype=int8)
"""
v = self._codes.view()
v.flags.writeable = False
return v
|
The category codes of this categorical index.
Codes are an array of integers which are the positions of the actual
values in the categories array.
There is no setter, use the other categorical methods and the normal item
setter to change values in the categorical.
Returns
-------
ndarray[int]
A non-writable view of the ``codes`` array.
See Also
--------
Categorical.from_codes : Make a Categorical from codes.
CategoricalIndex : An Index with an underlying ``Categorical``.
Examples
--------
For :class:`pandas.Categorical`:
>>> cat = pd.Categorical(["a", "b"], ordered=True)
>>> cat.codes
array([0, 1], dtype=int8)
For :class:`pandas.CategoricalIndex`:
>>> ci = pd.CategoricalIndex(["a", "b", "c", "a", "b", "c"])
>>> ci.codes
array([0, 1, 2, 0, 1, 2], dtype=int8)
>>> ci = pd.CategoricalIndex(["a", "c"], categories=["c", "b", "a"])
>>> ci.codes
array([2, 0], dtype=int8)
|
python
|
pandas/core/arrays/categorical.py
| 897
|
[
"self"
] |
np.ndarray
| true
| 1
| 6.64
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
toEnrichedRst
|
public String toEnrichedRst() {
StringBuilder b = new StringBuilder();
String lastKeyGroupName = "";
for (ConfigKey key : sortedConfigs()) {
if (key.internalConfig) {
continue;
}
if (key.group != null) {
if (!lastKeyGroupName.equalsIgnoreCase(key.group)) {
b.append(key.group).append("\n");
char[] underLine = new char[key.group.length()];
Arrays.fill(underLine, '^');
b.append(new String(underLine)).append("\n\n");
}
lastKeyGroupName = key.group;
}
getConfigKeyRst(key, b);
if (key.dependents != null && key.dependents.size() > 0) {
int j = 0;
b.append(" * Dependents: ");
for (String dependent : key.dependents) {
b.append("``");
b.append(dependent);
if (++j == key.dependents.size())
b.append("``");
else
b.append("``, ");
}
b.append("\n");
}
b.append("\n");
}
return b.toString();
}
|
Configs with new metadata (group, orderInGroup, dependents) formatted with reStructuredText, suitable for embedding in Sphinx
documentation.
|
java
|
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
| 1,514
|
[] |
String
| true
| 7
| 6.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
createCacheControl
|
private CacheControl createCacheControl() {
if (Boolean.TRUE.equals(this.noStore)) {
return CacheControl.noStore();
}
if (Boolean.TRUE.equals(this.noCache)) {
return CacheControl.noCache();
}
if (this.maxAge != null) {
return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS);
}
return CacheControl.empty();
}
|
Maximum time the response should be cached by shared caches, in seconds
if no duration suffix is not specified.
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java
| 599
|
[] |
CacheControl
| true
| 4
| 6.88
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
size
|
public int size() {
checkTokenized();
return tokens.length;
}
|
Gets the number of tokens found in the String.
@return the number of matched tokens.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
| 1,051
|
[] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
lchmod
|
function lchmod(path, mode, callback) {
validateFunction(callback, 'cb');
mode = parseFileMode(mode, 'mode');
fs.open(path, O_WRONLY | O_SYMLINK, (err, fd) => {
if (err) {
callback(err);
return;
}
// Prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
fs.fchmod(fd, mode, (err) => {
fs.close(fd, (err2) => {
callback(aggregateTwoErrors(err2, err));
});
});
});
}
|
Changes the permissions on a symbolic link.
@param {string | Buffer | URL} path
@param {number} mode
@param {(err?: Error) => any} callback
@returns {void}
|
javascript
|
lib/fs.js
| 1,966
|
[
"path",
"mode",
"callback"
] | false
| 2
| 6.4
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
withAdditionalProfiles
|
public Augmented withAdditionalProfiles(String... profiles) {
Set<String> merged = new LinkedHashSet<>(this.additionalProfiles);
merged.addAll(Arrays.asList(profiles));
return new Augmented(this.main, this.sources, merged);
}
|
Return a new {@link SpringApplication.Augmented} instance with additional
profiles that should be applied when the application runs.
@param profiles the profiles that should be applied
@return a new {@link SpringApplication.Augmented} instance
@since 3.4.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
| 1,523
|
[] |
Augmented
| true
| 1
| 6.4
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
addToLocal
|
private long addToLocal(List<DataBlock> parts, ZipCentralDirectoryFileHeaderRecord centralRecord,
ZipLocalFileHeaderRecord originalRecord, ZipDataDescriptorRecord dataDescriptorRecord, DataBlock name,
DataBlock content) throws IOException {
ZipLocalFileHeaderRecord record = originalRecord.withFileNameLength((short) (name.size() & 0xFFFF));
long originalRecordPos = Integer.toUnsignedLong(centralRecord.offsetToLocalHeader());
int extraFieldLength = Short.toUnsignedInt(originalRecord.extraFieldLength());
parts.add(new ByteArrayDataBlock(record.asByteArray()));
parts.add(name);
if (extraFieldLength > 0) {
parts.add(new DataPart(originalRecordPos + originalRecord.size() - extraFieldLength, extraFieldLength));
}
parts.add(content);
if (dataDescriptorRecord != null) {
parts.add(new ByteArrayDataBlock(dataDescriptorRecord.asByteArray()));
}
return record.size() + content.size() + ((dataDescriptorRecord != null) ? dataDescriptorRecord.size() : 0);
}
|
Create a new {@link VirtualZipDataBlock} for the given entries.
@param data the source zip data
@param nameOffsetLookups the name offsets to apply
@param centralRecords the records that should be copied to the virtual zip
@param centralRecordPositions the record positions in the data block.
@throws IOException on I/O error
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/VirtualZipDataBlock.java
| 89
|
[
"parts",
"centralRecord",
"originalRecord",
"dataDescriptorRecord",
"name",
"content"
] | true
| 4
| 6.56
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
generate
|
def generate( # type: ignore[override]
self,
name: str,
input_nodes: list[Buffer],
layout: Layout,
make_fx_graph: Callable[..., Any],
description: str = "",
input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None,
**kwargs: Any,
) -> SubgraphChoiceCaller:
"""
Generate a SubgraphChoiceCaller instance for autotuning.
Args:
name: The name for this subgraph choice
input_nodes: List of input nodes to the subgraph
layout: Memory layout information for the output
make_fx_graph: Callable that creates the FX graph for this subgraph
description: Optional description of this choice
input_gen_fns: Optional dict mapping input indices to tensor generators
**kwargs: Additional keyword arguments
Returns:
SubgraphChoiceCaller: A callable object that can be used for autotuning
"""
return SubgraphChoiceCaller(
name=f"{name}_{next(SubgraphTemplate.index_counter)}",
input_nodes=input_nodes,
layout=layout,
description=description,
make_fx_graph=make_fx_graph,
input_gen_fns=input_gen_fns,
)
|
Generate a SubgraphChoiceCaller instance for autotuning.
Args:
name: The name for this subgraph choice
input_nodes: List of input nodes to the subgraph
layout: Memory layout information for the output
make_fx_graph: Callable that creates the FX graph for this subgraph
description: Optional description of this choice
input_gen_fns: Optional dict mapping input indices to tensor generators
**kwargs: Additional keyword arguments
Returns:
SubgraphChoiceCaller: A callable object that can be used for autotuning
|
python
|
torch/_inductor/codegen/subgraph.py
| 247
|
[
"self",
"name",
"input_nodes",
"layout",
"make_fx_graph",
"description",
"input_gen_fns"
] |
SubgraphChoiceCaller
| true
| 1
| 6.08
|
pytorch/pytorch
| 96,034
|
google
| false
|
hashCode
|
@Override
public int hashCode() {
int result = 31;
result = 31 * result + Long.hashCode(producerId);
result = 31 * result + (int) epoch;
return result;
}
|
Returns a serialized string representation of this transaction state.
The format is "producerId:epoch" for an initialized state, or an empty string
for an uninitialized state (where producerId and epoch are both -1).
@return a serialized string representation
|
java
|
clients/src/main/java/org/apache/kafka/clients/producer/PreparedTxnState.java
| 121
|
[] | true
| 1
| 6.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
policyEntitlements
|
ModuleEntitlements policyEntitlements(
String componentName,
Collection<Path> componentPaths,
String moduleName,
List<Entitlement> entitlements
) {
FilesEntitlement filesEntitlement = FilesEntitlement.EMPTY;
for (Entitlement entitlement : entitlements) {
if (entitlement instanceof FilesEntitlement) {
filesEntitlement = (FilesEntitlement) entitlement;
}
}
return new ModuleEntitlements(
componentName,
moduleName,
entitlements.stream().collect(groupingBy(Entitlement::getClass)),
FileAccessTree.of(componentName, moduleName, filesEntitlement, pathLookup, componentPaths, exclusivePaths, forbiddenPaths)
);
}
|
This class contains all the entitlements by type, plus the {@link FileAccessTree} for the special case of filesystem entitlements.
<p>
We use layers when computing {@link ModuleEntitlements}; first, we check whether the module we are building it for is in the
server layer ({@link PolicyManager#SERVER_LAYER_MODULES}) (*).
If it is, we use the server policy, using the same caller class module name as the scope, and read the entitlements for that scope.
Otherwise, we use the {@code PluginResolver} to identify the correct plugin layer and find the policy for it (if any).
If the plugin is modular, we again use the same caller class module name as the scope, and read the entitlements for that scope.
If it's not, we use the single {@code ALL-UNNAMED} scope – in this case there is one scope and all entitlements apply
to all the plugin code.
</p>
<p>
(*) implementation detail: this is currently done in an indirect way: we know the module is not in the system layer
(otherwise the check would have been already trivially allowed), so we just check that the module is named, and it belongs to the
boot {@link ModuleLayer}. We might want to change this in the future to make it more consistent/easier to maintain.
</p>
@param componentName the plugin name or else one of the special component names like "(server)".
|
java
|
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/PolicyManager.java
| 163
|
[
"componentName",
"componentPaths",
"moduleName",
"entitlements"
] |
ModuleEntitlements
| true
| 2
| 6.72
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.