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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shortValue
|
@Override
public short shortValue() {
return value;
}
|
Returns the value of this MutableShort as a short.
@return the numeric value represented by this object after conversion to type short.
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableShort.java
| 342
|
[] | true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
isTrue
|
public static void isTrue(final boolean expression, final String message, final double value) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
}
}
|
Validate that the argument condition is {@code true}; otherwise
throwing an exception with the specified message. This method is useful when
validating according to an arbitrary boolean expression, such as validating a
primitive number or using your own custom validation expression.
<pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
<p>For performance reasons, the double value is passed as a separate parameter and
appended to the exception message only in the case of an error.</p>
@param expression the boolean expression to check.
@param message the {@link String#format(String, Object...)} exception message if invalid, not null.
@param value the value to append to the message when invalid.
@throws IllegalArgumentException if expression is {@code false}.
@see #isTrue(boolean)
@see #isTrue(boolean, String, long)
@see #isTrue(boolean, String, Object...)
@see #isTrue(boolean, Supplier)
|
java
|
src/main/java/org/apache/commons/lang3/Validate.java
| 522
|
[
"expression",
"message",
"value"
] |
void
| true
| 2
| 6.4
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
longToIntArray
|
public static int[] longToIntArray(final long src, final int srcPos, final int[] dst, final int dstPos, final int nInts) {
if (0 == nInts) {
return dst;
}
if ((nInts - 1) * Integer.SIZE + srcPos >= Long.SIZE) {
throw new IllegalArgumentException("(nInts - 1) * 32 + srcPos >= 64");
}
for (int i = 0; i < nInts; i++) {
final int shift = i * Integer.SIZE + srcPos;
dst[dstPos + i] = (int) (0xffffffff & src >> shift);
}
return dst;
}
|
Converts a long into an array of int using the default (little-endian, LSB0) byte and bit ordering.
@param src the long to convert.
@param srcPos the position in {@code src}, in bits, from where to start the conversion.
@param dst the destination array.
@param dstPos the position in {@code dst} where to copy the result.
@param nInts the number of ints to copy to {@code dst}, must be smaller or equal to the width of the input (from srcPos to MSB).
@return {@code dst}.
@throws NullPointerException if {@code dst} is {@code null} and {@code nInts > 0}.
@throws IllegalArgumentException if {@code (nInts - 1) * 32 + srcPos >= 64}.
@throws ArrayIndexOutOfBoundsException if {@code dstPos + nInts > dst.length}.
|
java
|
src/main/java/org/apache/commons/lang3/Conversion.java
| 1,172
|
[
"src",
"srcPos",
"dst",
"dstPos",
"nInts"
] | true
| 4
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
_get_secret
|
def _get_secret(self, path_prefix: str, secret_id: str, lookup_pattern: str | None) -> str | None:
"""
Get secret value from Parameter Store.
:param path_prefix: Prefix for the Path to get Secret
:param secret_id: Secret Key
:param lookup_pattern: If provided, `secret_id` must match this pattern to look up the secret in
Systems Manager
"""
if lookup_pattern and not re.match(lookup_pattern, secret_id, re.IGNORECASE):
return None
ssm_path = self.build_path(path_prefix, secret_id)
ssm_path = self._ensure_leading_slash(ssm_path)
try:
response = self.client.get_parameter(Name=ssm_path, WithDecryption=True)
return response["Parameter"]["Value"]
except self.client.exceptions.ParameterNotFound:
self.log.debug("Parameter %s not found.", ssm_path)
return None
|
Get secret value from Parameter Store.
:param path_prefix: Prefix for the Path to get Secret
:param secret_id: Secret Key
:param lookup_pattern: If provided, `secret_id` must match this pattern to look up the secret in
Systems Manager
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/secrets/systems_manager.py
| 171
|
[
"self",
"path_prefix",
"secret_id",
"lookup_pattern"
] |
str | None
| true
| 3
| 6.56
|
apache/airflow
| 43,597
|
sphinx
| false
|
opj_int_min
|
static INLINE OPJ_INT32 opj_int_min(OPJ_INT32 a, OPJ_INT32 b)
{
return a < b ? a : b;
}
|
Get the minimum of two integers
@return Returns a if a < b else b
|
cpp
|
3rdparty/openjpeg/openjp2/opj_intmath.h
| 56
|
[
"a",
"b"
] | true
| 2
| 6.48
|
opencv/opencv
| 85,374
|
doxygen
| false
|
|
inner
|
def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R:
"""Attempt to replay from cache, or record on cache miss.
Args:
*args: Positional arguments to pass to the function.
**kwargs: Keyword arguments to pass to the function.
Returns:
The result from cache (if hit) or from executing the function (if miss).
"""
# Try to replay first
try:
return replay_fn(*args, **kwargs)
except KeyError:
# Cache miss - record the result
return record_fn(*args, **kwargs)
|
Attempt to replay from cache, or record on cache miss.
Args:
*args: Positional arguments to pass to the function.
**kwargs: Keyword arguments to pass to the function.
Returns:
The result from cache (if hit) or from executing the function (if miss).
|
python
|
torch/_inductor/runtime/caching/interfaces.py
| 212
|
[] |
_R
| true
| 1
| 7.04
|
pytorch/pytorch
| 96,034
|
google
| false
|
svdvals
|
def svdvals(x, /):
"""
Returns the singular values of a matrix (or a stack of matrices) ``x``.
When x is a stack of matrices, the function will compute the singular
values for each matrix in the stack.
This function is Array API compatible.
Calling ``np.svdvals(x)`` to get singular values is the same as
``np.svd(x, compute_uv=False, hermitian=False)``.
Parameters
----------
x : (..., M, N) array_like
Input array having shape (..., M, N) and whose last two
dimensions form matrices on which to perform singular value
decomposition. Should have a floating-point data type.
Returns
-------
out : ndarray
An array with shape (..., K) that contains the vector(s)
of singular values of length K, where K = min(M, N).
See Also
--------
scipy.linalg.svdvals : Compute singular values of a matrix.
Examples
--------
>>> np.linalg.svdvals([[1, 2, 3, 4, 5],
... [1, 4, 9, 16, 25],
... [1, 8, 27, 64, 125]])
array([146.68862757, 5.57510612, 0.60393245])
Determine the rank of a matrix using singular values:
>>> s = np.linalg.svdvals([[1, 2, 3],
... [2, 4, 6],
... [-1, 1, -1]]); s
array([8.38434191e+00, 1.64402274e+00, 2.31534378e-16])
>>> np.count_nonzero(s > 1e-10) # Matrix of rank 2
2
"""
return svd(x, compute_uv=False, hermitian=False)
|
Returns the singular values of a matrix (or a stack of matrices) ``x``.
When x is a stack of matrices, the function will compute the singular
values for each matrix in the stack.
This function is Array API compatible.
Calling ``np.svdvals(x)`` to get singular values is the same as
``np.svd(x, compute_uv=False, hermitian=False)``.
Parameters
----------
x : (..., M, N) array_like
Input array having shape (..., M, N) and whose last two
dimensions form matrices on which to perform singular value
decomposition. Should have a floating-point data type.
Returns
-------
out : ndarray
An array with shape (..., K) that contains the vector(s)
of singular values of length K, where K = min(M, N).
See Also
--------
scipy.linalg.svdvals : Compute singular values of a matrix.
Examples
--------
>>> np.linalg.svdvals([[1, 2, 3, 4, 5],
... [1, 4, 9, 16, 25],
... [1, 8, 27, 64, 125]])
array([146.68862757, 5.57510612, 0.60393245])
Determine the rank of a matrix using singular values:
>>> s = np.linalg.svdvals([[1, 2, 3],
... [2, 4, 6],
... [-1, 1, -1]]); s
array([8.38434191e+00, 1.64402274e+00, 2.31534378e-16])
>>> np.count_nonzero(s > 1e-10) # Matrix of rank 2
2
|
python
|
numpy/linalg/_linalg.py
| 1,861
|
[
"x"
] | false
| 1
| 6.48
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
apply
|
R apply(double input) throws E;
|
Applies this function.
@param input the input for the function
@return the result of the function
@throws E Thrown when the function fails.
|
java
|
src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java
| 55
|
[
"input"
] |
R
| true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
shift
|
def shift(self, periods: int = 1, fill_value: object = None) -> ExtensionArray:
"""
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shifting backwards.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
The default is ``self.dtype.na_value``.
Returns
-------
ExtensionArray
Shifted.
See Also
--------
api.extensions.ExtensionArray.transpose : Return a transposed view on
this array.
api.extensions.ExtensionArray.factorize : Encode the extension array as an
enumerated type.
Notes
-----
If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
returned.
If ``periods > len(self)``, then an array of size
len(self) is returned, with all values filled with
``self.dtype.na_value``.
For 2-dimensional ExtensionArrays, we are always shifting along axis=0.
Examples
--------
>>> arr = pd.array([1, 2, 3])
>>> arr.shift(2)
<IntegerArray>
[<NA>, <NA>, 1]
Length: 3, dtype: Int64
"""
# Note: this implementation assumes that `self.dtype.na_value` can be
# stored in an instance of your ExtensionArray with `self.dtype`.
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
fill_value = self.dtype.na_value
empty = self._from_sequence(
[fill_value] * min(abs(periods), len(self)), dtype=self.dtype
)
if periods > 0:
a = empty
b = self[:-periods]
else:
a = self[abs(periods) :]
b = empty
return self._concat_same_type([a, b])
|
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shifting backwards.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
The default is ``self.dtype.na_value``.
Returns
-------
ExtensionArray
Shifted.
See Also
--------
api.extensions.ExtensionArray.transpose : Return a transposed view on
this array.
api.extensions.ExtensionArray.factorize : Encode the extension array as an
enumerated type.
Notes
-----
If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
returned.
If ``periods > len(self)``, then an array of size
len(self) is returned, with all values filled with
``self.dtype.na_value``.
For 2-dimensional ExtensionArrays, we are always shifting along axis=0.
Examples
--------
>>> arr = pd.array([1, 2, 3])
>>> arr.shift(2)
<IntegerArray>
[<NA>, <NA>, 1]
Length: 3, dtype: Int64
|
python
|
pandas/core/arrays/base.py
| 1,368
|
[
"self",
"periods",
"fill_value"
] |
ExtensionArray
| true
| 6
| 7.92
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
_finalize_template_configs
|
def _finalize_template_configs(
self,
template_choices: dict[str, Generator[KernelTemplateChoice, None, None]],
kernel_inputs: KernelInputs,
templates: list[Union[KernelTemplate, ExternKernelChoice]],
op_name: str,
kwarg_overrides: Optional[dict[str, dict[str, Any]]] = None,
) -> list[KernelTemplateChoice]:
"""Check lookup table for hits, use those if found, otherwise fall back to parent."""
# 1. Collect template src_hashes for validation
template_uids = [template.uid for template in templates]
template_hash_map = {}
for template in templates:
src_hash = getattr(template, "src_hash", None)
template_hash_map[template.uid] = src_hash
log.debug(
"Choices: attempting lookup for %s with %d templates",
op_name,
len(template_uids),
)
# 2. Single batch lookup for all templates
lookup_results = self.lookup_template_configs(
kernel_inputs, op_name, template_uids, template_hash_map
)
# 3. Early exit if no lookup table or no matches
if not lookup_results: # Empty dict
log.info("LookupChoices: lookup miss for %s, using fallback", op_name)
return self._fallback(
template_choices,
kernel_inputs,
templates,
op_name,
kwarg_overrides,
)
log.info(
"LookupChoices: lookup hit for %s - found %d/%d templates: %s",
op_name,
len(lookup_results),
len(template_uids),
list(lookup_results.keys()),
)
# 4. Create KTCs only for templates with lookup entries
return self._create_lookup_choices(
lookup_results, templates, kernel_inputs, op_name
)
|
Check lookup table for hits, use those if found, otherwise fall back to parent.
|
python
|
torch/_inductor/lookup_table/choices.py
| 312
|
[
"self",
"template_choices",
"kernel_inputs",
"templates",
"op_name",
"kwarg_overrides"
] |
list[KernelTemplateChoice]
| true
| 3
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
highlight_max
|
def highlight_max(
self,
subset: Subset | None = None,
color: str = "yellow",
axis: Axis | None = 0,
props: str | None = None,
) -> Styler:
"""
Highlight the maximum with a style.
Parameters
----------
%(subset)s
%(color)s
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
%(props)s
Returns
-------
Styler
Instance of class where max value is highlighted in given style.
See Also
--------
Styler.highlight_null: Highlight missing values with a style.
Styler.highlight_min: Highlight the minimum with a style.
Styler.highlight_between: Highlight a defined range with a style.
Styler.highlight_quantile: Highlight values defined by a quantile with a style.
Examples
--------
>>> df = pd.DataFrame({"A": [2, 1], "B": [3, 4]})
>>> df.style.highlight_max(color="yellow") # doctest: +SKIP
Please see:
`Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
"""
if props is None:
props = f"background-color: {color};"
return self.apply(
partial(_highlight_value, op="max"),
axis=axis,
subset=subset,
props=props,
)
|
Highlight the maximum with a style.
Parameters
----------
%(subset)s
%(color)s
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
%(props)s
Returns
-------
Styler
Instance of class where max value is highlighted in given style.
See Also
--------
Styler.highlight_null: Highlight missing values with a style.
Styler.highlight_min: Highlight the minimum with a style.
Styler.highlight_between: Highlight a defined range with a style.
Styler.highlight_quantile: Highlight values defined by a quantile with a style.
Examples
--------
>>> df = pd.DataFrame({"A": [2, 1], "B": [3, 4]})
>>> df.style.highlight_max(color="yellow") # doctest: +SKIP
Please see:
`Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
|
python
|
pandas/io/formats/style.py
| 3,351
|
[
"self",
"subset",
"color",
"axis",
"props"
] |
Styler
| true
| 2
| 6.8
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
flatten
|
function flatten<T extends L.List, I>(list: T & L.List<I>): Flatten<T> {
return reduce(list, (acc, item) => concat(acc, wrap(item)), [] as any[])
}
|
Returns a new array with all sub-array elements concatenated.
(more efficient than native flat)
@param list
@returns
|
typescript
|
helpers/blaze/flatten.ts
| 19
|
[
"list"
] | true
| 1
| 6.8
|
prisma/prisma
| 44,834
|
jsdoc
| false
|
|
parseParameterWorker
|
function parseParameterWorker(inOuterAwaitContext: boolean, allowAmbiguity = true): ParameterDeclaration | undefined {
const pos = getNodePos();
const hasJSDoc = hasPrecedingJSDocComment();
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
// Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
const modifiers = inOuterAwaitContext ?
doInAwaitContext(() => parseModifiers(/*allowDecorators*/ true)) :
doOutsideOfAwaitContext(() => parseModifiers(/*allowDecorators*/ true));
if (token() === SyntaxKind.ThisKeyword) {
const node = factory.createParameterDeclaration(
modifiers,
/*dotDotDotToken*/ undefined,
createIdentifier(/*isIdentifier*/ true),
/*questionToken*/ undefined,
parseTypeAnnotation(),
/*initializer*/ undefined,
);
const modifier = firstOrUndefined(modifiers);
if (modifier) {
parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters);
}
return withJSDoc(finishNode(node, pos), hasJSDoc);
}
const savedTopLevel = topLevel;
topLevel = false;
const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
if (!allowAmbiguity && !isParameterNameStart()) {
return undefined;
}
const node = withJSDoc(
finishNode(
factory.createParameterDeclaration(
modifiers,
dotDotDotToken,
parseNameOfParameter(modifiers),
parseOptionalToken(SyntaxKind.QuestionToken),
parseTypeAnnotation(),
parseInitializer(),
),
pos,
),
hasJSDoc,
);
topLevel = savedTopLevel;
return node;
}
|
Reports a diagnostic error for the current token being an invalid name.
@param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
@param nameDiagnostic Diagnostic to report for all other cases.
@param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
|
typescript
|
src/compiler/parser.ts
| 4,036
|
[
"inOuterAwaitContext",
"allowAmbiguity"
] | true
| 6
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
removeOccurrences
|
@CanIgnoreReturnValue
public static boolean removeOccurrences(
Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) {
checkNotNull(multisetToModify);
checkNotNull(occurrencesToRemove);
boolean changed = false;
Iterator<? extends Entry<?>> entryIterator = multisetToModify.entrySet().iterator();
while (entryIterator.hasNext()) {
Entry<?> entry = entryIterator.next();
int removeCount = occurrencesToRemove.count(entry.getElement());
if (removeCount >= entry.getCount()) {
entryIterator.remove();
changed = true;
} else if (removeCount > 0) {
multisetToModify.remove(entry.getElement(), removeCount);
changed = true;
}
}
return changed;
}
|
For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one
occurrence of {@code e} in {@code multisetToModify}.
<p>Equivalently, this method modifies {@code multisetToModify} so that {@code
multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) -
occurrencesToRemove.count(e))}.
<p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll
removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear
in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit
sometimes more efficient than, the following:
{@snippet :
for (E e : occurrencesToRemove) {
multisetToModify.remove(e);
}
}
@return {@code true} if {@code multisetToModify} was changed as a result of this operation
@since 10.0 (missing in 18.0 when only the overload taking an {@code Iterable} was present)
|
java
|
android/guava/src/com/google/common/collect/Multisets.java
| 800
|
[
"multisetToModify",
"occurrencesToRemove"
] | true
| 4
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
|
maybe_coerce_values
|
def maybe_coerce_values(values: ArrayLike) -> ArrayLike:
"""
Input validation for values passed to __init__. Ensure that
any datetime64/timedelta64 dtypes are in nanoseconds. Ensure
that we do not have string dtypes.
Parameters
----------
values : np.ndarray or ExtensionArray
Returns
-------
values : np.ndarray or ExtensionArray
"""
# Caller is responsible for ensuring NumpyExtensionArray is already extracted.
if isinstance(values, np.ndarray):
values = ensure_wrapped_if_datetimelike(values)
if issubclass(values.dtype.type, str):
values = np.array(values, dtype=object)
if isinstance(values, (DatetimeArray, TimedeltaArray)) and values.freq is not None:
# freq is only stored in DatetimeIndex/TimedeltaIndex, not in Series/DataFrame
values = values._with_freq(None)
return values
|
Input validation for values passed to __init__. Ensure that
any datetime64/timedelta64 dtypes are in nanoseconds. Ensure
that we do not have string dtypes.
Parameters
----------
values : np.ndarray or ExtensionArray
Returns
-------
values : np.ndarray or ExtensionArray
|
python
|
pandas/core/internals/blocks.py
| 2,187
|
[
"values"
] |
ArrayLike
| true
| 5
| 6.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
createSuperElementAccessInAsyncMethod
|
function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression {
if (enclosingSuperContainerFlags & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) {
return setTextRange(
factory.createPropertyAccessExpression(
factory.createCallExpression(
factory.createIdentifier("_superIndex"),
/*typeArguments*/ undefined,
[argumentExpression],
),
"value",
),
location,
);
}
else {
return setTextRange(
factory.createCallExpression(
factory.createIdentifier("_superIndex"),
/*typeArguments*/ undefined,
[argumentExpression],
),
location,
);
}
}
|
Hooks node substitutions.
@param hint The context for the emitter.
@param node The node to substitute.
|
typescript
|
src/compiler/transformers/es2018.ts
| 1,461
|
[
"argumentExpression",
"location"
] | true
| 3
| 7.04
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
bindLoggerGroups
|
private void bindLoggerGroups(ConfigurableEnvironment environment) {
if (this.loggerGroups != null) {
Binder binder = Binder.get(environment);
binder.bind(LOGGING_GROUP, STRING_STRINGS_MAP).ifBound(this.loggerGroups::putAll);
}
}
|
Initialize the logging system according to preferences expressed through the
{@link Environment} and the classpath.
@param environment the environment
@param classLoader the classloader
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java
| 368
|
[
"environment"
] |
void
| true
| 2
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
registerBeanDefinitions
|
public int registerBeanDefinitions(ResourceBundle rb) throws BeanDefinitionStoreException {
return registerBeanDefinitions(rb, null);
}
|
Register bean definitions contained in a resource bundle,
using all property keys (i.e. not filtering by prefix).
@param rb the ResourceBundle to load from
@return the number of bean definitions found
@throws BeanDefinitionStoreException in case of loading or parsing errors
@see #registerBeanDefinitions(java.util.ResourceBundle, String)
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java
| 287
|
[
"rb"
] | true
| 1
| 6.16
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
flushPendingBuffer
|
private void flushPendingBuffer() {
int latestPosition = buffer.position();
buffer.reset();
if (latestPosition > buffer.position()) {
buffer.limit(latestPosition);
addBuffer(buffer.slice());
buffer.position(latestPosition);
buffer.limit(buffer.capacity());
buffer.mark();
}
}
|
Write a record set. The underlying record data will be retained
in the result of {@link #build()}. See {@link BaseRecords#toSend()}.
@param records the records to write
|
java
|
clients/src/main/java/org/apache/kafka/common/protocol/SendBuilder.java
| 159
|
[] |
void
| true
| 2
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
clear
|
public FluentBitSet clear() {
bitSet.clear();
return this;
}
|
Sets all of the bits in this BitSet to {@code false}.
@return {@code this} instance.
|
java
|
src/main/java/org/apache/commons/lang3/util/FluentBitSet.java
| 138
|
[] |
FluentBitSet
| true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
invoke
|
def invoke( # type: ignore
self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any
) -> Result:
"""Invokes a CLI command in an isolated environment. See
:meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for
full method documentation. See :ref:`testing-cli` for examples.
If the ``obj`` argument is not given, passes an instance of
:class:`~flask.cli.ScriptInfo` that knows how to load the Flask
app being tested.
:param cli: Command object to invoke. Default is the app's
:attr:`~flask.app.Flask.cli` group.
:param args: List of strings to invoke the command with.
:return: a :class:`~click.testing.Result` object.
"""
if cli is None:
cli = self.app.cli
if "obj" not in kwargs:
kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)
return super().invoke(cli, args, **kwargs)
|
Invokes a CLI command in an isolated environment. See
:meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for
full method documentation. See :ref:`testing-cli` for examples.
If the ``obj`` argument is not given, passes an instance of
:class:`~flask.cli.ScriptInfo` that knows how to load the Flask
app being tested.
:param cli: Command object to invoke. Default is the app's
:attr:`~flask.app.Flask.cli` group.
:param args: List of strings to invoke the command with.
:return: a :class:`~click.testing.Result` object.
|
python
|
src/flask/testing.py
| 275
|
[
"self",
"cli",
"args"
] |
Result
| true
| 3
| 7.6
|
pallets/flask
| 70,946
|
sphinx
| false
|
bind
|
default @Nullable Object bind(ConfigurationPropertyName name, Bindable<?> target) {
return bind(name, target, null);
}
|
Bind the given name to a target bindable.
@param name the name to bind
@param target the target bindable
@return a bound object or {@code null}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/AggregateElementBinder.java
| 40
|
[
"name",
"target"
] |
Object
| true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
substitute
|
protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
return substitute(buf, offset, length, null) > 0;
}
|
Internal method that substitutes the variables.
<p>
Most users of this class do not need to call this method. This method will
be called automatically by another (public) method.
</p>
<p>
Writers of subclasses can override this method if they need access to
the substitution process at the start or end.
</p>
@param buf the string builder to substitute into, not null.
@param offset the start offset within the builder, must be valid.
@param length the length within the builder to be processed, must be valid.
@return true if altered.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java
| 1,088
|
[
"buf",
"offset",
"length"
] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
nextAcquiredRecord
|
private OffsetAndDeliveryCount nextAcquiredRecord() {
if (acquiredRecordIterator.hasNext()) {
return acquiredRecordIterator.next();
}
return null;
}
|
The {@link RecordBatch batch} of {@link Record records} is converted to a {@link List list} of
{@link ConsumerRecord consumer records} and returned. {@link BufferSupplier Decompression} and
{@link Deserializer deserialization} of the {@link Record record's} key and value are performed in
this step.
@param deserializers {@link Deserializer}s to use to convert the raw bytes to the expected key and value types
@param maxRecords The number of records to return; the number returned may be {@code 0 <= maxRecords}
@param checkCrcs Whether to check the CRC of fetched records
@return {@link ShareInFlightBatch The ShareInFlightBatch containing records and their acknowledgements}
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareCompletedFetch.java
| 275
|
[] |
OffsetAndDeliveryCount
| true
| 2
| 7.6
|
apache/kafka
| 31,560
|
javadoc
| false
|
requestAutoCommit
|
private CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> requestAutoCommit(final OffsetCommitRequestState requestState) {
AutoCommitState autocommit = autoCommitState.get();
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result;
if (requestState.offsets.isEmpty()) {
result = CompletableFuture.completedFuture(Collections.emptyMap());
} else {
autocommit.setInflightCommitStatus(true);
OffsetCommitRequestState request = pendingRequests.addOffsetCommitRequest(requestState);
result = request.future;
result.whenComplete(autoCommitCallback(request.offsets));
}
return result;
}
|
Generate a request to commit consumed offsets. Add the request to the queue of pending
requests to be sent out on the next call to {@link #poll(long)}. If there are empty
offsets to commit, no request will be generated and a completed future will be returned.
@param requestState Commit request
@return Future containing the offsets that were committed, or an error if the request
failed.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
| 250
|
[
"requestState"
] | true
| 2
| 8.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
getObject
|
@Override
public @Nullable Object getObject() throws Exception {
if (this.singleton) {
if (!this.initialized) {
throw new FactoryBeanNotInitializedException();
}
// Singleton: return shared object.
return this.singletonObject;
}
else {
// Prototype: new object on each call.
return invokeWithTargetException();
}
}
|
Returns the same value each time if the singleton property is set
to "true", otherwise returns the value returned from invoking the
specified method on the fly.
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java
| 118
|
[] |
Object
| true
| 3
| 7.04
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
_ensure_key_mapped_multiindex
|
def _ensure_key_mapped_multiindex(
index: MultiIndex, key: Callable, level=None
) -> MultiIndex:
"""
Returns a new MultiIndex in which key has been applied
to all levels specified in level (or all levels if level
is None). Used for key sorting for MultiIndex.
Parameters
----------
index : MultiIndex
Index to which to apply the key function on the
specified levels.
key : Callable
Function that takes an Index and returns an Index of
the same shape. This key is applied to each level
separately. The name of the level can be used to
distinguish different levels for application.
level : list-like, int or str, default None
Level or list of levels to apply the key function to.
If None, key function is applied to all levels. Other
levels are left unchanged.
Returns
-------
labels : MultiIndex
Resulting MultiIndex with modified levels.
"""
if level is not None:
if isinstance(level, (str, int)):
level_iter = [level]
else:
level_iter = level
sort_levels: range | set = {index._get_level_number(lev) for lev in level_iter}
else:
sort_levels = range(index.nlevels)
mapped = [
(
ensure_key_mapped(index._get_level_values(level), key)
if level in sort_levels
else index._get_level_values(level)
)
for level in range(index.nlevels)
]
return type(index).from_arrays(mapped)
|
Returns a new MultiIndex in which key has been applied
to all levels specified in level (or all levels if level
is None). Used for key sorting for MultiIndex.
Parameters
----------
index : MultiIndex
Index to which to apply the key function on the
specified levels.
key : Callable
Function that takes an Index and returns an Index of
the same shape. This key is applied to each level
separately. The name of the level can be used to
distinguish different levels for application.
level : list-like, int or str, default None
Level or list of levels to apply the key function to.
If None, key function is applied to all levels. Other
levels are left unchanged.
Returns
-------
labels : MultiIndex
Resulting MultiIndex with modified levels.
|
python
|
pandas/core/sorting.py
| 500
|
[
"index",
"key",
"level"
] |
MultiIndex
| true
| 6
| 6.72
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
get_bucket
|
def get_bucket(self, bucket_name: str | None = None) -> oss2.api.Bucket:
"""
Return a oss2.Bucket object.
:param bucket_name: the name of the bucket
:return: the bucket object to the bucket name.
"""
auth = self.get_credential()
return oss2.Bucket(auth, f"https://oss-{self.region}.aliyuncs.com", bucket_name)
|
Return a oss2.Bucket object.
:param bucket_name: the name of the bucket
:return: the bucket object to the bucket name.
|
python
|
providers/alibaba/src/airflow/providers/alibaba/cloud/hooks/oss.py
| 132
|
[
"self",
"bucket_name"
] |
oss2.api.Bucket
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
_validate_skipfooter
|
def _validate_skipfooter(kwds: dict[str, Any]) -> None:
"""
Check whether skipfooter is compatible with other kwargs in TextFileReader.
Parameters
----------
kwds : dict
Keyword arguments passed to TextFileReader.
Raises
------
ValueError
If skipfooter is not compatible with other parameters.
"""
if kwds.get("skipfooter"):
if kwds.get("iterator") or kwds.get("chunksize"):
raise ValueError("'skipfooter' not supported for iteration")
if kwds.get("nrows"):
raise ValueError("'skipfooter' not supported with 'nrows'")
|
Check whether skipfooter is compatible with other kwargs in TextFileReader.
Parameters
----------
kwds : dict
Keyword arguments passed to TextFileReader.
Raises
------
ValueError
If skipfooter is not compatible with other parameters.
|
python
|
pandas/io/parsers/readers.py
| 2,371
|
[
"kwds"
] |
None
| true
| 5
| 6.24
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
map
|
<T> Map<String, T> map(Supplier<Map<String, T>> mapFactory, CheckedFunction<XContentParser, T, IOException> mapValueParser)
throws IOException;
|
Returns an instance of {@link Map} holding parsed map.
Serves as a replacement for the "map", "mapOrdered" and "mapStrings" methods above.
@param mapFactory factory for creating new {@link Map} objects
@param mapValueParser parser for parsing a single map value
@param <T> map value type
@return {@link Map} object
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParser.java
| 101
|
[
"mapFactory",
"mapValueParser"
] | true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
_collect_all_valid_cia_ops
|
def _collect_all_valid_cia_ops() -> set["OperatorBase"]:
"""
This is an util function that gets the all CIA functional ops.
The algorithm is in 2 steps:
1. We first query C++ dispatcher to get the list of CIA ops
and then we call getattr on torch.ops.aten to lazily populate
them.
2. Sometimes, handful of ops have CIA registered in python dispatcher
but not on the C++ side, these can't be caught at the first step.
So we walk again to get the final list.
Note that the output of this function should never be modified
"""
cia_ops = set()
for op_namespace_name in torch.ops._dir:
# The reason we split here is because aten ops are safe to cache.
if op_namespace_name != "aten":
assert hasattr(torch.ops, op_namespace_name)
op_namespace = getattr(torch.ops, op_namespace_name)
if isinstance(op_namespace, torch._ops._OpNamespace):
cia_ops |= _collect_all_valid_cia_ops_for_namespace(op_namespace)
else:
cia_ops |= _collect_all_valid_cia_ops_for_aten_namespace()
return cia_ops
|
This is an util function that gets the all CIA functional ops.
The algorithm is in 2 steps:
1. We first query C++ dispatcher to get the list of CIA ops
and then we call getattr on torch.ops.aten to lazily populate
them.
2. Sometimes, handful of ops have CIA registered in python dispatcher
but not on the C++ side, these can't be caught at the first step.
So we walk again to get the final list.
Note that the output of this function should never be modified
|
python
|
torch/_export/utils.py
| 1,339
|
[] |
set["OperatorBase"]
| true
| 5
| 7.04
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
appendFile
|
function appendFile(path, data, options, callback) {
callback ||= options;
validateFunction(callback, 'cb');
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
// Don't make changes directly on options object
options = copyObject(options);
// Force append behavior when using a supplied file descriptor
if (!options.flag || isFd(path))
options.flag = 'a';
fs.writeFile(path, data, options, callback);
}
|
Asynchronously appends data to a file.
@param {string | Buffer | URL | number} path
@param {string | Buffer} data
@param {{
encoding?: string | null;
mode?: number;
flag?: string;
flush?: boolean;
} | string} [options]
@param {(err?: Error) => any} callback
@returns {void}
|
javascript
|
lib/fs.js
| 2,438
|
[
"path",
"data",
"options",
"callback"
] | false
| 3
| 6.24
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
setErrorAttributes
|
private void setErrorAttributes(HttpServletRequest request, int status, @Nullable String message) {
request.setAttribute(ERROR_STATUS_CODE, status);
request.setAttribute(ERROR_MESSAGE, message);
request.setAttribute(ERROR_REQUEST_URI, request.getRequestURI());
}
|
Return the description for the given request. By default this method will return a
description based on the request {@code servletPath} and {@code pathInfo}.
@param request the source request
@return the description
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java
| 256
|
[
"request",
"status",
"message"
] |
void
| true
| 1
| 6.72
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
lazyWeakReadWriteLock
|
public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) {
return lazyWeakCustom(stripes, WeakSafeReadWriteLock::new);
}
|
Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced read-write
locks. Every lock is reentrant.
@param stripes the minimum number of stripes (locks) required
@return a new {@code Striped<ReadWriteLock>}
|
java
|
android/guava/src/com/google/common/util/concurrent/Striped.java
| 279
|
[
"stripes"
] | true
| 1
| 6.16
|
google/guava
| 51,352
|
javadoc
| false
|
|
withExtraFieldLength
|
ZipLocalFileHeaderRecord withExtraFieldLength(short extraFieldLength) {
return new ZipLocalFileHeaderRecord(this.versionNeededToExtract, this.generalPurposeBitFlag,
this.compressionMethod, this.lastModFileTime, this.lastModFileDate, this.crc32, this.compressedSize,
this.uncompressedSize, this.fileNameLength, extraFieldLength);
}
|
Return a new {@link ZipLocalFileHeaderRecord} with a new
{@link #extraFieldLength()}.
@param extraFieldLength the new extra field length
@return a new {@link ZipLocalFileHeaderRecord} instance
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipLocalFileHeaderRecord.java
| 66
|
[
"extraFieldLength"
] |
ZipLocalFileHeaderRecord
| true
| 1
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
get_secret_as_dict
|
def get_secret_as_dict(self, secret_name: str) -> dict:
"""
Retrieve secret value from AWS Secrets Manager as a dict.
:param secret_name: name of the secrets.
:return: dict with the information about the secrets
"""
return json.loads(self.get_secret(secret_name))
|
Retrieve secret value from AWS Secrets Manager as a dict.
:param secret_name: name of the secrets.
:return: dict with the information about the secrets
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/secrets_manager.py
| 64
|
[
"self",
"secret_name"
] |
dict
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
withoutParameters
|
public MediaType withoutParameters() {
return parameters.isEmpty() ? this : create(type, subtype);
}
|
Returns a new instance with the same type and subtype as this instance, but without any
parameters.
|
java
|
android/guava/src/com/google/common/net/MediaType.java
| 881
|
[] |
MediaType
| true
| 2
| 6.96
|
google/guava
| 51,352
|
javadoc
| false
|
statfs
|
function statfs(path, options = { bigint: false }, callback) {
if (typeof options === 'function') {
callback = options;
options = kEmptyObject;
}
validateFunction(callback, 'cb');
path = getValidatedPath(path);
const req = new FSReqCallback(options.bigint);
req.oncomplete = (err, stats) => {
if (err) {
return callback(err);
}
callback(err, getStatFsFromBinding(stats));
};
binding.statfs(getValidatedPath(path), options.bigint, req);
}
|
Asynchronously gets the stats of a file.
@param {string | Buffer | URL} path
@param {{ bigint?: boolean; }} [options]
@param {(
err?: Error,
stats?: Stats
) => any} callback
@returns {void}
|
javascript
|
lib/fs.js
| 1,629
|
[
"path",
"callback"
] | false
| 3
| 6.08
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
of
|
public static Options of(Option... options) {
Assert.notNull(options, "'options' must not be null");
if (options.length == 0) {
return NONE;
}
return new Options(EnumSet.copyOf(Arrays.asList(options)));
}
|
Create a new instance with the given {@link Option} values.
@param options the options to include
@return a new {@link Options} instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigData.java
| 255
|
[] |
Options
| true
| 2
| 8.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
baseUnset
|
function baseUnset(object, path) {
path = castPath(path, object);
// Prevent prototype pollution, see: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg
var index = -1,
length = path.length;
if (!length) {
return true;
}
var isRootPrimitive = object == null || (typeof object !== 'object' && typeof object !== 'function');
while (++index < length) {
var key = path[index];
// skip non-string keys (e.g., Symbols, numbers)
if (typeof key !== 'string') {
continue;
}
// Always block "__proto__" anywhere in the path if it's not expected
if (key === '__proto__' && !hasOwnProperty.call(object, '__proto__')) {
return false;
}
// Block "constructor.prototype" chains
if (key === 'constructor' &&
(index + 1) < length &&
typeof path[index + 1] === 'string' &&
path[index + 1] === 'prototype') {
// Allow ONLY when the path starts at a primitive root, e.g., _.unset(0, 'constructor.prototype.a')
if (isRootPrimitive && index === 0) {
continue;
}
return false;
}
}
var obj = parent(object, path);
return obj == null || delete obj[toKey(last(path))];
}
|
The base implementation of `_.unset`.
@private
@param {Object} object The object to modify.
@param {Array|string} path The property path to unset.
@returns {boolean} Returns `true` if the property is deleted, else `false`.
|
javascript
|
lodash.js
| 4,371
|
[
"object",
"path"
] | false
| 15
| 6.4
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
first_valid_index
|
def first_valid_index(self) -> Hashable:
"""
Return index for {position} non-missing value or None, if no value is found.
See the :ref:`User Guide <missing_data>` for more information
on which values are considered missing.
Returns
-------
type of index
Index of {position} non-missing value.
See Also
--------
DataFrame.last_valid_index : Return index for last non-NA value or None, if
no non-NA value is found.
Series.last_valid_index : Return index for last non-NA value or None, if no
non-NA value is found.
DataFrame.isna : Detect missing values.
Examples
--------
For Series:
>>> s = pd.Series([None, 3, 4])
>>> s.first_valid_index()
1
>>> s.last_valid_index()
2
>>> s = pd.Series([None, None])
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If all elements in Series are NA/null, returns None.
>>> s = pd.Series()
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If Series is empty, returns None.
For DataFrame:
>>> df = pd.DataFrame({{"A": [None, None, 2], "B": [None, 3, 4]}})
>>> df
A B
0 NaN NaN
1 NaN 3.0
2 2.0 4.0
>>> df.first_valid_index()
1
>>> df.last_valid_index()
2
>>> df = pd.DataFrame({{"A": [None, None, None], "B": [None, None, None]}})
>>> df
A B
0 None None
1 None None
2 None None
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If all elements in DataFrame are NA/null, returns None.
>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If DataFrame is empty, returns None.
"""
return self._find_valid_index(how="first")
|
Return index for {position} non-missing value or None, if no value is found.
See the :ref:`User Guide <missing_data>` for more information
on which values are considered missing.
Returns
-------
type of index
Index of {position} non-missing value.
See Also
--------
DataFrame.last_valid_index : Return index for last non-NA value or None, if
no non-NA value is found.
Series.last_valid_index : Return index for last non-NA value or None, if no
non-NA value is found.
DataFrame.isna : Detect missing values.
Examples
--------
For Series:
>>> s = pd.Series([None, 3, 4])
>>> s.first_valid_index()
1
>>> s.last_valid_index()
2
>>> s = pd.Series([None, None])
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If all elements in Series are NA/null, returns None.
>>> s = pd.Series()
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If Series is empty, returns None.
For DataFrame:
>>> df = pd.DataFrame({{"A": [None, None, 2], "B": [None, 3, 4]}})
>>> df
A B
0 NaN NaN
1 NaN 3.0
2 2.0 4.0
>>> df.first_valid_index()
1
>>> df.last_valid_index()
2
>>> df = pd.DataFrame({{"A": [None, None, None], "B": [None, None, None]}})
>>> df
A B
0 None None
1 None None
2 None None
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If all elements in DataFrame are NA/null, returns None.
>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If DataFrame is empty, returns None.
|
python
|
pandas/core/generic.py
| 11,602
|
[
"self"
] |
Hashable
| true
| 1
| 6
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
optInt
|
public int optInt(int index) {
return optInt(index, 0);
}
|
Returns the value at {@code index} if it exists and is an int or can be coerced to
an int. Returns 0 otherwise.
@param index the index to get the value from
@return the {@code value} or {@code 0}
|
java
|
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
| 421
|
[
"index"
] | true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
putIfAbsent
|
public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value) {
if (map == null) {
return null;
}
final V result = map.putIfAbsent(key, value);
return result != null ? result : value;
}
|
Puts a value in the specified {@link ConcurrentMap} if the key is not yet
present. This method works similar to the {@code putIfAbsent()} method of
the {@link ConcurrentMap} interface, but the value returned is different.
Basically, this method is equivalent to the following code fragment:
<pre>
if (!map.containsKey(key)) {
map.put(key, value);
return value;
} else {
return map.get(key);
}
</pre>
<p>
except that the action is performed atomically. So this method always
returns the value which is stored in the map.
</p>
<p>
This method is <strong>null</strong>-safe: It accepts a <strong>null</strong> map as input
without throwing an exception. In this case the return value is
<strong>null</strong>, too.
</p>
@param <K> the type of the keys of the map
@param <V> the type of the values of the map
@param map the map to be modified
@param key the key of the value to be added
@param value the value to be added
@return the value stored in the map after this operation
|
java
|
src/main/java/org/apache/commons/lang3/concurrent/ConcurrentUtils.java
| 345
|
[
"map",
"key",
"value"
] |
V
| true
| 3
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
createDeclarationName
|
function createDeclarationName(symbol: Symbol, declaration: Declaration | undefined): PropertyName {
if (getCheckFlags(symbol) & CheckFlags.Mapped) {
const nameType = (symbol as TransientSymbol).links.nameType;
if (nameType && isTypeUsableAsPropertyName(nameType)) {
return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType)));
}
}
return getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false) as PropertyName;
}
|
(#49811)
Note that there are cases in which the symbol declaration is not present. For example, in the code below both
`MappedIndirect.ax` and `MappedIndirect.ay` have no declaration node attached (due to their mapped-type
parent):
```ts
type Base = { ax: number; ay: string };
type BaseKeys = keyof Base;
type MappedIndirect = { [K in BaseKeys]: boolean };
```
In such cases, we assume the declaration to be a `PropertySignature`.
|
typescript
|
src/services/codefixes/helpers.ts
| 365
|
[
"symbol",
"declaration"
] | true
| 4
| 7.28
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
containsLocalBean
|
@Override
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
|
Internal extended variant of {@link #isTypeMatch(String, ResolvableType)}
to check whether the bean with the given name matches the specified type. Allow
additional constraints to be applied to ensure that beans are not created early.
@param name the name of the bean to query
@param typeToMatch the type to match against (as a {@code ResolvableType})
@return {@code true} if the bean type matches, {@code false} if it
doesn't match or cannot be determined yet
@throws NoSuchBeanDefinitionException if there is no bean with the given name
@since 5.2
@see #getBean
@see #getType
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
| 803
|
[
"name"
] | true
| 4
| 7.92
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
isGroupReady
|
private boolean isGroupReady(List<StreamsGroupHeartbeatResponseData.Status> statuses) {
if (statuses != null) {
for (final StreamsGroupHeartbeatResponseData.Status status : statuses) {
switch (StreamsGroupHeartbeatResponse.Status.fromCode(status.statusCode())) {
case MISSING_SOURCE_TOPICS:
case MISSING_INTERNAL_TOPICS:
case INCORRECTLY_PARTITIONED_TOPICS:
case ASSIGNMENT_DELAYED:
return false;
default:
// continue checking other statuses
}
}
}
return true;
}
|
Notify about a successful heartbeat response.
@param response Heartbeat response to extract member info and errors from.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
| 729
|
[
"statuses"
] | true
| 2
| 6.72
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
attributesFor
|
static @Nullable AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationTypeName) {
return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationTypeName));
}
|
Register all relevant annotation post processors in the given registry.
@param registry the registry to operate on
@param source the configuration source element (already extracted)
that this registration was triggered from. May be {@code null}.
@return a Set of BeanDefinitionHolders, containing all bean definitions
that have actually been registered by this call
|
java
|
spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
| 293
|
[
"metadata",
"annotationTypeName"
] |
AnnotationAttributes
| true
| 1
| 6.16
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
assign
|
public abstract Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
Map<String, Subscription> subscriptions);
|
Perform the group assignment given the partition counts and member subscriptions
@param partitionsPerTopic The number of partitions for each subscribed topic. Topics not in metadata will be excluded
from this map.
@param subscriptions Map from the member id to their respective topic subscription
@return Map from each member to the list of partitions assigned to them.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractPartitionAssignor.java
| 58
|
[
"partitionsPerTopic",
"subscriptions"
] | true
| 1
| 6.32
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
of
|
public static ConfigDataLocation of(@Nullable String location) {
boolean optional = location != null && location.startsWith(OPTIONAL_PREFIX);
String value = (location != null && optional) ? location.substring(OPTIONAL_PREFIX.length()) : location;
return (StringUtils.hasText(value)) ? new ConfigDataLocation(optional, value, null) : EMPTY;
}
|
Factory method to create a new {@link ConfigDataLocation} from a string.
@param location the location string
@return the {@link ConfigDataLocation} (which may be empty)
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocation.java
| 167
|
[
"location"
] |
ConfigDataLocation
| true
| 5
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
findThreads
|
@Deprecated
public static Collection<Thread> findThreads(final ThreadPredicate predicate) {
return findThreads(getSystemThreadGroup(), true, predicate);
}
|
Finds all active threads which match the given predicate.
@param predicate the predicate.
@return An unmodifiable {@link Collection} of active threads matching the given predicate.
@throws NullPointerException if the predicate is null.
@throws SecurityException if the current thread cannot access the system thread group.
@throws SecurityException if the current thread cannot modify thread groups from this thread's thread group up to the system thread group.
@deprecated Use {@link #findThreads(Predicate)}.
|
java
|
src/main/java/org/apache/commons/lang3/ThreadUtils.java
| 380
|
[
"predicate"
] | true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
close
|
void close() throws Exception {
if (this.archive != null) {
this.archive.close();
}
}
|
Properties key for boolean flag (default false) which, if set, will cause the
external configuration properties to be copied to System properties (assuming that
is allowed by Java security).
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/launch/PropertiesLauncher.java
| 445
|
[] |
void
| true
| 2
| 6.72
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
replay
|
public static Log replay(Log source, Class<?> destination) {
return replay(source, LogFactory.getLog(destination));
}
|
Replay from a source log to a destination log when the source is deferred.
@param source the source logger
@param destination the destination logger class
@return the destination
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java
| 233
|
[
"source",
"destination"
] |
Log
| true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
canHandleNewAssignment
|
public boolean canHandleNewAssignment() {
return MemberState.RECONCILING.getPreviousValidStates().contains(this);
}
|
@return True if the member is in a state where it should reconcile the new assignment.
Expected to be true whenever the member is part of the group and intends of staying in it
(ex. false when the member is preparing to leave the group).
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/MemberState.java
| 159
|
[] | true
| 1
| 6.96
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
is_fusible_node
|
def is_fusible_node(n: fx.Node) -> bool:
"""Check if a node is fusible based on whether it has an inductor lowering.
A node is fusible if:
- It has a lowering in torch._inductor.lowering.lowerings
- It does NOT have a flop counter (expensive compute ops like mm/conv)
- It is NOT a registered fallback (ops that fall back to eager)
- It is NOT a collective or wait op
- For aten.cat, it must have <= max_pointwise_cat_inputs inputs
"""
if n.op != "call_function":
return False
target = n.target
if not isinstance(target, torch._ops.OpOverload):
return False
# Exclude collectives and waits (they have their own scheduling)
if target.namespace == "_c10d_functional":
return False
from torch._inductor.lowering import fallbacks, lowerings
from torch.utils.flop_counter import flop_registry
# Must have a lowering
if target not in lowerings:
return False
# Exclude fallbacks (ops that fall back to eager execution)
if target in fallbacks:
return False
# Exclude ops with flop counters (expensive compute ops like mm, conv, etc.)
overload_packet = target.overloadpacket
if overload_packet in flop_registry:
return False
# Special case: cat is only fusible if it has few enough inputs
if target == torch.ops.aten.cat.default:
inputs = n.args[0] if n.args else []
if isinstance(inputs, (list, tuple)):
import torch._inductor.config as inductor_config
if len(inputs) > inductor_config.max_pointwise_cat_inputs:
return False
return True
|
Check if a node is fusible based on whether it has an inductor lowering.
A node is fusible if:
- It has a lowering in torch._inductor.lowering.lowerings
- It does NOT have a flop counter (expensive compute ops like mm/conv)
- It is NOT a registered fallback (ops that fall back to eager)
- It is NOT a collective or wait op
- For aten.cat, it must have <= max_pointwise_cat_inputs inputs
|
python
|
torch/_inductor/fx_passes/fusion_regions.py
| 57
|
[
"n"
] |
bool
| true
| 11
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
leastLoadedNode
|
LeastLoadedNode leastLoadedNode(long now);
|
Choose the node with the fewest outstanding requests. This method will prefer a node with an existing connection,
but will potentially choose a node for which we don't yet have a connection if all existing connections are in
use.
@param now The current time in ms
@return The node with the fewest in-flight requests.
|
java
|
clients/src/main/java/org/apache/kafka/clients/KafkaClient.java
| 133
|
[
"now"
] |
LeastLoadedNode
| true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
chain_as_grid
|
def chain_as_grid(*tasks):
# type: (BaseOperator) -> None
"""
Chain tasks as a grid.
Example:
t0 -> t1 -> t2 -> t3
| | |
v v v
t4 -> t5 -> t6
| |
v v
t7 -> t8
|
v
t9
"""
if len(tasks) > 100 * 99 / 2:
raise ValueError("Cannot generate grid DAGs with lateral size larger than 100 tasks.")
grid_size = min([n for n in range(100) if n * (n + 1) / 2 >= len(tasks)])
def index(i, j):
"""Return the index of node (i, j) on the grid."""
return int(grid_size * i - i * (i - 1) / 2 + j)
for i in range(grid_size - 1):
for j in range(grid_size - i - 1):
if index(i + 1, j) < len(tasks):
tasks[index(i + 1, j)].set_downstream(tasks[index(i, j)])
if index(i, j + 1) < len(tasks):
tasks[index(i, j + 1)].set_downstream(tasks[index(i, j)])
|
Chain tasks as a grid.
Example:
t0 -> t1 -> t2 -> t3
| | |
v v v
t4 -> t5 -> t6
| |
v v
t7 -> t8
|
v
t9
|
python
|
performance/src/performance_dags/performance_dag/performance_dag.py
| 148
|
[] | false
| 6
| 7.36
|
apache/airflow
| 43,597
|
unknown
| false
|
|
find
|
static @Nullable ConfigurationPropertyCaching find(@Nullable ConfigurationPropertySource source) {
if (source instanceof CachingConfigurationPropertySource cachingSource) {
return cachingSource.getCaching();
}
return null;
}
|
Find {@link ConfigurationPropertyCaching} for the given source.
@param source the configuration property source
@return a {@link ConfigurationPropertyCaching} instance or {@code null} if the
source does not support caching.
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/CachingConfigurationPropertySource.java
| 41
|
[
"source"
] |
ConfigurationPropertyCaching
| true
| 2
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
SetConsoleCtrlHandler
|
boolean SetConsoleCtrlHandler(ConsoleCtrlHandler handler, boolean add);
|
Native call to the Kernel32 API to set a new Console Ctrl Handler.
@param handler A callback to handle control events
@param add True if the handler should be added, false if it should replace existing handlers
@return true if the handler is correctly set
@see <a href="https://learn.microsoft.com/en-us/windows/console/setconsolectrlhandler">SetConsoleCtrlHandler docs</a>
|
java
|
libs/native/src/main/java/org/elasticsearch/nativeaccess/lib/Kernel32Library.java
| 117
|
[
"handler",
"add"
] | true
| 1
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
check_all_tuning_directions
|
def check_all_tuning_directions(
self,
# pyrefly: ignore [missing-attribute]
func: Callable[["triton.Config"], float],
best_config,
best_timing,
):
"""
Check all directions. We only do this once the regular coordinate
descent tuning find no better choices any more.
We only have a few tunable fields, so this should be fine.
"""
candidate_values_list = []
effective_fields = []
for field in self.tunable_fields:
old_value = get_field(best_config, field)
if old_value is None:
continue
radius = self.inductor_meta.get("coordinate_descent_search_radius", 1)
candidate_values = self.get_neighbour_values(
field,
old_value,
radius=radius,
include_self=True,
)
candidate_values_list.append(candidate_values)
effective_fields.append(field)
choices = itertools.product(*candidate_values_list)
improved = False
for choice in choices:
assert len(choice) == len(effective_fields)
candidate_config = copy.deepcopy(best_config)
for new_val, field in zip(choice, effective_fields):
set_field(candidate_config, field, new_val)
if not self.is_valid_config(candidate_config):
continue
cmp_res, candidate_timing = self.compare_config(
func, candidate_config, best_config, best_timing
)
if cmp_res:
improved = True
best_config = candidate_config
best_timing = candidate_timing
return improved, best_config, best_timing
|
Check all directions. We only do this once the regular coordinate
descent tuning find no better choices any more.
We only have a few tunable fields, so this should be fine.
|
python
|
torch/_inductor/runtime/coordinate_descent_tuner.py
| 224
|
[
"self",
"func",
"best_config",
"best_timing"
] | true
| 7
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
|
asList
|
public static List<Boolean> asList(boolean... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new BooleanArrayAsList(backingArray);
}
|
Returns a fixed-size list backed by the specified array, similar to {@link
Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
set a value to {@code null} will result in a {@link NullPointerException}.
<p>There are at most two distinct objects in this list, {@code (Boolean) true} and {@code
(Boolean) false}. Java guarantees that those are always represented by the same objects.
<p>The returned list is serializable.
@param backingArray the array to back the list
@return a list view of the array
|
java
|
android/guava/src/com/google/common/primitives/Booleans.java
| 383
|
[] | true
| 2
| 8.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
commitSync
|
public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitSync(final Map<TopicPartition, OffsetAndMetadata> offsets,
final long deadlineMs) {
if (offsets.isEmpty()) {
return CompletableFuture.completedFuture(Map.of());
}
maybeUpdateLastSeenEpochIfNewer(offsets);
CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
OffsetCommitRequestState requestState = createOffsetCommitRequest(offsets, deadlineMs);
commitSyncWithRetries(requestState, result);
return result;
}
|
Commit offsets, retrying on expected retriable errors while the retry timeout hasn't expired.
@param offsets Offsets to commit
@param deadlineMs Time until which the request will be retried if it fails with
an expected retriable error.
@return Future that will complete when a successful response
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
| 429
|
[
"offsets",
"deadlineMs"
] | true
| 2
| 7.76
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
all
|
public KafkaFuture<Void> all() {
return this.future.thenApply(topicPartitionErrorsMap -> {
List<TopicPartition> partitionsFailed = topicPartitionErrorsMap.entrySet()
.stream()
.filter(e -> e.getValue() != Errors.NONE)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
for (Errors error : topicPartitionErrorsMap.values()) {
if (error != Errors.NONE) {
throw error.exception(
"Failed altering group offsets for the following partitions: " + partitionsFailed);
}
}
return null;
});
}
|
Return a future which succeeds if all the alter offsets succeed.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/AlterConsumerGroupOffsetsResult.java
| 67
|
[] | true
| 2
| 7.04
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
moveProfileSpecificChildren
|
private ConfigDataEnvironmentContributor moveProfileSpecificChildren(ConfigDataEnvironmentContributor contributor,
List<ConfigDataEnvironmentContributor> removed) {
for (ImportPhase importPhase : ImportPhase.values()) {
List<ConfigDataEnvironmentContributor> children = contributor.getChildren(importPhase);
List<ConfigDataEnvironmentContributor> updatedChildren = new ArrayList<>(children.size());
for (ConfigDataEnvironmentContributor child : children) {
if (child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC)) {
removed.add(child.withoutConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC));
}
else {
updatedChildren.add(child);
}
}
contributor = contributor.withChildren(importPhase, updatedChildren);
}
return contributor;
}
|
Create a new {@link ConfigDataEnvironmentContributor} instance with a new set of
children for the given phase.
@param importPhase the import phase
@param children the new children
@return a new contributor instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java
| 298
|
[
"contributor",
"removed"
] |
ConfigDataEnvironmentContributor
| true
| 2
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
getPrimitiveType
|
PrimitiveType getPrimitiveType(TypeMirror typeMirror) {
if (getPrimitiveFor(typeMirror) != null) {
return this.types.unboxedType(typeMirror);
}
return null;
}
|
Return the {@link PrimitiveType} of the specified type or {@code null} if the type
does not represent a valid wrapper type.
@param typeMirror a type
@return the primitive type or {@code null} if the type is not a wrapper type
|
java
|
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java
| 194
|
[
"typeMirror"
] |
PrimitiveType
| true
| 2
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
_maybe_infer_ndim
|
def _maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int:
"""
If `ndim` is not provided, infer it from placement and values.
"""
if ndim is None:
# GH#38134 Block constructor now assumes ndim is not None
if not isinstance(values.dtype, np.dtype):
if len(placement) != 1:
ndim = 1
else:
ndim = 2
else:
ndim = values.ndim
return ndim
|
If `ndim` is not provided, infer it from placement and values.
|
python
|
pandas/core/internals/api.py
| 152
|
[
"values",
"placement",
"ndim"
] |
int
| true
| 6
| 6
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
_get_label_or_level_values
|
def _get_label_or_level_values(self, key: Level, axis: AxisInt = 0) -> ArrayLike:
"""
Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key : Hashable
Label or level name.
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
np.ndarray or ExtensionArray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
"""
axis = self._get_axis_number(axis)
first_other_axes = next(
(ax for ax in range(self._AXIS_LEN) if ax != axis), None
)
if self._is_label_reference(key, axis=axis):
self._check_label_or_level_ambiguity(key, axis=axis)
if first_other_axes is None:
raise ValueError("axis matched all axes")
values = self.xs(key, axis=first_other_axes)._values
elif self._is_level_reference(key, axis=axis):
values = self.axes[axis].get_level_values(key)._values
else:
raise KeyError(key)
# Check for duplicates
if values.ndim > 1:
if first_other_axes is not None and isinstance(
self._get_axis(first_other_axes), MultiIndex
):
multi_message = (
"\n"
"For a multi-index, the label must be a "
"tuple with elements corresponding to each level."
)
else:
multi_message = ""
label_axis_name = "column" if axis == 0 else "index"
raise ValueError(
f"The {label_axis_name} label '{key}' is not unique.{multi_message}"
)
return values
|
Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key : Hashable
Label or level name.
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
np.ndarray or ExtensionArray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
|
python
|
pandas/core/generic.py
| 1,735
|
[
"self",
"key",
"axis"
] |
ArrayLike
| true
| 10
| 6.8
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
construct
|
Object construct(ConstructorInvocation invocation) throws Throwable;
|
Implement this method to perform extra treatments before and
after the construction of a new object. Polite implementations
would certainly like to invoke {@link Joinpoint#proceed()}.
@param invocation the construction joinpoint
@return the newly created object, which is also the result of
the call to {@link Joinpoint#proceed()}; might be replaced by
the interceptor
@throws Throwable if the interceptors or the target object
throws an exception
|
java
|
spring-aop/src/main/java/org/aopalliance/intercept/ConstructorInterceptor.java
| 57
|
[
"invocation"
] |
Object
| true
| 1
| 6.16
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
get_callable_argument_names
|
def get_callable_argument_names(fn) -> list[str]:
"""
Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`.
Returns an empty list when other types of arguments are present.
This is used by `torch.jit.trace` to assign meaningful argument names to
traced functions and modules.
Args:
fn: A callable.
Returns:
Argument names: List[str]
"""
# inspect.signature may fail, give up in that case.
try:
callable_signature = inspect.signature(fn)
except Exception:
return []
argument_names = []
for name, param in callable_signature.parameters.items():
# All four other types of arguments do not map to individual values
# with a keyword as name.
if param.kind != param.POSITIONAL_OR_KEYWORD:
continue
argument_names.append(name)
return argument_names
|
Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`.
Returns an empty list when other types of arguments are present.
This is used by `torch.jit.trace` to assign meaningful argument names to
traced functions and modules.
Args:
fn: A callable.
Returns:
Argument names: List[str]
|
python
|
torch/_jit_internal.py
| 433
|
[
"fn"
] |
list[str]
| true
| 3
| 8.08
|
pytorch/pytorch
| 96,034
|
google
| false
|
tryConsumeDefine
|
function tryConsumeDefine(): boolean {
let token = scanner.getToken();
if (token === SyntaxKind.Identifier && scanner.getTokenValue() === "define") {
token = nextToken();
if (token !== SyntaxKind.OpenParenToken) {
return true;
}
token = nextToken();
if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NoSubstitutionTemplateLiteral) {
// looks like define ("modname", ... - skip string literal and comma
token = nextToken();
if (token === SyntaxKind.CommaToken) {
token = nextToken();
}
else {
// unexpected token
return true;
}
}
// should be start of dependency list
if (token !== SyntaxKind.OpenBracketToken) {
return true;
}
// skip open bracket
token = nextToken();
// scan until ']' or EOF
while (token !== SyntaxKind.CloseBracketToken && token !== SyntaxKind.EndOfFileToken) {
// record string literals as module names
if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NoSubstitutionTemplateLiteral) {
recordModuleName();
}
token = nextToken();
}
return true;
}
return false;
}
|
Returns true if at least one token was consumed from the stream
|
typescript
|
src/services/preProcess.ts
| 294
|
[] | true
| 13
| 6.56
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
readStaticField
|
public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
Objects.requireNonNull(field, "field");
Validate.isTrue(MemberUtils.isStatic(field), "The field '%s' is not static", field.getName());
return readField(field, (Object) null, forceAccess);
}
|
Reads a static {@link Field}.
@param field
to read.
@param forceAccess
whether to break scope restrictions using the
{@link AccessibleObject#setAccessible(boolean)} method.
@return the field value.
@throws NullPointerException
if the field is {@code null}.
@throws IllegalArgumentException
if the field is not {@code static}.
@throws IllegalAccessException
if the field is not made accessible.
@throws SecurityException if an underlying accessible object's method denies the request.
@see SecurityManager#checkPermission
|
java
|
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
| 542
|
[
"field",
"forceAccess"
] |
Object
| true
| 1
| 6.24
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
uriParts
|
public static Map<String, Object> uriParts(String uri) {
return UriPartsProcessor.apply(uri);
}
|
Uses {@link CommunityIdProcessor} to compute community ID for network flow data.
@param sourceIpAddrString source IP address
@param destIpAddrString destination IP address
@param ianaNumber IANA number
@param transport transport protocol
@param sourcePort source port
@param destinationPort destination port
@param icmpType ICMP type
@param icmpCode ICMP code
@return Community ID
|
java
|
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/Processors.java
| 195
|
[
"uri"
] | true
| 1
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
parseObject
|
@Override
public Object parseObject(final String source, final ParsePosition pos) {
return parser.parseObject(source, pos);
}
|
Uses the parser Format instance.
@param source the String source
@param pos the ParsePosition containing the position to parse from, will
be updated according to parsing success (index) or failure
(error index)
@return the parsed Object
@see Format#parseObject(String, ParsePosition)
|
java
|
src/main/java/org/apache/commons/lang3/text/CompositeFormat.java
| 102
|
[
"source",
"pos"
] |
Object
| true
| 1
| 6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
visitVariableStatement
|
function visitVariableStatement(node: VariableStatement): VisitResult<VariableStatement> {
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
const savedExportedVariableStatement = exportedVariableStatement;
exportedVariableStatement = true;
const visited = visitEachChild(node, visitor, context);
exportedVariableStatement = savedExportedVariableStatement;
return visited;
}
return visitEachChild(node, visitor, context);
}
|
@param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
expression of an `ExpressionStatement`).
|
typescript
|
src/compiler/transformers/es2018.ts
| 668
|
[
"node"
] | true
| 2
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
readFirstLine
|
public @Nullable String readFirstLine() throws IOException {
Closer closer = Closer.create();
try {
BufferedReader reader = closer.register(openBufferedStream());
return reader.readLine();
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
|
Reads the first line of this source as a string. Returns {@code null} if this source is empty.
<p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
\n}. If the source's content does not end in a line termination sequence, it is treated as if
it does.
@throws IOException if an I/O error occurs while reading from this source
|
java
|
android/guava/src/com/google/common/io/CharSource.java
| 314
|
[] |
String
| true
| 2
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
groupInstanceId
|
public Optional<String> groupInstanceId() {
return groupInstanceId;
}
|
@return Instance ID used by the member when joining the group. If non-empty, it will indicate that
this is a static member.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerMembershipManager.java
| 203
|
[] | true
| 1
| 6.96
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
build_subgraph_module_buffer
|
def build_subgraph_module_buffer(
args: list[TensorBox],
graph_module: torch.fx.GraphModule,
) -> SubgraphResults:
"""This function's goal is to take in the required args and produce the subgraph buffer
The subgraph buffer is a ComputedBuffer that will be inlined into the triton template
Args:
args: The args that are passed into the subgraph. Contains both fixed and lifted inputs.
subgraph: The Subgraph ir for which to produce the output node
"""
# This one we gotta keep lazy
from ...subgraph_lowering import PointwiseSubgraphLowering
pw_subgraph = PointwiseSubgraphLowering(
graph_module,
root_graph_lowering=V.graph,
allowed_mutations=OrderedSet([torch.ops.flex_lib.zeros_and_scatter.default]),
additional_lowerings={
torch.ops.flex_lib.zeros_and_scatter.default: zeros_and_scatter_lowering
},
)
with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type]
pw_subgraph.run(*args)
def convert_output_node_to_buffer(output_buffer) -> Optional[ComputedBuffer]:
if output_buffer is None:
return None
if isinstance(output_buffer, ComputedBuffer):
# These nodes are coming from the output of zeros_and_scatter
return output_buffer
assert isinstance(output_buffer, TensorBox), (
"The output node for flex attention's subgraph must be a TensorBox, but got: ",
type(output_buffer),
)
assert isinstance(output_buffer.data, StorageBox), (
"The output node for the flex attention subgraph must be a StorageBox, but got: ",
type(output_buffer),
)
device = output_buffer.data.get_device()
assert device is not None
subgraph_buffer = ComputedBuffer(
name=None,
layout=FlexibleLayout(
device=device,
dtype=output_buffer.data.get_dtype(),
size=output_buffer.data.get_size(),
),
data=output_buffer.data.data, # type: ignore[arg-type]
)
return subgraph_buffer
return tree_map(convert_output_node_to_buffer, pw_subgraph.graph_outputs)
|
This function's goal is to take in the required args and produce the subgraph buffer
The subgraph buffer is a ComputedBuffer that will be inlined into the triton template
Args:
args: The args that are passed into the subgraph. Contains both fixed and lifted inputs.
subgraph: The Subgraph ir for which to produce the output node
|
python
|
torch/_inductor/kernel/flex/common.py
| 114
|
[
"args",
"graph_module"
] |
SubgraphResults
| true
| 3
| 6.88
|
pytorch/pytorch
| 96,034
|
google
| false
|
_get_email_list_from_str
|
def _get_email_list_from_str(addresses: str) -> list[str]:
"""
Extract a list of email addresses from a string.
The string can contain multiple email addresses separated
by any of the following delimiters: ',' or ';'.
:param addresses: A string containing one or more email addresses.
:return: A list of email addresses.
"""
pattern = r"\s*[,;]\s*"
return re.split(pattern, addresses)
|
Extract a list of email addresses from a string.
The string can contain multiple email addresses separated
by any of the following delimiters: ',' or ';'.
:param addresses: A string containing one or more email addresses.
:return: A list of email addresses.
|
python
|
airflow-core/src/airflow/utils/email.py
| 320
|
[
"addresses"
] |
list[str]
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
on_group_start
|
def on_group_start(self, group, **headers) -> dict:
"""Method that is called on group stamping start.
Arguments:
group (group): Group that is stamped.
headers (Dict): Partial headers that could be merged with existing headers.
Returns:
Dict: headers to update.
"""
return {}
|
Method that is called on group stamping start.
Arguments:
group (group): Group that is stamped.
headers (Dict): Partial headers that could be merged with existing headers.
Returns:
Dict: headers to update.
|
python
|
celery/canvas.py
| 124
|
[
"self",
"group"
] |
dict
| true
| 1
| 6.88
|
celery/celery
| 27,741
|
google
| false
|
get_submodule_paths
|
def get_submodule_paths():
'''
Get paths to submodules so that we can exclude them from things like
check_test_name.py, check_unicode.py, etc.
'''
root_directory = os.path.dirname(os.path.dirname(__file__))
gitmodule_file = os.path.join(root_directory, '.gitmodules')
with open(gitmodule_file) as gitmodules:
data = gitmodules.read().split('\n')
submodule_paths = [datum.split(' = ')[1] for datum in data if
datum.startswith('\tpath = ')]
submodule_paths = [os.path.join(root_directory, path) for path in
submodule_paths]
# vendored with a script rather than via gitmodules
with open(
os.path.join(root_directory, ".gitattributes"), "r"
) as attr_file:
for line in attr_file:
if "vendored" in line:
pattern = line.split(" ", 1)[0]
submodule_paths.extend(glob.glob(pattern))
return submodule_paths
|
Get paths to submodules so that we can exclude them from things like
check_test_name.py, check_unicode.py, etc.
|
python
|
tools/get_submodule_paths.py
| 5
|
[] | false
| 3
| 6.08
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
visitCommaListExpression
|
function visitCommaListExpression(node: CommaListExpression) {
// flattened version of `visitCommaExpression`
let pendingExpressions: Expression[] = [];
for (const elem of node.elements) {
if (isBinaryExpression(elem) && elem.operatorToken.kind === SyntaxKind.CommaToken) {
pendingExpressions.push(visitCommaExpression(elem));
}
else {
if (containsYield(elem) && pendingExpressions.length > 0) {
emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
pendingExpressions = [];
}
pendingExpressions.push(Debug.checkDefined(visitNode(elem, visitor, isExpression)));
}
}
return factory.inlineExpressions(pendingExpressions);
}
|
Visits a comma-list expression.
@param node The node to visit.
|
typescript
|
src/compiler/transformers/generators.ts
| 915
|
[
"node"
] | false
| 6
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
getWarnings
|
public List<String> getWarnings() {
List<String> warnings = new ArrayList<>();
for (Header header : response.getHeaders("Warning")) {
String warning = header.getValue();
if (matchWarningHeaderPatternByPrefix(warning)) {
warnings.add(extractWarningValueFromWarningHeader(warning));
} else {
warnings.add(warning);
}
}
return warnings;
}
|
Returns a list of all warning headers returned in the response.
|
java
|
client/rest/src/main/java/org/elasticsearch/client/Response.java
| 176
|
[] | true
| 2
| 7.04
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
wrapper
|
def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]:
"""Wrap the function to enable memoization.
Args:
fn: The function to wrap.
Returns:
A wrapped version of the function.
"""
# If caching is disabled, return the original function unchanged
if not config.IS_CACHING_MODULE_ENABLED():
return fn
# Get the memory-cached version from the memoizer
memory_record_fn = self._memoizer.record(
custom_params_encoder, custom_result_encoder
)(fn)
def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R:
"""Call the original function and cache the result in both caches.
Args:
*args: Positional arguments to pass to the function.
**kwargs: Keyword arguments to pass to the function.
Returns:
The result of calling the original function.
"""
# Call the memory-cached version (which calls fn and caches in memory)
result = memory_record_fn(*args, **kwargs)
# Also store in disk cache
cache_key = self._make_key(custom_params_encoder, *args, **kwargs)
# Get the cache entry from memory cache
# We know it must be there since memory_record_fn just cached it
cached_hit = self._memoizer._cache.get(cache_key)
assert cached_hit, "Cache entry must exist in memory cache"
cache_entry = cast(CacheEntry, cached_hit.value)
# Store the full CacheEntry in disk cache for easier debugging
pickled_entry: bytes = pickle.dumps(cache_entry)
self._disk_cache.insert(cache_key, pickled_entry)
return result
return inner
|
Wrap the function to enable memoization.
Args:
fn: The function to wrap.
Returns:
A wrapped version of the function.
|
python
|
torch/_inductor/runtime/caching/interfaces.py
| 662
|
[
"fn"
] |
Callable[_P, _R]
| true
| 2
| 8.24
|
pytorch/pytorch
| 96,034
|
google
| false
|
_ensure_tensor_ssa
|
def _ensure_tensor_ssa(arg: CuteDSLArg, template_tensor: CuteDSLArg) -> str:
"""
Convert scalar arguments to TensorSSA using cute.full_like if needed.
Args:
arg: The argument to check (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
template_tensor: A tensor argument to use as template for full_like
Returns:
String representation suitable for CuteDSL operations
"""
if isinstance(arg, CSEVariable):
return str(arg)
if isinstance(arg, OpsValue) and isinstance(arg.value, CSEVariable):
return str(arg.value)
if isinstance(template_tensor, CSEVariable):
return f"cute.full_like({template_tensor}, {arg})"
return str(arg)
|
Convert scalar arguments to TensorSSA using cute.full_like if needed.
Args:
arg: The argument to check (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
template_tensor: A tensor argument to use as template for full_like
Returns:
String representation suitable for CuteDSL operations
|
python
|
torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py
| 65
|
[
"arg",
"template_tensor"
] |
str
| true
| 5
| 7.28
|
pytorch/pytorch
| 96,034
|
google
| false
|
sumBy
|
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee, 2))
: 0;
}
|
This method is like `_.sum` except that it accepts `iteratee` which is
invoked for each element in `array` to generate the value to be summed.
The iteratee is invoked with one argument: (value).
@static
@memberOf _
@since 4.0.0
@category Math
@param {Array} array The array to iterate over.
@param {Function} [iteratee=_.identity] The iteratee invoked per element.
@returns {number} Returns the sum.
@example
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, function(o) { return o.n; });
// => 20
// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20
|
javascript
|
lodash.js
| 16,652
|
[
"array",
"iteratee"
] | false
| 3
| 7.52
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
obtainFreshBeanFactory
|
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
|
Tell the subclass to refresh the internal bean factory.
@return the fresh BeanFactory instance
@see #refreshBeanFactory()
@see #getBeanFactory()
|
java
|
spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
| 718
|
[] |
ConfigurableListableBeanFactory
| true
| 1
| 6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
allMatch
|
public boolean allMatch(final FailablePredicate<T, ?> predicate) {
assertNotTerminated();
return stream().allMatch(Failable.asPredicate(predicate));
}
|
Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all
elements if not necessary for determining the result. If the stream is empty then {@code true} is returned and the
predicate is not evaluated.
<p>
This is a short-circuiting terminal operation.
</p>
Note This method evaluates the <em>universal quantification</em> of the predicate over the elements of the stream
(for all x P(x)). If the stream is empty, the quantification is said to be <em>vacuously satisfied</em> and is always
{@code true} (regardless of P(x)).
@param predicate A non-interfering, stateless predicate to apply to elements of this stream
@return {@code true} If either all elements of the stream match the provided predicate or the stream is empty,
otherwise {@code false}.
|
java
|
src/main/java/org/apache/commons/lang3/stream/Streams.java
| 203
|
[
"predicate"
] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
keyOrNull
|
private static <K extends @Nullable Object> @Nullable K keyOrNull(@Nullable Node<K, ?> node) {
return node == null ? null : node.key;
}
|
Returns {@code true} if this BiMap contains an entry whose value is equal to {@code value} (or,
equivalently, if this inverse view contains a key that is equal to {@code value}).
<p>Due to the property that values in a BiMap are unique, this will tend to execute in
faster-than-linear time.
@param value the object to search for in the values of this BiMap
@return true if a mapping exists from a key to the specified value
|
java
|
guava/src/com/google/common/collect/HashBiMap.java
| 805
|
[
"node"
] |
K
| true
| 2
| 7.84
|
google/guava
| 51,352
|
javadoc
| false
|
getMessage
|
public static String getMessage(final Throwable th) {
if (th == null) {
return StringUtils.EMPTY;
}
final String clsName = ClassUtils.getShortClassName(th, null);
return clsName + ": " + StringUtils.defaultString(th.getMessage());
}
|
Gets a short message summarizing the exception.
<p>
The message returned is of the form
{ClassNameWithoutPackage}: {ThrowableMessage}
</p>
@param th the throwable to get a message for, null returns empty string.
@return the message, non-null.
@since 2.2
|
java
|
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
| 292
|
[
"th"
] |
String
| true
| 2
| 7.92
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
getNamedFormat
|
function getNamedFormat(locale: string, format: string): string {
const localeId = getLocaleId(locale);
NAMED_FORMATS[localeId] ??= {};
if (NAMED_FORMATS[localeId][format]) {
return NAMED_FORMATS[localeId][format];
}
let formatValue = '';
switch (format) {
case 'shortDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Short);
break;
case 'mediumDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Medium);
break;
case 'longDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Long);
break;
case 'fullDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Full);
break;
case 'shortTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Short);
break;
case 'mediumTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium);
break;
case 'longTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Long);
break;
case 'fullTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Full);
break;
case 'short':
const shortTime = getNamedFormat(locale, 'shortTime');
const shortDate = getNamedFormat(locale, 'shortDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [
shortTime,
shortDate,
]);
break;
case 'medium':
const mediumTime = getNamedFormat(locale, 'mediumTime');
const mediumDate = getNamedFormat(locale, 'mediumDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [
mediumTime,
mediumDate,
]);
break;
case 'long':
const longTime = getNamedFormat(locale, 'longTime');
const longDate = getNamedFormat(locale, 'longDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [
longTime,
longDate,
]);
break;
case 'full':
const fullTime = getNamedFormat(locale, 'fullTime');
const fullDate = getNamedFormat(locale, 'fullDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [
fullTime,
fullDate,
]);
break;
}
if (formatValue) {
NAMED_FORMATS[localeId][format] = formatValue;
}
return formatValue;
}
|
Create a new Date object with the given date value, and the time set to midnight.
We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999.
See: https://github.com/angular/angular/issues/40377
Note that this function returns a Date object whose time is midnight in the current locale's
timezone. In the future we might want to change this to be midnight in UTC, but this would be a
considerable breaking change.
|
typescript
|
packages/common/src/i18n/format_date.ts
| 190
|
[
"locale",
"format"
] | true
| 3
| 6.96
|
angular/angular
| 99,544
|
jsdoc
| false
|
|
add_defaults
|
def add_defaults(self, fun):
"""Add default configuration from dict ``d``.
If the argument is a callable function then it will be regarded
as a promise, and it won't be loaded until the configuration is
actually needed.
This method can be compared to:
.. code-block:: pycon
>>> celery.conf.update(d)
with a difference that 1) no copy will be made and 2) the dict will
not be transferred when the worker spawns child processes, so
it's important that the same configuration happens at import time
when pickle restores the object on the other side.
"""
if not callable(fun):
d, fun = fun, lambda: d
if self.configured:
return self._conf.add_defaults(fun())
self._pending_defaults.append(fun)
|
Add default configuration from dict ``d``.
If the argument is a callable function then it will be regarded
as a promise, and it won't be loaded until the configuration is
actually needed.
This method can be compared to:
.. code-block:: pycon
>>> celery.conf.update(d)
with a difference that 1) no copy will be made and 2) the dict will
not be transferred when the worker spawns child processes, so
it's important that the same configuration happens at import time
when pickle restores the object on the other side.
|
python
|
celery/app/base.py
| 653
|
[
"self",
"fun"
] | false
| 3
| 6.32
|
celery/celery
| 27,741
|
unknown
| false
|
|
make_lookup_key
|
def make_lookup_key(
self, kernel_inputs: KernelInputs, op_name: str, include_device: bool = False
) -> Optional[str]:
"""
Create a flattened lookup key from kernel inputs and operation name.
Override this method to customize key generation.
Args:
kernel_inputs: KernelInputs object containing input nodes and scalars
op_name: Operation name (e.g., "mm", "addmm")
include_device: Whether to include device key in the generated key
Returns:
A string key combining device (optional), operation, and input information
"""
device = kernel_inputs.device()
dev_key = self._get_device_key(device)
if dev_key is None:
# The system does not run when dev_key is None, regardless of
# whether include_device is True or False
return None
if not include_device:
dev_key = None
# Generate input key using our staticmethod
input_key = self._generate_kernel_inputs_key(kernel_inputs)
# Create the flattened lookup key
if dev_key is not None:
key_parts = [dev_key, input_key, op_name]
else:
key_parts = [input_key, op_name]
return "+".join(key_parts)
|
Create a flattened lookup key from kernel inputs and operation name.
Override this method to customize key generation.
Args:
kernel_inputs: KernelInputs object containing input nodes and scalars
op_name: Operation name (e.g., "mm", "addmm")
include_device: Whether to include device key in the generated key
Returns:
A string key combining device (optional), operation, and input information
|
python
|
torch/_inductor/lookup_table/choices.py
| 90
|
[
"self",
"kernel_inputs",
"op_name",
"include_device"
] |
Optional[str]
| true
| 5
| 7.6
|
pytorch/pytorch
| 96,034
|
google
| false
|
powFast
|
private static double powFast(double value, int power) {
if (power > 5) { // Most common case first.
double oddRemains = 1.0;
do {
// Test if power is odd.
if ((power & 1) != 0) {
oddRemains *= value;
}
value *= value;
power >>= 1; // power = power / 2
} while (power > 5);
// Here, power is in [3,5]: faster to finish outside the loop.
if (power == 3) {
return oddRemains * value * value * value;
} else {
double v2 = value * value;
if (power == 4) {
return oddRemains * v2 * v2;
} else { // power == 5
return oddRemains * v2 * v2 * value;
}
}
} else if (power >= 0) { // power in [0,5]
if (power < 3) { // power in [0,2]
if (power == 2) { // Most common case first.
return value * value;
} else if (power != 0) { // faster than == 1
return value;
} else { // power == 0
return 1.0;
}
} else { // power in [3,5]
if (power == 3) {
return value * value * value;
} else { // power in [4,5]
double v2 = value * value;
if (power == 4) {
return v2 * v2;
} else { // power == 5
return v2 * v2 * value;
}
}
}
} else { // power < 0
// Opposite of Integer.MIN_VALUE does not exist as int.
if (power == Integer.MIN_VALUE) {
// Integer.MAX_VALUE = -(power+1)
return 1.0 / (FastMath.powFast(value, Integer.MAX_VALUE) * value);
} else {
return 1.0 / FastMath.powFast(value, -power);
}
}
}
|
This treatment is somehow accurate for low values of |power|,
and for |power*getExponent(value)| < 1023 or so (to stay away
from double extreme magnitudes (large and small)).
@param value A double value.
@param power A power.
@return value^power.
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/FastMath.java
| 609
|
[
"value",
"power"
] | true
| 12
| 8
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
openInputStream
|
private synchronized InputStream openInputStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else {
// requireNonNull is safe because we always have either `file` or `memory`.
requireNonNull(memory);
return new ByteArrayInputStream(memory.getBuffer(), 0, memory.getCount());
}
}
|
Returns a readable {@link ByteSource} view of the data that has been written to this stream.
@since 15.0
|
java
|
android/guava/src/com/google/common/io/FileBackedOutputStream.java
| 165
|
[] |
InputStream
| true
| 2
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
validate
|
@SuppressWarnings("unchecked")
@Override
public Map<Integer, Object> validate(Object item) {
try {
NavigableMap<Integer, Object> objects = (NavigableMap<Integer, Object>) item;
for (Map.Entry<Integer, Object> entry : objects.entrySet()) {
Integer tag = entry.getKey();
Field field = fields.get(tag);
if (field == null) {
if (!(entry.getValue() instanceof RawTaggedField)) {
throw new SchemaException("The value associated with tag " + tag +
" must be a RawTaggedField in this version of the software.");
}
} else {
field.type.validate(entry.getValue());
}
}
return objects;
} catch (ClassCastException e) {
throw new SchemaException("Not a NavigableMap. Found class " + item.getClass().getSimpleName());
}
}
|
Create a new TaggedFields object with the given tags and fields.
@param fields This is an array containing Integer tags followed
by associated Field objects.
@return The new {@link TaggedFields}
|
java
|
clients/src/main/java/org/apache/kafka/common/protocol/types/TaggedFields.java
| 147
|
[
"item"
] | true
| 4
| 7.92
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
isCglibProxy
|
@Contract("null -> false")
public static boolean isCglibProxy(@Nullable Object object) {
return (object instanceof SpringProxy &&
object.getClass().getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR));
}
|
Check whether the given object is a CGLIB proxy.
<p>This method goes beyond the implementation of
{@link ClassUtils#isCglibProxy(Object)} by additionally checking if
the given object is an instance of {@link SpringProxy}.
@param object the object to check
@see ClassUtils#isCglibProxy(Object)
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
| 108
|
[
"object"
] | true
| 2
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
maximumWeight
|
@GwtIncompatible // To be supported
@CanIgnoreReturnValue
public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
checkState(
this.maximumWeight == UNSET_INT,
"maximum weight was already set to %s",
this.maximumWeight);
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
this.maximumWeight = maximumWeight;
return this;
}
|
Specifies the maximum weight of entries the cache may contain. Weight is determined using the
{@link Weigher} specified with {@link #weigher}, and use of this method requires a
corresponding call to {@link #weigher} prior to calling {@link #build}.
<p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
resulting segment inside the cache <i>independently</i> limits its own weight to approximately
{@code maximumWeight / concurrencyLevel}.
<p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
For example, the cache may evict an entry because it hasn't been used recently or very often.
<p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
into cache. This can be useful in testing, or to disable caching temporarily.
<p>Note that weight is only used to determine whether the cache is over capacity; it has no
effect on selecting which entry should be evicted next.
<p>This feature cannot be used in conjunction with {@link #maximumSize}.
@param maximumWeight the maximum total weight of entries the cache may contain
@return this {@code CacheBuilder} instance (for chaining)
@throws IllegalArgumentException if {@code maximumWeight} is negative
@throws IllegalStateException if a maximum weight or size was already set
@since 11.0
|
java
|
android/guava/src/com/google/common/cache/CacheBuilder.java
| 535
|
[
"maximumWeight"
] | true
| 1
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
create
|
public static <O> ReentrantLockVisitor<O> create(final O object, final ReentrantLock reentrantLock) {
return new LockingVisitors.ReentrantLockVisitor<>(object, reentrantLock);
}
|
Creates a new instance of {@link ReentrantLockVisitor} with the given object and lock.
@param <O> The type of the object to protect.
@param object The object to protect.
@param reentrantLock The lock to use.
@return A new {@link ReentrantLockVisitor}.
@see LockingVisitors
@since 3.18.0
|
java
|
src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
| 709
|
[
"object",
"reentrantLock"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
parse
|
Date parse(String source) throws ParseException;
|
Equivalent to DateFormat.parse(String).
See {@link java.text.DateFormat#parse(String)} for more information.
@param source A {@link String} whose beginning should be parsed.
@return A {@link Date} parsed from the string.
@throws ParseException if the beginning of the specified string cannot be parsed.
|
java
|
src/main/java/org/apache/commons/lang3/time/DateParser.java
| 73
|
[
"source"
] |
Date
| true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
select_key
|
def select_key(
self,
key: str,
bucket_name: str | None = None,
expression: str | None = None,
expression_type: str | None = None,
input_serialization: dict[str, Any] | None = None,
output_serialization: dict[str, Any] | None = None,
) -> str:
"""
Read a key with S3 Select.
.. seealso::
- :external+boto3:py:meth:`S3.Client.select_object_content`
:param key: S3 key that will point to the file
:param bucket_name: Name of the bucket in which the file is stored
:param expression: S3 Select expression
:param expression_type: S3 Select expression type
:param input_serialization: S3 Select input data serialization format
:param output_serialization: S3 Select output data serialization format
:return: retrieved subset of original data by S3 Select
"""
expression = expression or "SELECT * FROM S3Object"
expression_type = expression_type or "SQL"
extra_args = {}
if input_serialization is None:
input_serialization = {"CSV": {}}
if output_serialization is None:
output_serialization = {"CSV": {}}
if self._requester_pays:
extra_args["RequestPayer"] = "requester"
response = self.get_conn().select_object_content(
Bucket=bucket_name,
Key=key,
Expression=expression,
ExpressionType=expression_type,
InputSerialization=input_serialization,
OutputSerialization=output_serialization,
ExtraArgs=extra_args,
)
return b"".join(
event["Records"]["Payload"] for event in response["Payload"] if "Records" in event
).decode("utf-8")
|
Read a key with S3 Select.
.. seealso::
- :external+boto3:py:meth:`S3.Client.select_object_content`
:param key: S3 key that will point to the file
:param bucket_name: Name of the bucket in which the file is stored
:param expression: S3 Select expression
:param expression_type: S3 Select expression type
:param input_serialization: S3 Select input data serialization format
:param output_serialization: S3 Select output data serialization format
:return: retrieved subset of original data by S3 Select
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py
| 1,084
|
[
"self",
"key",
"bucket_name",
"expression",
"expression_type",
"input_serialization",
"output_serialization"
] |
str
| true
| 6
| 7.44
|
apache/airflow
| 43,597
|
sphinx
| false
|
subscriptionPattern
|
public synchronized SubscriptionPattern subscriptionPattern() {
if (hasRe2JPatternSubscription())
return this.subscribedRe2JPattern;
return null;
}
|
@return The RE2J compatible pattern in use, provided via a call to
{@link #subscribe(SubscriptionPattern, Optional)}.
Null if there is no SubscriptionPattern in use.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
| 380
|
[] |
SubscriptionPattern
| true
| 2
| 7.44
|
apache/kafka
| 31,560
|
javadoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.