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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
getLoggerForInvocation
|
protected Log getLoggerForInvocation(MethodInvocation invocation) {
if (this.defaultLogger != null) {
return this.defaultLogger;
}
else {
Object target = invocation.getThis();
Assert.state(target != null, "Target must not be null");
return LogFactory.getLog(getClassForLogging(target));
}
}
|
Return the appropriate {@code Log} instance to use for the given
{@code MethodInvocation}. If the {@code useDynamicLogger} flag
is set, the {@code Log} instance will be for the target class of the
{@code MethodInvocation}, otherwise the {@code Log} will be the
default static logger.
@param invocation the {@code MethodInvocation} being traced
@return the {@code Log} instance to use
@see #setUseDynamicLogger
|
java
|
spring-aop/src/main/java/org/springframework/aop/interceptor/AbstractTraceInterceptor.java
| 147
|
[
"invocation"
] |
Log
| true
| 2
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
hasEntry
|
public boolean hasEntry(CharSequence namePrefix, CharSequence name) {
int nameHash = nameHash(namePrefix, name);
int lookupIndex = getFirstLookupIndex(nameHash);
int size = size();
while (lookupIndex >= 0 && lookupIndex < size && this.nameHashLookups[lookupIndex] == nameHash) {
long pos = getCentralDirectoryFileHeaderRecordPos(lookupIndex);
ZipCentralDirectoryFileHeaderRecord centralRecord = loadZipCentralDirectoryFileHeaderRecord(pos);
if (hasName(lookupIndex, centralRecord, pos, namePrefix, name)) {
return true;
}
lookupIndex++;
}
return false;
}
|
Return if an entry with the given name exists.
@param namePrefix an optional prefix for the name
@param name the name of the entry to find
@return the entry or {@code null}
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java
| 231
|
[
"namePrefix",
"name"
] | true
| 5
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
withFilter
|
public SELF withFilter(Filter<C, A> filter) {
Assert.notNull(filter, "'filter' must not be null");
this.filter = filter;
return self();
}
|
Use a specific filter to determine when a callback should apply. If no explicit
filter is set filter will be attempted using the generic type on the callback
type.
@param filter the filter to use
@return this instance
@since 3.4.8
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java
| 152
|
[
"filter"
] |
SELF
| true
| 1
| 7.04
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
enter
|
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public boolean enter(long time, TimeUnit unit) {
long timeoutNanos = toSafeNanos(time, unit);
ReentrantLock lock = this.lock;
if (!fair && lock.tryLock()) {
return true;
}
boolean interrupted = Thread.interrupted();
try {
long startTime = System.nanoTime();
for (long remainingNanos = timeoutNanos; ; ) {
try {
return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException interrupt) {
interrupted = true;
remainingNanos = remainingNanos(startTime, timeoutNanos);
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
|
Enters this monitor. Blocks at most the given time.
@return whether the monitor was entered
|
java
|
android/guava/src/com/google/common/util/concurrent/Monitor.java
| 403
|
[
"time",
"unit"
] | true
| 6
| 7.04
|
google/guava
| 51,352
|
javadoc
| false
|
|
postProcessEnvironment
|
public static void postProcessEnvironment(ConfigurableEnvironment environment,
ConfigurableEnvironment parentEnvironment) {
PropertySource<?> parentSystemEnvironmentPropertySource = parentEnvironment.getPropertySources()
.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
if (parentSystemEnvironmentPropertySource instanceof OriginAwareSystemEnvironmentPropertySource parentOriginAwareSystemEnvironmentPropertySource) {
new SystemEnvironmentPropertySourceEnvironmentPostProcessor().postProcessEnvironment(environment,
parentOriginAwareSystemEnvironmentPropertySource.getPrefix());
}
}
|
Post-process the given {@link ConfigurableEnvironment} by copying appropriate
settings from a parent {@link ConfigurableEnvironment}.
@param environment the environment to post-process
@param parentEnvironment the parent environment
@since 3.4.12
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/support/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java
| 93
|
[
"environment",
"parentEnvironment"
] |
void
| true
| 2
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
nextRequest
|
synchronized TxnRequestHandler nextRequest(boolean hasIncompleteBatches) {
if (!newPartitionsInTransaction.isEmpty())
enqueueRequest(addPartitionsToTransactionHandler());
TxnRequestHandler nextRequestHandler = pendingRequests.peek();
if (nextRequestHandler == null)
return null;
// Do not send the EndTxn until all batches have been flushed
if (nextRequestHandler.isEndTxn() && hasIncompleteBatches)
return null;
pendingRequests.poll();
if (maybeTerminateRequestWithError(nextRequestHandler)) {
log.trace("Not sending transactional request {} because we are in an error state",
nextRequestHandler.requestBuilder());
return null;
}
if (nextRequestHandler.isEndTxn() && !transactionStarted) {
nextRequestHandler.result.done();
if (currentState != State.FATAL_ERROR) {
if (isTransactionV2Enabled) {
log.debug("Not sending EndTxn for completed transaction since no send " +
"or sendOffsetsToTransaction were triggered");
} else {
log.debug("Not sending EndTxn for completed transaction since no partitions " +
"or offsets were successfully added");
}
resetTransactionState();
}
nextRequestHandler = pendingRequests.poll();
}
if (nextRequestHandler != null)
log.trace("Request {} dequeued for sending", nextRequestHandler.requestBuilder());
return nextRequestHandler;
}
|
Returns the first inflight sequence for a given partition. This is the base sequence of an inflight batch with
the lowest sequence number.
@return the lowest inflight sequence if the transaction manager is tracking inflight requests for this partition.
If there are no inflight requests being tracked for this partition, this method will return
RecordBatch.NO_SEQUENCE.
|
java
|
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
| 896
|
[
"hasIncompleteBatches"
] |
TxnRequestHandler
| true
| 11
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
close
|
@Override
public void close() throws IOException {
if (currentUsages.updateAndGet(current -> current > 0 ? current - 1 : current + 1) == -1) {
doShutdown();
}
}
|
Prepares the database for lookup by incrementing the usage count.
If the usage count is already negative, it indicates that the database is being closed,
and this method will return false to indicate that no lookup should be performed.
@return true if the database is ready for lookup, false if it is being closed
|
java
|
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseReaderLazyLoader.java
| 105
|
[] |
void
| true
| 3
| 8.08
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
_putmask
|
def _putmask(self, mask: npt.NDArray[np.bool_], value) -> None:
"""
Analogue to np.putmask(self, mask, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
If listlike, must be arraylike with same length as self.
Returns
-------
None
Notes
-----
Unlike np.putmask, we do not repeat listlike values with mismatched length.
'value' should either be a scalar or an arraylike with the same length
as self.
"""
if is_list_like(value):
val = value[mask]
else:
val = value
self[mask] = val
|
Analogue to np.putmask(self, mask, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
If listlike, must be arraylike with same length as self.
Returns
-------
None
Notes
-----
Unlike np.putmask, we do not repeat listlike values with mismatched length.
'value' should either be a scalar or an arraylike with the same length
as self.
|
python
|
pandas/core/arrays/base.py
| 2,489
|
[
"self",
"mask",
"value"
] |
None
| true
| 3
| 6.88
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
packDibit
|
public static void packDibit(int[] vector, byte[] packed) {
if (packed.length * Byte.SIZE / 2 < vector.length) {
throw new IllegalArgumentException("packed array is too small: " + packed.length * Byte.SIZE / 2 + " < " + vector.length);
}
IMPL.packDibit(vector, packed);
}
|
Packs the provided int array populated with "0" and "1" values into a byte array.
@param vector the int array to pack, must contain only "0" and "1" values.
@param packed the byte array to store the packed result, must be large enough to hold the packed data.
|
java
|
libs/simdvec/src/main/java/org/elasticsearch/simdvec/ESVectorUtil.java
| 396
|
[
"vector",
"packed"
] |
void
| true
| 2
| 7.04
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
render_template_string
|
def render_template_string(
template_string: str,
context: dict[str, Any],
autoescape: bool = True,
keep_trailing_newline: bool = False,
) -> str:
"""
Renders template based on its name. Reads the template from <name> file in the current dir.
:param template_string: string of the template to use
:param context: Jinja2 context
:param autoescape: Whether to autoescape HTML
:param keep_trailing_newline: Whether to keep the newline in rendered output
:return: rendered template
"""
import jinja2
template = jinja2.Environment(
loader=BaseLoader(),
undefined=jinja2.StrictUndefined,
autoescape=autoescape,
keep_trailing_newline=keep_trailing_newline,
).from_string(template_string)
content: str = template.render(context)
return content
|
Renders template based on its name. Reads the template from <name> file in the current dir.
:param template_string: string of the template to use
:param context: Jinja2 context
:param autoescape: Whether to autoescape HTML
:param keep_trailing_newline: Whether to keep the newline in rendered output
:return: rendered template
|
python
|
dev/prepare_bulk_issues.py
| 81
|
[
"template_string",
"context",
"autoescape",
"keep_trailing_newline"
] |
str
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
onFailure
|
@Override
public @Nullable Object onFailure(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Exception error) throws Exception {
if (context.getDepth() == 0 && error instanceof ConverterNotFoundException) {
return null;
}
throw error;
}
|
Create a new {@link IgnoreTopLevelConverterNotFoundBindHandler} instance with a
specific parent.
@param parent the parent handler
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandler.java
| 52
|
[
"name",
"target",
"context",
"error"
] |
Object
| true
| 3
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
create
|
private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) {
SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository();
repository.add(metadata.getSources());
for (ConfigurationMetadataItem item : metadata.getItems()) {
ConfigurationMetadataSource source = metadata.getSource(item);
repository.add(item, source);
}
Map<String, ConfigurationMetadataProperty> allProperties = repository.getAllProperties();
for (ConfigurationMetadataHint hint : metadata.getHints()) {
ConfigurationMetadataProperty property = allProperties.get(hint.getId());
if (property != null) {
addValueHints(property, hint);
}
else {
String id = hint.resolveId();
property = allProperties.get(id);
if (property != null) {
if (hint.isMapKeyHints()) {
addMapHints(property, hint);
}
else {
addValueHints(property, hint);
}
}
}
}
return repository;
}
|
Build a {@link ConfigurationMetadataRepository} with the current state of this
builder.
@return this builder
|
java
|
configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java
| 107
|
[
"metadata"
] |
SimpleConfigurationMetadataRepository
| true
| 4
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
nanargmin
|
def nanargmin(a, axis=None, out=None, *, keepdims=np._NoValue):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
.. versionadded:: 1.22.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> import numpy as np
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
if mask is not None and mask.size:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
res = np.argmin(a, axis=axis, out=out, keepdims=keepdims)
return res
|
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
.. versionadded:: 1.22.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> import numpy as np
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
|
python
|
numpy/lib/_nanfunctions_impl.py
| 511
|
[
"a",
"axis",
"out",
"keepdims"
] | false
| 4
| 7.52
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
groupToSubframes
|
function groupToSubframes(
valuesByGroupKey: Map<string, FieldMap>,
options: GroupToNestedTableTransformerOptions
): DataFrame[][] {
const subFrames: DataFrame[][] = [];
// Construct a subframe of any fields
// that aren't being group on or reduced
for (const [, value] of valuesByGroupKey) {
const nestedFields: Field[] = [];
for (const [fieldName, field] of Object.entries(value)) {
const fieldOpts = options.fields[fieldName];
if (fieldOpts === undefined) {
nestedFields.push(field);
}
// Depending on the configuration form state all of the following are possible
else if (
fieldOpts.aggregations === undefined ||
(fieldOpts.operation === GroupByOperationID.aggregate && fieldOpts.aggregations.length === 0) ||
fieldOpts.operation === null ||
fieldOpts.operation === undefined
) {
nestedFields.push(field);
}
}
// If there are any values in the subfields
// push a new subframe with the fields
// otherwise push an empty frame
if (nestedFields.length > 0) {
subFrames.push([createSubframe(nestedFields, nestedFields[0].values.length, options)]);
} else {
subFrames.push([createSubframe([], 0, options)]);
}
}
return subFrames;
}
|
Group values into subframes so that they'll be displayed
inside of a subtable.
@param valuesByGroupKey
A mapping of group keys to their respective grouped values.
@param options
Transformation options, which are used to find ungrouped/unaggregated fields.
@returns
|
typescript
|
packages/grafana-data/src/transformations/transformers/groupToNestedTable.ts
| 210
|
[
"valuesByGroupKey",
"options"
] | true
| 10
| 7.76
|
grafana/grafana
| 71,362
|
jsdoc
| false
|
|
patch_lazy_xp_functions
|
def patch_lazy_xp_functions(
request: pytest.FixtureRequest,
monkeypatch: pytest.MonkeyPatch | None = None,
*,
xp: ModuleType,
) -> contextlib.AbstractContextManager[None]:
"""
Test lazy execution of functions tagged with :func:`lazy_xp_function`.
If ``xp==jax.numpy``, search for all functions which have been tagged with
:func:`lazy_xp_function` in the globals of the module that defines the current test,
as well as in the ``lazy_xp_modules`` list in the globals of the same module,
and wrap them with :func:`jax.jit`. Unwrap them at the end of the test.
If ``xp==dask.array``, wrap the functions with a decorator that disables
``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised
eagerly.
This function should be typically called by your library's `xp` fixture that runs
tests on multiple backends::
@pytest.fixture(params=[
numpy,
array_api_strict,
pytest.param(jax.numpy, marks=pytest.mark.thread_unsafe),
pytest.param(dask.array, marks=pytest.mark.thread_unsafe),
])
def xp(request):
with patch_lazy_xp_functions(request, xp=request.param):
yield request.param
but it can be otherwise be called by the test itself too.
Parameters
----------
request : pytest.FixtureRequest
Pytest fixture, as acquired by the test itself or by one of its fixtures.
monkeypatch : pytest.MonkeyPatch
Deprecated
xp : array_namespace
Array namespace to be tested.
See Also
--------
lazy_xp_function : Tag a function to be tested on lazy backends.
pytest.FixtureRequest : `request` test function parameter.
Notes
-----
This context manager monkey-patches modules and as such is thread unsafe
on Dask and JAX. If you run your test suite with
`pytest-run-parallel <https://github.com/Quansight-Labs/pytest-run-parallel/>`_,
you should mark these backends with ``@pytest.mark.thread_unsafe``, as shown in
the example above.
"""
mod = cast(ModuleType, request.module)
mods = [mod, *cast(list[ModuleType], getattr(mod, "lazy_xp_modules", []))]
to_revert: list[tuple[ModuleType, str, object]] = []
def temp_setattr(mod: ModuleType, name: str, func: object) -> None:
"""
Variant of monkeypatch.setattr, which allows monkey-patching only selected
parameters of a test so that pytest-run-parallel can run on the remainder.
"""
assert hasattr(mod, name)
to_revert.append((mod, name, getattr(mod, name)))
setattr(mod, name, func)
if monkeypatch is not None:
warnings.warn(
(
"The `monkeypatch` parameter is deprecated and will be removed in a "
"future version. "
"Use `patch_lazy_xp_function` as a context manager instead."
),
DeprecationWarning,
stacklevel=2,
)
# Enable using patch_lazy_xp_function not as a context manager
temp_setattr = monkeypatch.setattr # type: ignore[assignment] # pyright: ignore[reportAssignmentType]
def iter_tagged() -> Iterator[
tuple[ModuleType, str, Callable[..., Any], dict[str, Any]]
]:
for mod in mods:
for name, func in mod.__dict__.items():
tags: dict[str, Any] | None = None
with contextlib.suppress(AttributeError):
tags = func._lazy_xp_function # pylint: disable=protected-access
if tags is None:
with contextlib.suppress(KeyError, TypeError):
tags = _ufuncs_tags[func]
if tags is not None:
yield mod, name, func, tags
if is_dask_namespace(xp):
for mod, name, func, tags in iter_tagged():
n = tags["allow_dask_compute"]
if n is True:
n = 1_000_000
elif n is False:
n = 0
wrapped = _dask_wrap(func, n)
temp_setattr(mod, name, wrapped)
elif is_jax_namespace(xp):
for mod, name, func, tags in iter_tagged():
if tags["jax_jit"]:
wrapped = jax_autojit(func)
temp_setattr(mod, name, wrapped)
# We can't just decorate patch_lazy_xp_functions with
# @contextlib.contextmanager because it would not work with the
# deprecated monkeypatch when not used as a context manager.
@contextlib.contextmanager
def revert_on_exit() -> Generator[None]:
try:
yield
finally:
for mod, name, orig_func in to_revert:
setattr(mod, name, orig_func)
return revert_on_exit()
|
Test lazy execution of functions tagged with :func:`lazy_xp_function`.
If ``xp==jax.numpy``, search for all functions which have been tagged with
:func:`lazy_xp_function` in the globals of the module that defines the current test,
as well as in the ``lazy_xp_modules`` list in the globals of the same module,
and wrap them with :func:`jax.jit`. Unwrap them at the end of the test.
If ``xp==dask.array``, wrap the functions with a decorator that disables
``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised
eagerly.
This function should be typically called by your library's `xp` fixture that runs
tests on multiple backends::
@pytest.fixture(params=[
numpy,
array_api_strict,
pytest.param(jax.numpy, marks=pytest.mark.thread_unsafe),
pytest.param(dask.array, marks=pytest.mark.thread_unsafe),
])
def xp(request):
with patch_lazy_xp_functions(request, xp=request.param):
yield request.param
but it can be otherwise be called by the test itself too.
Parameters
----------
request : pytest.FixtureRequest
Pytest fixture, as acquired by the test itself or by one of its fixtures.
monkeypatch : pytest.MonkeyPatch
Deprecated
xp : array_namespace
Array namespace to be tested.
See Also
--------
lazy_xp_function : Tag a function to be tested on lazy backends.
pytest.FixtureRequest : `request` test function parameter.
Notes
-----
This context manager monkey-patches modules and as such is thread unsafe
on Dask and JAX. If you run your test suite with
`pytest-run-parallel <https://github.com/Quansight-Labs/pytest-run-parallel/>`_,
you should mark these backends with ``@pytest.mark.thread_unsafe``, as shown in
the example above.
|
python
|
sklearn/externals/array_api_extra/testing.py
| 218
|
[
"request",
"monkeypatch",
"xp"
] |
contextlib.AbstractContextManager[None]
| true
| 14
| 6.32
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
runGc
|
@SuppressForbidden(reason = "we need to request a system GC for the benchmark")
private void runGc() {
long previousCollections = getTotalGcCount();
int attempts = 0;
do {
// request a full GC ...
System.gc();
// ... and give GC a chance to run
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
attempts++;
} while (previousCollections == getTotalGcCount() || attempts < 5);
}
|
Requests a full GC and checks whether the GC did actually run after a request. It retries up to 5 times in case the GC did not
run in time.
|
java
|
client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java
| 148
|
[] |
void
| true
| 3
| 7.04
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
notBlank
|
public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) {
Objects.requireNonNull(chars, toSupplier(message, values));
if (StringUtils.isBlank(chars)) {
throw new IllegalArgumentException(getMessage(message, values));
}
return chars;
}
|
Validates that the specified argument character sequence is not {@link StringUtils#isBlank(CharSequence) blank} (whitespaces, empty ({@code ""}) or
{@code null}); otherwise throwing an exception with the specified message.
<pre>
Validate.notBlank(myString, "The string must not be blank");
</pre>
@param <T> the character sequence type.
@param chars the character sequence to check, validated not null by this method.
@param message the {@link String#format(String, Object...)} exception message if invalid, not null.
@param values the optional values for the formatted exception message, null array not recommended.
@return the validated character sequence (never {@code null} method for chaining).
@throws NullPointerException if the character sequence is {@code null}.
@throws IllegalArgumentException if the character sequence is blank.
@see #notBlank(CharSequence)
@see StringUtils#isBlank(CharSequence)
@since 3.0
|
java
|
src/main/java/org/apache/commons/lang3/Validate.java
| 803
|
[
"chars",
"message"
] |
T
| true
| 2
| 7.6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
equals
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ConsumerGroupListing)) return false;
ConsumerGroupListing that = (ConsumerGroupListing) o;
return isSimpleConsumerGroup() == that.isSimpleConsumerGroup() &&
Objects.equals(groupId, that.groupId) &&
Objects.equals(groupState, that.groupState) &&
Objects.equals(type, that.type);
}
|
The type of the consumer group.
@return An Optional containing the type, if available.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/ConsumerGroupListing.java
| 170
|
[
"o"
] | true
| 6
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
createMergingDigest
|
public static MergingDigest createMergingDigest(TDigestArrays arrays, double compression) {
return MergingDigest.create(arrays, compression);
}
|
Creates an {@link MergingDigest}. This is the fastest implementation for large sample populations, with constant memory
allocation while delivering relating accuracy close to 1%.
@param compression The compression parameter. 100 is a common value for normal uses. 1000 is extremely large.
The number of centroids retained will be a smallish (usually less than 10) multiple of this number.
@return the MergingDigest
|
java
|
libs/tdigest/src/main/java/org/elasticsearch/tdigest/TDigest.java
| 55
|
[
"arrays",
"compression"
] |
MergingDigest
| true
| 1
| 6.64
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
send_email
|
def send_email(
self,
mail_from: str,
to: str | Iterable[str],
subject: str,
html_content: str,
files: list[str] | None = None,
cc: str | Iterable[str] | None = None,
bcc: str | Iterable[str] | None = None,
mime_subtype: str = "mixed",
mime_charset: str = "utf-8",
reply_to: str | None = None,
return_path: str | None = None,
custom_headers: dict[str, Any] | None = None,
) -> dict:
"""
Send email using Amazon Simple Email Service.
.. seealso::
- :external+boto3:py:meth:`SES.Client.send_raw_email`
:param mail_from: Email address to set as email's from
:param to: List of email addresses to set as email's to
:param subject: Email's subject
:param html_content: Content of email in HTML format
:param files: List of paths of files to be attached
:param cc: List of email addresses to set as email's CC
:param bcc: List of email addresses to set as email's BCC
:param mime_subtype: Can be used to specify the subtype of the message. Default = mixed
:param mime_charset: Email's charset. Default = UTF-8.
:param return_path: The email address to which replies will be sent. By default, replies
are sent to the original sender's email address.
:param reply_to: The email address to which message bounces and complaints should be sent.
"Return-Path" is sometimes called "envelope from", "envelope sender", or "MAIL FROM".
:param custom_headers: Additional headers to add to the MIME message.
No validations are run on these values, and they should be able to be encoded.
:return: Response from Amazon SES service with unique message identifier.
"""
custom_headers = self._build_headers(custom_headers, reply_to, return_path)
message, recipients = build_mime_message(
mail_from=mail_from,
to=to,
subject=subject,
html_content=html_content,
files=files,
cc=cc,
bcc=bcc,
mime_subtype=mime_subtype,
mime_charset=mime_charset,
custom_headers=custom_headers,
)
return self.conn.send_raw_email(
Source=mail_from, Destinations=recipients, RawMessage={"Data": message.as_string()}
)
|
Send email using Amazon Simple Email Service.
.. seealso::
- :external+boto3:py:meth:`SES.Client.send_raw_email`
:param mail_from: Email address to set as email's from
:param to: List of email addresses to set as email's to
:param subject: Email's subject
:param html_content: Content of email in HTML format
:param files: List of paths of files to be attached
:param cc: List of email addresses to set as email's CC
:param bcc: List of email addresses to set as email's BCC
:param mime_subtype: Can be used to specify the subtype of the message. Default = mixed
:param mime_charset: Email's charset. Default = UTF-8.
:param return_path: The email address to which replies will be sent. By default, replies
are sent to the original sender's email address.
:param reply_to: The email address to which message bounces and complaints should be sent.
"Return-Path" is sometimes called "envelope from", "envelope sender", or "MAIL FROM".
:param custom_headers: Additional headers to add to the MIME message.
No validations are run on these values, and they should be able to be encoded.
:return: Response from Amazon SES service with unique message identifier.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/ses.py
| 59
|
[
"self",
"mail_from",
"to",
"subject",
"html_content",
"files",
"cc",
"bcc",
"mime_subtype",
"mime_charset",
"reply_to",
"return_path",
"custom_headers"
] |
dict
| true
| 1
| 6.64
|
apache/airflow
| 43,597
|
sphinx
| false
|
equals
|
public abstract boolean equals(CharSequence cs1, CharSequence cs2);
|
Compares two CharSequences, returning {@code true} if they represent equal sequences of characters.
<p>
{@code null}s are handled without exceptions. Two {@code null} references are considered to be equal.
</p>
<p>
Case-sensitive examples
</p>
<pre>
Strings.CS.equals(null, null) = true
Strings.CS.equals(null, "abc") = false
Strings.CS.equals("abc", null) = false
Strings.CS.equals("abc", "abc") = true
Strings.CS.equals("abc", "ABC") = false
</pre>
<p>
Case-insensitive examples
</p>
<pre>
Strings.CI.equals(null, null) = true
Strings.CI.equals(null, "abc") = false
Strings.CI.equals("abc", null) = false
Strings.CI.equals("abc", "abc") = true
Strings.CI.equals("abc", "ABC") = true
</pre>
@param cs1 the first CharSequence, may be {@code null}
@param cs2 the second CharSequence, may be {@code null}
@return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
@see Object#equals(Object)
@see String#compareTo(String)
@see String#equalsIgnoreCase(String)
|
java
|
src/main/java/org/apache/commons/lang3/Strings.java
| 682
|
[
"cs1",
"cs2"
] | true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
remove
|
@CanIgnoreReturnValue
@Override
public @Nullable V remove(@Nullable Object key) {
Node<K, V> node = seekByKey(key, smearedHash(key));
if (node == null) {
return null;
} else {
delete(node);
node.prevInKeyInsertionOrder = null;
node.nextInKeyInsertionOrder = null;
return node.value;
}
}
|
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
| 415
|
[
"key"
] |
V
| true
| 2
| 7.92
|
google/guava
| 51,352
|
javadoc
| false
|
__init__
|
def __init__(self, dropout=0.0):
r"""Processes a projected query and key-value pair to apply
scaled dot product attention.
Args:
dropout (float): probability of dropping an attention weight.
Examples::
>>> SDP = torchtext.models.ScaledDotProduct(0.1)
>>> q = torch.randn(256, 21, 3)
>>> k = v = torch.randn(256, 21, 3)
>>> attn_output, attn_weights = SDP(q, k, v)
>>> print(attn_output.shape, attn_weights.shape)
torch.Size([256, 21, 3]) torch.Size([256, 21, 21])
"""
super().__init__()
self.dropout = dropout
|
r"""Processes a projected query and key-value pair to apply
scaled dot product attention.
Args:
dropout (float): probability of dropping an attention weight.
Examples::
>>> SDP = torchtext.models.ScaledDotProduct(0.1)
>>> q = torch.randn(256, 21, 3)
>>> k = v = torch.randn(256, 21, 3)
>>> attn_output, attn_weights = SDP(q, k, v)
>>> print(attn_output.shape, attn_weights.shape)
torch.Size([256, 21, 3]) torch.Size([256, 21, 21])
|
python
|
benchmarks/functional_autograd_benchmark/torchaudio_models.py
| 568
|
[
"self",
"dropout"
] | false
| 1
| 6
|
pytorch/pytorch
| 96,034
|
google
| false
|
|
equals
|
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof SimpleKey that && Arrays.deepEquals(this.params, that.params)));
}
|
Create a new {@link SimpleKey} instance.
@param elements the elements of the key
|
java
|
spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java
| 64
|
[
"other"
] | true
| 3
| 6.64
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
of
|
static Parameters of(String... descriptions) {
return new Parameters(descriptions);
}
|
Factory method used to create a new {@link Parameters} instance with specific
descriptions.
@param descriptions the parameter descriptions
@return a new {@link Parameters} instance with the given descriptions
|
java
|
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/Command.java
| 194
|
[] |
Parameters
| true
| 1
| 6.32
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
asTokenizer
|
public StrTokenizer asTokenizer() {
return new StrBuilderTokenizer();
}
|
Creates a tokenizer that can tokenize the contents of this builder.
<p>
This method allows the contents of this builder to be tokenized.
The tokenizer will be setup by default to tokenize on space, tab,
newline and formfeed (as per StringTokenizer). These values can be
changed on the tokenizer class, before retrieving the tokens.
</p>
<p>
The returned tokenizer is linked to this builder. You may intermix
calls to the builder and tokenizer within certain limits, however
there is no synchronization. Once the tokenizer has been used once,
it must be {@link StrTokenizer#reset() reset} to pickup the latest
changes in the builder. For example:
</p>
<pre>
StrBuilder b = new StrBuilder();
b.append("a b ");
StrTokenizer t = b.asTokenizer();
String[] tokens1 = t.getTokenArray(); // returns a,b
b.append("c d ");
String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
t.reset(); // reset causes builder changes to be picked up
String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
</pre>
<p>
In addition to simply intermixing appends and tokenization, you can also
call the set methods on the tokenizer to alter how it tokenizes. Just
remember to call reset when you want to pickup builder changes.
</p>
<p>
Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])}
with a non-null value will break the link with the builder.
</p>
@return a tokenizer that is linked to this builder
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 1,526
|
[] |
StrTokenizer
| true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
mappings
|
private static XContentBuilder mappings() {
try {
return jsonBuilder().startObject()
.startObject(SINGLE_MAPPING_NAME)
.startObject("_meta")
.field("version", LEGACY_VERSION_FIELD_VALUE)
.field(SystemIndexDescriptor.VERSION_META_KEY, GEOIP_INDEX_MAPPINGS_VERSION)
.endObject()
.field("dynamic", "strict")
.startObject("properties")
.startObject("name")
.field("type", "keyword")
.endObject()
.startObject("chunk")
.field("type", "integer")
.endObject()
.startObject("data")
.field("type", "binary")
.endObject()
.endObject()
.endObject()
.endObject();
} catch (IOException e) {
throw new UncheckedIOException("Failed to build mappings for " + DATABASES_INDEX, e);
}
}
|
No longer used for determining the age of mappings, but system index descriptor
code requires <em>something</em> be set. We use a value that can be parsed by
old nodes in mixed-version clusters, just in case any old code exists that
tries to parse <code>version</code> from index metadata, and that will indicate
to these old nodes that the mappings are newer than they are.
|
java
|
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IngestGeoIpPlugin.java
| 299
|
[] |
XContentBuilder
| true
| 2
| 6.88
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
_get_cython_vals
|
def _get_cython_vals(self, values: np.ndarray) -> np.ndarray:
"""
Cast numeric dtypes to float64 for functions that only support that.
Parameters
----------
values : np.ndarray
Returns
-------
values : np.ndarray
"""
how = self.how
if how in ["median", "std", "sem", "skew", "kurt"]:
# median only has a float64 implementation
# We should only get here with is_numeric, as non-numeric cases
# should raise in _get_cython_function
values = ensure_float64(values)
elif values.dtype.kind in "iu":
if how in ["var", "mean"] or (
self.kind == "transform" and self.has_dropped_na
):
# has_dropped_na check need for test_null_group_str_transformer
# result may still include NaN, so we have to cast
values = ensure_float64(values)
elif how in ["sum", "ohlc", "prod", "cumsum", "cumprod"]:
# Avoid overflow during group op
if values.dtype.kind == "i":
values = ensure_int64(values)
else:
values = ensure_uint64(values)
return values
|
Cast numeric dtypes to float64 for functions that only support that.
Parameters
----------
values : np.ndarray
Returns
-------
values : np.ndarray
|
python
|
pandas/core/groupby/ops.py
| 214
|
[
"self",
"values"
] |
np.ndarray
| true
| 9
| 6.88
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
at
|
public @Nullable V at(int rowIndex, int columnIndex) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
return array[rowIndex][columnIndex];
}
|
Returns the value corresponding to the specified row and column indices. The same value is
returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
method runs more quickly.
@param rowIndex position of the row key in {@link #rowKeyList()}
@param columnIndex position of the row key in {@link #columnKeyList()}
@return the value with the specified row and column
@throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
to the number of allowed column keys
|
java
|
android/guava/src/com/google/common/collect/ArrayTable.java
| 323
|
[
"rowIndex",
"columnIndex"
] |
V
| true
| 1
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
allowChildToHandleSigInt
|
private boolean allowChildToHandleSigInt() {
Process process = this.process;
if (process == null) {
return true;
}
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
if (!process.isAlive()) {
return true;
}
try {
Thread.sleep(500);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
return false;
}
|
Return if the process was stopped.
@return {@code true} if stopped
|
java
|
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java
| 124
|
[] | true
| 5
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
metadataTopics
|
synchronized Set<String> metadataTopics() {
if (groupSubscription.isEmpty())
return subscription;
else if (groupSubscription.containsAll(subscription))
return groupSubscription;
else {
// When subscription changes `groupSubscription` may be outdated, ensure that
// new subscription topics are returned.
Set<String> topics = new HashSet<>(groupSubscription);
topics.addAll(subscription);
return topics;
}
}
|
Get the subscription topics for which metadata is required. For the leader, this will include
the union of the subscriptions of all group members. For followers, it is just that member's
subscription. This is used when querying topic metadata to detect the metadata changes which would
require rebalancing. The leader fetches metadata for all topics in the group so that it
can do the partition assignment (which requires at least partition counts for all topics
to be assigned).
@return The union of all subscribed topics in the group if this member is the leader
of the current generation; otherwise it returns the same set as {@link #subscription()}
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
| 408
|
[] | true
| 3
| 8.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
getSystemTrustStore
|
private KeyStore getSystemTrustStore() {
if (isPkcs11Truststore(systemProperties) && trustStorePassword != null) {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS11");
keyStore.load(null, trustStorePassword);
return keyStore;
} catch (GeneralSecurityException | IOException e) {
throw new SslConfigException("failed to load the system PKCS#11 truststore", e);
}
}
return null;
}
|
When a PKCS#11 token is used as the system default keystore/truststore, we need to pass the keystore
password when loading, even for reading certificates only ( as opposed to i.e. JKS keystores where
we only need to pass the password for reading Private Key entries ).
@return the KeyStore used as truststore for PKCS#11 initialized with the password, null otherwise
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java
| 79
|
[] |
KeyStore
| true
| 4
| 7.92
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
tril
|
def tril(m, k=0):
"""
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
For arrays with ``ndim`` exceeding 2, `tril` will apply to the final two
axes.
Parameters
----------
m : array_like, shape (..., M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
tril : ndarray, shape (..., M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu : same thing, only for the upper triangle
Examples
--------
>>> import numpy as np
>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
>>> np.tril(np.arange(3*4*5).reshape(3, 4, 5))
array([[[ 0, 0, 0, 0, 0],
[ 5, 6, 0, 0, 0],
[10, 11, 12, 0, 0],
[15, 16, 17, 18, 0]],
[[20, 0, 0, 0, 0],
[25, 26, 0, 0, 0],
[30, 31, 32, 0, 0],
[35, 36, 37, 38, 0]],
[[40, 0, 0, 0, 0],
[45, 46, 0, 0, 0],
[50, 51, 52, 0, 0],
[55, 56, 57, 58, 0]]])
"""
m = asanyarray(m)
mask = tri(*m.shape[-2:], k=k, dtype=bool)
return where(mask, m, zeros(1, m.dtype))
|
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
For arrays with ``ndim`` exceeding 2, `tril` will apply to the final two
axes.
Parameters
----------
m : array_like, shape (..., M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
tril : ndarray, shape (..., M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu : same thing, only for the upper triangle
Examples
--------
>>> import numpy as np
>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
>>> np.tril(np.arange(3*4*5).reshape(3, 4, 5))
array([[[ 0, 0, 0, 0, 0],
[ 5, 6, 0, 0, 0],
[10, 11, 12, 0, 0],
[15, 16, 17, 18, 0]],
[[20, 0, 0, 0, 0],
[25, 26, 0, 0, 0],
[30, 31, 32, 0, 0],
[35, 36, 37, 38, 0]],
[[40, 0, 0, 0, 0],
[45, 46, 0, 0, 0],
[50, 51, 52, 0, 0],
[55, 56, 57, 58, 0]]])
|
python
|
numpy/lib/_twodim_base_impl.py
| 455
|
[
"m",
"k"
] | false
| 1
| 6.48
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
_math_mode_with_parentheses
|
def _math_mode_with_parentheses(s: str) -> str:
r"""
All characters in LaTeX math mode are preserved.
The substrings in LaTeX math mode, which start with
the character ``\(`` and end with ``\)``, are preserved
without escaping. Otherwise regular LaTeX escaping applies.
Parameters
----------
s : str
Input to be escaped
Return
------
str :
Escaped string
"""
s = s.replace(r"\(", r"LEFT§=§6yzLEFT").replace(r"\)", r"RIGHTab5§=§RIGHT")
res = []
for item in re.split(r"LEFT§=§6yz|ab5§=§RIGHT", s):
if item.startswith("LEFT") and item.endswith("RIGHT"):
res.append(item.replace("LEFT", r"\(").replace("RIGHT", r"\)"))
elif "LEFT" in item and "RIGHT" in item:
res.append(
_escape_latex(item).replace("LEFT", r"\(").replace("RIGHT", r"\)")
)
else:
res.append(
_escape_latex(item)
.replace("LEFT", r"\textbackslash (")
.replace("RIGHT", r"\textbackslash )")
)
return "".join(res)
|
r"""
All characters in LaTeX math mode are preserved.
The substrings in LaTeX math mode, which start with
the character ``\(`` and end with ``\)``, are preserved
without escaping. Otherwise regular LaTeX escaping applies.
Parameters
----------
s : str
Input to be escaped
Return
------
str :
Escaped string
|
python
|
pandas/io/formats/style_render.py
| 2,612
|
[
"s"
] |
str
| true
| 7
| 6.72
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
isEligibleAttribute
|
protected boolean isEligibleAttribute(Attr attribute, ParserContext parserContext) {
String fullName = attribute.getName();
return (!fullName.equals("xmlns") && !fullName.startsWith("xmlns:") &&
isEligibleAttribute(parserContext.getDelegate().getLocalName(attribute)));
}
|
Determine whether the given attribute is eligible for being
turned into a corresponding bean property value.
<p>The default implementation considers any attribute as eligible,
except for the "id" attribute and namespace declaration attributes.
@param attribute the XML attribute to check
@param parserContext the {@code ParserContext}
@see #isEligibleAttribute(String)
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java
| 150
|
[
"attribute",
"parserContext"
] | true
| 3
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
describe_endpoint
|
def describe_endpoint(self, name: str) -> dict:
"""
Get the description of an endpoint.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_endpoint`
:param name: the name of the endpoint
:return: A dict contains all the endpoint info
"""
return self.get_conn().describe_endpoint(EndpointName=name)
|
Get the description of an endpoint.
.. seealso::
- :external+boto3:py:meth:`SageMaker.Client.describe_endpoint`
:param name: the name of the endpoint
:return: A dict contains all the endpoint info
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 700
|
[
"self",
"name"
] |
dict
| true
| 1
| 6.4
|
apache/airflow
| 43,597
|
sphinx
| false
|
_rewrite_assign
|
def _rewrite_assign(tok: tuple[int, str]) -> tuple[int, str]:
"""
Rewrite the assignment operator for PyTables expressions that use ``=``
as a substitute for ``==``.
Parameters
----------
tok : tuple of int, str
ints correspond to the all caps constants in the tokenize module
Returns
-------
tuple of int, str
Either the input or token or the replacement values
"""
toknum, tokval = tok
return toknum, "==" if tokval == "=" else tokval
|
Rewrite the assignment operator for PyTables expressions that use ``=``
as a substitute for ``==``.
Parameters
----------
tok : tuple of int, str
ints correspond to the all caps constants in the tokenize module
Returns
-------
tuple of int, str
Either the input or token or the replacement values
|
python
|
pandas/core/computation/expr.py
| 55
|
[
"tok"
] |
tuple[int, str]
| true
| 2
| 6.56
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
toStringArray
|
public static String[] toStringArray(final Object[] array, final String valueForNullElements) {
if (null == array) {
return null;
}
if (array.length == 0) {
return EMPTY_STRING_ARRAY;
}
return map(array, String.class, e -> Objects.toString(e, valueForNullElements));
}
|
Returns an array containing the string representation of each element in the argument array handling {@code null} elements.
<p>
This method returns {@code null} for a {@code null} input array.
</p>
@param array the Object[] to be processed, may be {@code null}.
@param valueForNullElements the value to insert if {@code null} is found.
@return a {@link String} array, {@code null} if null array input.
@since 3.6
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 9,298
|
[
"array",
"valueForNullElements"
] | true
| 3
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
_json_to_enum
|
def _json_to_enum(cls, json_dict: Optional[str], enum_class: Any) -> Optional[Enum]:
"""Convert JSON string to enum value.
Format: {name: "EnumName", value: 1}
Args:
json_dict: JSON string representation
enum_class: Target enum class
Returns:
Optional[Enum]: Reconstructed enum value or None
"""
if json_dict is None:
return None
enum_dict = json.loads(json_dict)
return enum_class[enum_dict["name"]]
|
Convert JSON string to enum value.
Format: {name: "EnumName", value: 1}
Args:
json_dict: JSON string representation
enum_class: Target enum class
Returns:
Optional[Enum]: Reconstructed enum value or None
|
python
|
torch/_inductor/codegen/cuda/serialization.py
| 483
|
[
"cls",
"json_dict",
"enum_class"
] |
Optional[Enum]
| true
| 2
| 7.44
|
pytorch/pytorch
| 96,034
|
google
| false
|
appendEndTxnMarker
|
public void appendEndTxnMarker(long timestamp, EndTransactionMarker marker) {
if (producerId == RecordBatch.NO_PRODUCER_ID)
throw new IllegalArgumentException("End transaction marker requires a valid producerId");
if (!isTransactional)
throw new IllegalArgumentException("End transaction marker depends on batch transactional flag being enabled");
ByteBuffer value = marker.serializeValue();
appendControlRecord(timestamp, marker.controlType(), value);
}
|
Append a control record at the next sequential offset.
@param timestamp The record timestamp
@param type The control record type (cannot be UNKNOWN)
@param value The control record value
|
java
|
clients/src/main/java/org/apache/kafka/common/record/MemoryRecordsBuilder.java
| 621
|
[
"timestamp",
"marker"
] |
void
| true
| 3
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
truncate
|
def truncate(self, before=None, after=None) -> MultiIndex:
"""
Slice index between two labels / tuples, return new MultiIndex.
Parameters
----------
before : label or tuple, can be partial. Default None
None defaults to start.
after : label or tuple, can be partial. Default None
None defaults to end.
Returns
-------
MultiIndex
The truncated MultiIndex.
See Also
--------
DataFrame.truncate : Truncate a DataFrame before and after some index values.
Series.truncate : Truncate a Series before and after some index values.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays([["a", "b", "c"], ["x", "y", "z"]])
>>> mi
MultiIndex([('a', 'x'), ('b', 'y'), ('c', 'z')],
)
>>> mi.truncate(before="a", after="b")
MultiIndex([('a', 'x'), ('b', 'y')],
)
"""
if after and before and after < before:
raise ValueError("after < before")
i, j = self.levels[0].slice_locs(before, after)
left, right = self.slice_locs(before, after)
new_levels = list(self.levels)
new_levels[0] = new_levels[0][i:j]
new_codes = [level_codes[left:right] for level_codes in self.codes]
new_codes[0] = new_codes[0] - i
return MultiIndex(
levels=new_levels,
codes=new_codes,
names=self._names,
verify_integrity=False,
)
|
Slice index between two labels / tuples, return new MultiIndex.
Parameters
----------
before : label or tuple, can be partial. Default None
None defaults to start.
after : label or tuple, can be partial. Default None
None defaults to end.
Returns
-------
MultiIndex
The truncated MultiIndex.
See Also
--------
DataFrame.truncate : Truncate a DataFrame before and after some index values.
Series.truncate : Truncate a Series before and after some index values.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays([["a", "b", "c"], ["x", "y", "z"]])
>>> mi
MultiIndex([('a', 'x'), ('b', 'y'), ('c', 'z')],
)
>>> mi.truncate(before="a", after="b")
MultiIndex([('a', 'x'), ('b', 'y')],
)
|
python
|
pandas/core/indexes/multi.py
| 3,947
|
[
"self",
"before",
"after"
] |
MultiIndex
| true
| 4
| 8.32
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
assocIndexOf
|
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
|
Gets the index at which the `key` is found in `array` of key-value pairs.
@private
@param {Array} array The array to inspect.
@param {*} key The key to search for.
@returns {number} Returns the index of the matched value, else `-1`.
|
javascript
|
lodash.js
| 2,529
|
[
"array",
"key"
] | false
| 3
| 6.24
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
createException
|
private ReportableException createException(String url, ClassicHttpResponse httpResponse) {
StatusLine statusLine = new StatusLine(httpResponse);
String message = "Initializr service call failed using '" + url + "' - service returned "
+ statusLine.getReasonPhrase();
String error = extractMessage(httpResponse.getEntity());
if (StringUtils.hasText(error)) {
message += ": '" + error + "'";
}
else {
int statusCode = statusLine.getStatusCode();
message += " (unexpected " + statusCode + " error)";
}
throw new ReportableException(message);
}
|
Retrieves the meta-data of the service at the specified URL.
@param url the URL
@return the response
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
| 196
|
[
"url",
"httpResponse"
] |
ReportableException
| true
| 2
| 8.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
from_tuples
|
def from_tuples(
cls,
data,
closed: IntervalClosedType | None = "right",
copy: bool = False,
dtype: Dtype | None = None,
) -> Self:
"""
Construct an IntervalArray from an array-like of tuples.
Parameters
----------
data : array-like (1-dimensional)
Array of tuples.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
or neither.
copy : bool, default False
By-default copy the data, this is compat only and ignored.
dtype : dtype or None, default None
If None, dtype will be inferred.
Returns
-------
IntervalArray
See Also
--------
interval_range : Function to create a fixed frequency IntervalIndex.
IntervalArray.from_arrays : Construct an IntervalArray from a left and
right array.
IntervalArray.from_breaks : Construct an IntervalArray from an array of
splits.
Examples
--------
>>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
<IntervalArray>
[(0, 1], (1, 2]]
Length: 2, dtype: interval[int64, right]
"""
if len(data):
left, right = [], []
else:
# ensure that empty data keeps input dtype
left = right = data
for d in data:
if not isinstance(d, tuple) and isna(d):
lhs = rhs = np.nan
else:
name = cls.__name__
try:
# need list of length 2 tuples, e.g. [(0, 1), (1, 2), ...]
lhs, rhs = d
except ValueError as err:
msg = f"{name}.from_tuples requires tuples of length 2, got {d}"
raise ValueError(msg) from err
except TypeError as err:
msg = f"{name}.from_tuples received an invalid item, {d}"
raise TypeError(msg) from err
left.append(lhs)
right.append(rhs)
return cls.from_arrays(left, right, closed, copy=False, dtype=dtype)
|
Construct an IntervalArray from an array-like of tuples.
Parameters
----------
data : array-like (1-dimensional)
Array of tuples.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
or neither.
copy : bool, default False
By-default copy the data, this is compat only and ignored.
dtype : dtype or None, default None
If None, dtype will be inferred.
Returns
-------
IntervalArray
See Also
--------
interval_range : Function to create a fixed frequency IntervalIndex.
IntervalArray.from_arrays : Construct an IntervalArray from a left and
right array.
IntervalArray.from_breaks : Construct an IntervalArray from an array of
splits.
Examples
--------
>>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
<IntervalArray>
[(0, 1], (1, 2]]
Length: 2, dtype: interval[int64, right]
|
python
|
pandas/core/arrays/interval.py
| 688
|
[
"cls",
"data",
"closed",
"copy",
"dtype"
] |
Self
| true
| 7
| 8.08
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
topicId
|
public Uuid topicId() {
return topicId;
}
|
@return Universally unique id representing this topic partition.
|
java
|
clients/src/main/java/org/apache/kafka/common/TopicIdPartition.java
| 56
|
[] |
Uuid
| true
| 1
| 6.16
|
apache/kafka
| 31,560
|
javadoc
| false
|
SynchronizedScrollContainer
|
function SynchronizedScrollContainer({
className,
children,
scaleRef,
}: {
className?: string,
children?: React.Node,
scaleRef: {current: number},
}) {
const bridge = useContext(BridgeContext);
const ref = useRef(null);
const applyingScrollRef = useRef(false);
// TODO: useEffectEvent
function scrollContainerTo({
left,
top,
right,
bottom,
}: {
left: number,
top: number,
right: number,
bottom: number,
}): void {
const element = ref.current;
if (element === null) {
return;
}
const scale = scaleRef.current / element.clientWidth;
const targetLeft = Math.round(left / scale);
const targetTop = Math.round(top / scale);
if (
targetLeft !== Math.round(element.scrollLeft) ||
targetTop !== Math.round(element.scrollTop)
) {
// Disable scroll events until we've applied the new scroll position.
applyingScrollRef.current = true;
element.scrollTo({
left: targetLeft,
top: targetTop,
behavior: 'smooth',
});
}
}
useEffect(() => {
const callback = scrollContainerTo;
bridge.addListener('scrollTo', callback);
// Ask for the current scroll position when we mount so we can attach ourselves to it.
bridge.send('requestScrollPosition');
return () => bridge.removeListener('scrollTo', callback);
}, [bridge]);
const scrollTimer = useRef<null | TimeoutID>(null);
// TODO: useEffectEvent
function sendScroll() {
if (scrollTimer.current) {
clearTimeout(scrollTimer.current);
scrollTimer.current = null;
}
if (applyingScrollRef.current) {
return;
}
const element = ref.current;
if (element === null) {
return;
}
const scale = scaleRef.current / element.clientWidth;
const left = element.scrollLeft * scale;
const top = element.scrollTop * scale;
const right = left + element.clientWidth * scale;
const bottom = top + element.clientHeight * scale;
bridge.send('scrollTo', {left, top, right, bottom});
}
// TODO: useEffectEvent
function throttleScroll() {
if (!scrollTimer.current) {
// Periodically synchronize the scroll while scrolling.
scrollTimer.current = setTimeout(sendScroll, 400);
}
}
function scrollEnd() {
// Upon scrollend send it immediately.
sendScroll();
applyingScrollRef.current = false;
}
useEffect(() => {
const element = ref.current;
if (element === null) {
return;
}
const scrollCallback = throttleScroll;
const scrollEndCallback = scrollEnd;
element.addEventListener('scroll', scrollCallback);
element.addEventListener('scrollend', scrollEndCallback);
return () => {
element.removeEventListener('scroll', scrollCallback);
element.removeEventListener('scrollend', scrollEndCallback);
};
}, [ref]);
return (
<div className={className} ref={ref}>
{children}
</div>
);
}
|
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@flow
|
javascript
|
packages/react-devtools-shared/src/devtools/views/SuspenseTab/SuspenseTab.js
| 162
|
[] | false
| 10
| 6.16
|
facebook/react
| 241,750
|
jsdoc
| false
|
|
getDefaultLocale
|
protected @Nullable Locale getDefaultLocale() {
if (this.defaultLocale != null) {
return this.defaultLocale;
}
if (this.fallbackToSystemLocale) {
return Locale.getDefault();
}
return null;
}
|
Determine a default Locale to fall back to: either a locally specified default
Locale or the system Locale, or {@code null} for no fallback locale at all.
@since 5.2.2
@see #setDefaultLocale
@see #setFallbackToSystemLocale
@see Locale#getDefault()
|
java
|
spring-context/src/main/java/org/springframework/context/support/AbstractResourceBasedMessageSource.java
| 188
|
[] |
Locale
| true
| 3
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
unicodeSize
|
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
|
Gets the size of a Unicode `string`.
@private
@param {string} string The string inspect.
@returns {number} Returns the string size.
|
javascript
|
lodash.js
| 1,387
|
[
"string"
] | false
| 2
| 6.08
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
getSpringConfigLocations
|
protected String[] getSpringConfigLocations() {
String[] locations = getStandardConfigLocations();
for (int i = 0; i < locations.length; i++) {
String extension = StringUtils.getFilenameExtension(locations[i]);
int extensionLength = (extension != null) ? (extension.length() + 1) : 0;
locations[i] = locations[i].substring(0, locations[i].length() - extensionLength) + "-spring." + extension;
}
return locations;
}
|
Return the spring config locations for this system. By default this method returns
a set of locations based on {@link #getStandardConfigLocations()}.
@return the spring config locations
@see #getSpringInitializationConfig()
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java
| 134
|
[] | true
| 3
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
downgrade
|
def downgrade():
"""Unapply Change value column type to longblob in xcom table for mysql."""
conn = op.get_bind()
if conn.dialect.name == "mysql":
with op.batch_alter_table("xcom", schema=None) as batch_op:
batch_op.alter_column("value", type_=sa.LargeBinary)
|
Unapply Change value column type to longblob in xcom table for mysql.
|
python
|
airflow-core/src/airflow/migrations/versions/0013_2_9_0_make_xcom_value_to_longblob_for_mysql.py
| 50
|
[] | false
| 2
| 6.24
|
apache/airflow
| 43,597
|
unknown
| false
|
|
equals
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListTransactionsOptions that = (ListTransactionsOptions) o;
return Objects.equals(filteredStates, that.filteredStates) &&
Objects.equals(filteredProducerIds, that.filteredProducerIds) &&
Objects.equals(filteredDuration, that.filteredDuration) &&
Objects.equals(filteredTransactionalIdPattern, that.filteredTransactionalIdPattern);
}
|
Returns transactional ID being filtered.
@return the current transactional ID pattern filter (empty means no transactional IDs are filtered and all
transactions will be returned)
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/ListTransactionsOptions.java
| 137
|
[
"o"
] | true
| 7
| 6.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
nullToEmpty
|
static String nullToEmpty(@Nullable String string) {
return (string == null) ? "" : string;
}
|
Returns the string if it is not null, or an empty string otherwise.
@param string the string to test and possibly return
@return {@code string} if it is not null; {@code ""} otherwise
|
java
|
android/guava/src/com/google/common/base/Platform.java
| 67
|
[
"string"
] |
String
| true
| 2
| 8.16
|
google/guava
| 51,352
|
javadoc
| false
|
difference
|
public static <K extends @Nullable Object, V extends @Nullable Object>
MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
@SuppressWarnings("unchecked")
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
return difference(sortedLeft, right);
}
return difference(left, right, Equivalence.equals());
}
|
Computes the difference between two maps. This difference is an immutable snapshot of the state
of the maps at the time this method is called. It will never change, even if the maps change at
a later time.
<p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
<p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code
left.equals(right)} instead of this method.
@param left the map to treat as the "left" map for purposes of comparison
@param right the map to treat as the "right" map for purposes of comparison
@return the difference between the two maps
|
java
|
android/guava/src/com/google/common/collect/Maps.java
| 474
|
[
"left",
"right"
] | true
| 2
| 8.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
_message_with_time
|
def _message_with_time(source, message, time):
"""Create one line message for logging purposes.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str
Short message.
time : int
Time in seconds.
"""
start_message = "[%s] " % source
# adapted from joblib.logger.short_format_time without the Windows -.1s
# adjustment
if time > 60:
time_str = "%4.1fmin" % (time / 60)
else:
time_str = " %5.1fs" % time
end_message = " %s, total=%s" % (message, time_str)
dots_len = 70 - len(start_message) - len(end_message)
return "%s%s%s" % (start_message, dots_len * ".", end_message)
|
Create one line message for logging purposes.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str
Short message.
time : int
Time in seconds.
|
python
|
sklearn/utils/_user_interface.py
| 8
|
[
"source",
"message",
"time"
] | false
| 3
| 6.24
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
run
|
ExitStatus run(String... args) throws Exception;
|
Run the command.
@param args command arguments (this will not include the command itself)
@return the outcome of the command
@throws Exception if the command fails
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/Command.java
| 82
|
[] |
ExitStatus
| true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
addMigration
|
private void addMigration(ConfigurationPropertySource propertySource,
ConfigurationMetadataProperty metadataProperty, ConfigurationPropertyName propertyName,
boolean mapMigration, List<PropertyMigration> migrations) {
ConfigurationProperty property = propertySource.getConfigurationProperty(propertyName);
if (property != null) {
ConfigurationMetadataProperty replacement = determineReplacementMetadata(metadataProperty);
if (replacement == null || !hasSameName(property, replacement)) {
migrations.add(new PropertyMigration(property, metadataProperty, replacement, mapMigration));
}
}
}
|
Analyse the {@link ConfigurableEnvironment environment} and attempt to rename
legacy properties if a replacement exists.
@return a report of the migration
|
java
|
core/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java
| 140
|
[
"propertySource",
"metadataProperty",
"propertyName",
"mapMigration",
"migrations"
] |
void
| true
| 4
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
hist_series
|
def hist_series(
self: Series,
by=None,
ax=None,
grid: bool = True,
xlabelsize: int | None = None,
xrot: float | None = None,
ylabelsize: int | None = None,
yrot: float | None = None,
figsize: tuple[int, int] | None = None,
bins: int | Sequence[int] = 10,
backend: str | None = None,
legend: bool = False,
**kwargs,
):
"""
Draw histogram of the input series using matplotlib.
Parameters
----------
by : object, optional
If passed, then used to form histograms for separate groups.
ax : matplotlib axis object
If not passed, uses gca().
grid : bool, default True
Whether to show axis grid lines.
xlabelsize : int, default None
If specified changes the x-axis label size.
xrot : float, default None
Rotation of x axis labels.
ylabelsize : int, default None
If specified changes the y-axis label size.
yrot : float, default None
Rotation of y axis labels.
figsize : tuple, default None
Figure size in inches by default.
bins : int or sequence, default 10
Number of histogram bins to be used. If an integer is given, bins + 1
bin edges are calculated and returned. If bins is a sequence, gives
bin edges, including left edge of first bin and right edge of last
bin. In this case, bins is returned unmodified.
backend : str, default None
Backend to use instead of the backend specified in the option
``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
specify the ``plotting.backend`` for the whole session, set
``pd.options.plotting.backend``.
legend : bool, default False
Whether to show the legend.
**kwargs
To be passed to the actual plotting function.
Returns
-------
matplotlib.axes.Axes
A histogram plot.
See Also
--------
matplotlib.axes.Axes.hist : Plot a histogram using matplotlib.
Examples
--------
For Series:
.. plot::
:context: close-figs
>>> lst = ["a", "a", "a", "b", "b", "b"]
>>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
>>> hist = ser.hist()
For Groupby:
.. plot::
:context: close-figs
>>> lst = ["a", "a", "a", "b", "b", "b"]
>>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
>>> hist = ser.groupby(level=0).hist()
"""
plot_backend = _get_plot_backend(backend)
return plot_backend.hist_series(
self,
by=by,
ax=ax,
grid=grid,
xlabelsize=xlabelsize,
xrot=xrot,
ylabelsize=ylabelsize,
yrot=yrot,
figsize=figsize,
bins=bins,
legend=legend,
**kwargs,
)
|
Draw histogram of the input series using matplotlib.
Parameters
----------
by : object, optional
If passed, then used to form histograms for separate groups.
ax : matplotlib axis object
If not passed, uses gca().
grid : bool, default True
Whether to show axis grid lines.
xlabelsize : int, default None
If specified changes the x-axis label size.
xrot : float, default None
Rotation of x axis labels.
ylabelsize : int, default None
If specified changes the y-axis label size.
yrot : float, default None
Rotation of y axis labels.
figsize : tuple, default None
Figure size in inches by default.
bins : int or sequence, default 10
Number of histogram bins to be used. If an integer is given, bins + 1
bin edges are calculated and returned. If bins is a sequence, gives
bin edges, including left edge of first bin and right edge of last
bin. In this case, bins is returned unmodified.
backend : str, default None
Backend to use instead of the backend specified in the option
``plotting.backend``. For instance, 'matplotlib'. Alternatively, to
specify the ``plotting.backend`` for the whole session, set
``pd.options.plotting.backend``.
legend : bool, default False
Whether to show the legend.
**kwargs
To be passed to the actual plotting function.
Returns
-------
matplotlib.axes.Axes
A histogram plot.
See Also
--------
matplotlib.axes.Axes.hist : Plot a histogram using matplotlib.
Examples
--------
For Series:
.. plot::
:context: close-figs
>>> lst = ["a", "a", "a", "b", "b", "b"]
>>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
>>> hist = ser.hist()
For Groupby:
.. plot::
:context: close-figs
>>> lst = ["a", "a", "a", "b", "b", "b"]
>>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst)
>>> hist = ser.groupby(level=0).hist()
|
python
|
pandas/plotting/_core.py
| 50
|
[
"self",
"by",
"ax",
"grid",
"xlabelsize",
"xrot",
"ylabelsize",
"yrot",
"figsize",
"bins",
"backend",
"legend"
] | true
| 1
| 7.2
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
radius_neighbors_graph
|
def radius_neighbors_graph(
self, X=None, radius=None, mode="connectivity", sort_results=False
):
"""Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query point or points.
If not provided, neighbors of each indexed point are returned.
In this case, the query point is not considered its own neighbor.
radius : float, default=None
Radius of neighborhoods. The default is the value passed to the
constructor.
mode : {'connectivity', 'distance'}, default='connectivity'
Type of returned matrix: 'connectivity' will return the
connectivity matrix with ones and zeros, in 'distance' the
edges are distances between points, type of distance
depends on the selected metric parameter in
NearestNeighbors class.
sort_results : bool, default=False
If True, in each row of the result, the non-zero entries will be
sorted by increasing distances. If False, the non-zero entries may
not be sorted. Only used with mode='distance'.
.. versionadded:: 0.22
Returns
-------
A : sparse-matrix of shape (n_queries, n_samples_fit)
`n_samples_fit` is the number of samples in the fitted data.
`A[i, j]` gives the weight of the edge connecting `i` to `j`.
The matrix is of CSR format.
See Also
--------
kneighbors_graph : Compute the (weighted) graph of k-Neighbors for
points in X.
Examples
--------
>>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(radius=1.5)
>>> neigh.fit(X)
NearestNeighbors(radius=1.5)
>>> A = neigh.radius_neighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
[0., 1., 0.],
[1., 0., 1.]])
"""
check_is_fitted(self)
# check the input only in self.radius_neighbors
if radius is None:
radius = self.radius
# construct CSR matrix representation of the NN graph
if mode == "connectivity":
A_ind = self.radius_neighbors(X, radius, return_distance=False)
A_data = None
elif mode == "distance":
dist, A_ind = self.radius_neighbors(
X, radius, return_distance=True, sort_results=sort_results
)
A_data = np.concatenate(list(dist))
else:
raise ValueError(
'Unsupported mode, must be one of "connectivity", '
f'or "distance" but got "{mode}" instead'
)
n_queries = A_ind.shape[0]
n_samples_fit = self.n_samples_fit_
n_neighbors = np.array([len(a) for a in A_ind])
A_ind = np.concatenate(list(A_ind))
if A_data is None:
A_data = np.ones(len(A_ind))
A_indptr = np.concatenate((np.zeros(1, dtype=int), np.cumsum(n_neighbors)))
return csr_matrix((A_data, A_ind, A_indptr), shape=(n_queries, n_samples_fit))
|
Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query point or points.
If not provided, neighbors of each indexed point are returned.
In this case, the query point is not considered its own neighbor.
radius : float, default=None
Radius of neighborhoods. The default is the value passed to the
constructor.
mode : {'connectivity', 'distance'}, default='connectivity'
Type of returned matrix: 'connectivity' will return the
connectivity matrix with ones and zeros, in 'distance' the
edges are distances between points, type of distance
depends on the selected metric parameter in
NearestNeighbors class.
sort_results : bool, default=False
If True, in each row of the result, the non-zero entries will be
sorted by increasing distances. If False, the non-zero entries may
not be sorted. Only used with mode='distance'.
.. versionadded:: 0.22
Returns
-------
A : sparse-matrix of shape (n_queries, n_samples_fit)
`n_samples_fit` is the number of samples in the fitted data.
`A[i, j]` gives the weight of the edge connecting `i` to `j`.
The matrix is of CSR format.
See Also
--------
kneighbors_graph : Compute the (weighted) graph of k-Neighbors for
points in X.
Examples
--------
>>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(radius=1.5)
>>> neigh.fit(X)
NearestNeighbors(radius=1.5)
>>> A = neigh.radius_neighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
[0., 1., 0.],
[1., 0., 1.]])
|
python
|
sklearn/neighbors/_base.py
| 1,304
|
[
"self",
"X",
"radius",
"mode",
"sort_results"
] | false
| 6
| 7.6
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
registerResolvableDependency
|
@Override
public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) {
Assert.notNull(dependencyType, "Dependency type must not be null");
if (autowiredValue != null) {
if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) {
throw new IllegalArgumentException("Value [" + autowiredValue +
"] does not implement specified dependency type [" + dependencyType.getName() + "]");
}
this.resolvableDependencies.put(dependencyType, autowiredValue);
}
}
|
Check whether the specified bean would need to be eagerly initialized
in order to determine its type.
@param factoryBeanName a factory-bean reference that the bean definition
defines a factory method for
@return whether eager initialization is necessary
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
| 887
|
[
"dependencyType",
"autowiredValue"
] |
void
| true
| 4
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
_get_values
|
def _get_values(
values: np.ndarray,
skipna: bool,
fill_value: Any = None,
fill_value_typ: str | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_] | None]:
"""
Utility to get the values view, mask, dtype, dtype_max, and fill_value.
If both mask and fill_value/fill_value_typ are not None and skipna is True,
the values array will be copied.
For input arrays of boolean or integer dtypes, copies will only occur if a
precomputed mask, a fill_value/fill_value_typ, and skipna=True are
provided.
Parameters
----------
values : ndarray
input array to potentially compute mask for
skipna : bool
boolean for whether NaNs should be skipped
fill_value : Any
value to fill NaNs with
fill_value_typ : str
Set to '+inf' or '-inf' to handle dtype-specific infinities
mask : Optional[np.ndarray[bool]]
nan-mask if known
Returns
-------
values : ndarray
Potential copy of input value array
mask : Optional[ndarray[bool]]
Mask for values, if deemed necessary to compute
"""
# In _get_values is only called from within nanops, and in all cases
# with scalar fill_value. This guarantee is important for the
# np.where call below
mask = _maybe_get_mask(values, skipna, mask)
dtype = values.dtype
datetimelike = False
if values.dtype.kind in "mM":
# changing timedelta64/datetime64 to int64 needs to happen after
# finding `mask` above
values = np.asarray(values.view("i8"))
datetimelike = True
if skipna and (mask is not None):
# get our fill value (in case we need to provide an alternative
# dtype for it)
fill_value = _get_fill_value(
dtype, fill_value=fill_value, fill_value_typ=fill_value_typ
)
if fill_value is not None:
if mask.any():
if datetimelike or _na_ok_dtype(dtype):
values = values.copy()
np.putmask(values, mask, fill_value)
else:
# np.where will promote if needed
values = np.where(~mask, values, fill_value)
return values, mask
|
Utility to get the values view, mask, dtype, dtype_max, and fill_value.
If both mask and fill_value/fill_value_typ are not None and skipna is True,
the values array will be copied.
For input arrays of boolean or integer dtypes, copies will only occur if a
precomputed mask, a fill_value/fill_value_typ, and skipna=True are
provided.
Parameters
----------
values : ndarray
input array to potentially compute mask for
skipna : bool
boolean for whether NaNs should be skipped
fill_value : Any
value to fill NaNs with
fill_value_typ : str
Set to '+inf' or '-inf' to handle dtype-specific infinities
mask : Optional[np.ndarray[bool]]
nan-mask if known
Returns
-------
values : ndarray
Potential copy of input value array
mask : Optional[ndarray[bool]]
Mask for values, if deemed necessary to compute
|
python
|
pandas/core/nanops.py
| 255
|
[
"values",
"skipna",
"fill_value",
"fill_value_typ",
"mask"
] |
tuple[np.ndarray, npt.NDArray[np.bool_] | None]
| true
| 9
| 6.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
builder
|
public static RestClientBuilder builder(String cloudId) {
// there is an optional first portion of the cloudId that is a human readable string, but it is not used.
if (cloudId.contains(":")) {
if (cloudId.indexOf(':') == cloudId.length() - 1) {
throw new IllegalStateException("cloudId " + cloudId + " must begin with a human readable identifier followed by a colon");
}
cloudId = cloudId.substring(cloudId.indexOf(':') + 1);
}
String decoded = new String(Base64.getDecoder().decode(cloudId), UTF_8);
// once decoded the parts are separated by a $ character.
// they are respectively domain name and optional port, elasticsearch id, kibana id
String[] decodedParts = decoded.split("\\$");
if (decodedParts.length != 3) {
throw new IllegalStateException("cloudId " + cloudId + " did not decode to a cluster identifier correctly");
}
// domain name and optional port
String[] domainAndMaybePort = decodedParts[0].split(":", 2);
String domain = domainAndMaybePort[0];
int port;
if (domainAndMaybePort.length == 2) {
try {
port = Integer.parseInt(domainAndMaybePort[1]);
} catch (NumberFormatException nfe) {
throw new IllegalStateException("cloudId " + cloudId + " does not contain a valid port number");
}
} else {
port = 443;
}
String url = decodedParts[1] + "." + domain;
return builder(new HttpHost(url, port, "https"));
}
|
Returns a new {@link RestClientBuilder} to help with {@link RestClient} creation.
Creates a new builder instance and sets the nodes that the client will send requests to.
@param cloudId a valid elastic cloud cloudId that will route to a cluster. The cloudId is located in
the user console https://cloud.elastic.co and will resemble a string like the following
optionalHumanReadableName:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyRlbGFzdGljc2VhcmNoJGtpYmFuYQ==
|
java
|
client/rest/src/main/java/org/elasticsearch/client/RestClient.java
| 159
|
[
"cloudId"
] |
RestClientBuilder
| true
| 6
| 6.56
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
equals
|
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultJdkTrustConfig that = (DefaultJdkTrustConfig) o;
return Arrays.equals(this.trustStorePassword, that.trustStorePassword);
}
|
When a PKCS#11 token is used as the system default keystore/truststore, we need to pass the keystore
password when loading, even for reading certificates only ( as opposed to i.e. JKS keystores where
we only need to pass the password for reading Private Key entries ).
@return the KeyStore used as truststore for PKCS#11 initialized with the password, null otherwise
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java
| 115
|
[
"o"
] | true
| 4
| 6.72
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
_parse_latex_table_styles
|
def _parse_latex_table_styles(table_styles: CSSStyles, selector: str) -> str | None:
"""
Return the first 'props' 'value' from ``tables_styles`` identified by ``selector``.
Examples
--------
>>> table_styles = [
... {"selector": "foo", "props": [("attr", "value")]},
... {"selector": "bar", "props": [("attr", "overwritten")]},
... {"selector": "bar", "props": [("a1", "baz"), ("a2", "ignore")]},
... ]
>>> _parse_latex_table_styles(table_styles, selector="bar")
'baz'
Notes
-----
The replacement of "§" with ":" is to avoid the CSS problem where ":" has structural
significance and cannot be used in LaTeX labels, but is often required by them.
"""
for style in table_styles[::-1]: # in reverse for most recently applied style
if style["selector"] == selector:
return str(style["props"][0][1]).replace("§", ":")
return None
|
Return the first 'props' 'value' from ``tables_styles`` identified by ``selector``.
Examples
--------
>>> table_styles = [
... {"selector": "foo", "props": [("attr", "value")]},
... {"selector": "bar", "props": [("attr", "overwritten")]},
... {"selector": "bar", "props": [("a1", "baz"), ("a2", "ignore")]},
... ]
>>> _parse_latex_table_styles(table_styles, selector="bar")
'baz'
Notes
-----
The replacement of "§" with ":" is to avoid the CSS problem where ":" has structural
significance and cannot be used in LaTeX labels, but is often required by them.
|
python
|
pandas/io/formats/style_render.py
| 2,330
|
[
"table_styles",
"selector"
] |
str | None
| true
| 3
| 6.8
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
because
|
public ConditionMessage because(@Nullable String reason) {
if (StringUtils.hasLength(reason)) {
return new ConditionMessage(ConditionMessage.this,
StringUtils.hasLength(this.condition) ? this.condition + " " + reason : reason);
}
return new ConditionMessage(ConditionMessage.this, this.condition);
}
|
Indicates the reason. For example {@code because("running Linux")} results in
the message "running Linux".
@param reason the reason for the message
@return a built {@link ConditionMessage}
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
| 301
|
[
"reason"
] |
ConditionMessage
| true
| 3
| 7.44
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
findBaseOfDeclaration
|
function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {
const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;
if (!classOrInterfaceDeclaration) return;
const isStaticMember = hasStaticModifier(declaration);
return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {
const baseType = checker.getTypeAtLocation(superTypeNode);
const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType;
const symbol = checker.getPropertyOfType(type, declaration.symbol.name);
return symbol ? cb(symbol) : undefined;
});
}
|
Returns whether or not the given node has a JSDoc "inheritDoc" tag on it.
@param node the Node in question.
@returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`.
|
typescript
|
src/services/services.ts
| 1,051
|
[
"checker",
"declaration",
"cb"
] | true
| 6
| 8.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
max0
|
private static int max0(final int other) {
return Math.max(0, other);
}
|
Maps elements from an array into elements of a new array of a given type, while mapping old elements to new elements.
@param <T> The input array type.
@param <R> The output array type.
@param <E> The type of exceptions thrown when the mapper function fails.
@param array The input array.
@param componentType the component type of the result array.
@param mapper a non-interfering, stateless function to apply to each element.
@return a new array.
@throws E Thrown when the mapper function fails.
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 4,225
|
[
"other"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
createExportStatement
|
function createExportStatement(name: Identifier | StringLiteral, value: Expression, allowComments?: boolean) {
const statement = factory.createExpressionStatement(createExportExpression(name, value));
startOnNewLine(statement);
if (!allowComments) {
setEmitFlags(statement, EmitFlags.NoComments);
}
return statement;
}
|
Creates a call to the current file's export function to export a value.
@param name The bound name of the export.
@param value The exported value.
@param allowComments An optional value indicating whether to emit comments for the statement.
|
typescript
|
src/compiler/transformers/module/system.ts
| 1,200
|
[
"name",
"value",
"allowComments?"
] | false
| 2
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
generateInstanceSupplierCode
|
CodeBlock generateInstanceSupplierCode(
GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode,
boolean allowDirectSupplierShortcut);
|
Generate the instance supplier code.
@param generationContext the generation context
@param beanRegistrationCode the bean registration code
@param allowDirectSupplierShortcut if direct suppliers may be used rather
than always needing an {@link InstanceSupplier}
@return the generated code
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationCodeFragments.java
| 120
|
[
"generationContext",
"beanRegistrationCode",
"allowDirectSupplierShortcut"
] |
CodeBlock
| true
| 1
| 6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
lenientFormat
|
static String lenientFormat(@Nullable String template, @Nullable Object @Nullable ... args) {
return Strings.lenientFormat(template, args);
}
|
Returns the string if it is not empty, or a null string otherwise.
@param string the string to test and possibly return
@return {@code string} if it is not empty; {@code null} otherwise
|
java
|
android/guava/src/com/google/common/base/Platform.java
| 81
|
[
"template"
] |
String
| true
| 1
| 6.96
|
google/guava
| 51,352
|
javadoc
| false
|
initAnnotatedTypeExists
|
private static boolean initAnnotatedTypeExists() {
try {
Class.forName("java.lang.reflect.AnnotatedType");
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
|
This should never return a type that's not a subtype of Throwable.
|
java
|
android/guava/src/com/google/common/reflect/Invokable.java
| 514
|
[] | true
| 2
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
|
slice_locs
|
def slice_locs(self, start=None, end=None, step=None) -> tuple[int, int]:
"""
For an ordered MultiIndex, compute the slice locations for input
labels.
The input labels can be tuples representing partial levels, e.g. for a
MultiIndex with 3 levels, you can pass a single value (corresponding to
the first level), or a 1-, 2-, or 3-tuple.
Parameters
----------
start : label or tuple, default None
If None, defaults to the beginning
end : label or tuple
If None, defaults to the end
step : int or None
Slice step
Returns
-------
(start, end) : (int, int)
Notes
-----
This method only works if the MultiIndex is properly lexsorted. So,
if only the first 2 levels of a 3-level MultiIndex are lexsorted,
you can only pass two levels to ``.slice_locs``.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays(
... [list("abbd"), list("deff")], names=["A", "B"]
... )
Get the slice locations from the beginning of 'b' in the first level
until the end of the multiindex:
>>> mi.slice_locs(start="b")
(1, 4)
Like above, but stop at the end of 'b' in the first level and 'f' in
the second level:
>>> mi.slice_locs(start="b", end=("b", "f"))
(1, 3)
See Also
--------
MultiIndex.get_loc : Get location for a label or a tuple of labels.
MultiIndex.get_locs : Get location for a label/slice/list/mask or a
sequence of such.
"""
# This function adds nothing to its parent implementation (the magic
# happens in get_slice_bound method), but it adds meaningful doc.
return super().slice_locs(start, end, step)
|
For an ordered MultiIndex, compute the slice locations for input
labels.
The input labels can be tuples representing partial levels, e.g. for a
MultiIndex with 3 levels, you can pass a single value (corresponding to
the first level), or a 1-, 2-, or 3-tuple.
Parameters
----------
start : label or tuple, default None
If None, defaults to the beginning
end : label or tuple
If None, defaults to the end
step : int or None
Slice step
Returns
-------
(start, end) : (int, int)
Notes
-----
This method only works if the MultiIndex is properly lexsorted. So,
if only the first 2 levels of a 3-level MultiIndex are lexsorted,
you can only pass two levels to ``.slice_locs``.
Examples
--------
>>> mi = pd.MultiIndex.from_arrays(
... [list("abbd"), list("deff")], names=["A", "B"]
... )
Get the slice locations from the beginning of 'b' in the first level
until the end of the multiindex:
>>> mi.slice_locs(start="b")
(1, 4)
Like above, but stop at the end of 'b' in the first level and 'f' in
the second level:
>>> mi.slice_locs(start="b", end=("b", "f"))
(1, 3)
See Also
--------
MultiIndex.get_loc : Get location for a label or a tuple of labels.
MultiIndex.get_locs : Get location for a label/slice/list/mask or a
sequence of such.
|
python
|
pandas/core/indexes/multi.py
| 3,135
|
[
"self",
"start",
"end",
"step"
] |
tuple[int, int]
| true
| 1
| 7.28
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
findThreadGroups
|
@Deprecated
public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup threadGroup, final boolean recurse, final ThreadGroupPredicate predicate) {
return findThreadGroups(threadGroup, recurse, (Predicate<ThreadGroup>) predicate::test);
}
|
Finds all active thread groups which match the given predicate and which is a subgroup of the given thread group (or one of its subgroups).
@param threadGroup the thread group.
@param recurse if {@code true} then evaluate the predicate recursively on all thread groups in all subgroups of the given group.
@param predicate the predicate.
@return An unmodifiable {@link Collection} of active thread groups which match the given predicate and which is a subgroup of the given thread group.
@throws NullPointerException if the given group or predicate is null.
@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 #findThreadGroups(ThreadGroup, boolean, Predicate)}.
|
java
|
src/main/java/org/apache/commons/lang3/ThreadUtils.java
| 282
|
[
"threadGroup",
"recurse",
"predicate"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
as
|
public <R> Source<R> as(Adapter<? super T, ? extends R> adapter) {
Assert.notNull(adapter, "'adapter' must not be null");
Supplier<@Nullable R> supplier = () -> {
T value = getValue();
return (value != null && this.predicate.test(value)) ? adapter.adapt(value) : null;
};
Predicate<R> predicate = (adaptedValue) -> {
T value = getValue();
return value != null && this.predicate.test(value);
};
return new Source<>(supplier, predicate);
}
|
Return an adapted version of the source changed through the given adapter
function.
@param <R> the resulting type
@param adapter the adapter to apply
@return a new adapted source instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java
| 198
|
[
"adapter"
] | true
| 4
| 8.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
is_replication_group_available
|
def is_replication_group_available(self, replication_group_id: str) -> bool:
"""
Check if replication group is available or not.
:param replication_group_id: ID of replication group to check for availability
:return: True if available else False
"""
return self.get_replication_group_status(replication_group_id) == "available"
|
Check if replication group is available or not.
:param replication_group_id: ID of replication group to check for availability
:return: True if available else False
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/elasticache_replication_group.py
| 111
|
[
"self",
"replication_group_id"
] |
bool
| true
| 1
| 6.72
|
apache/airflow
| 43,597
|
sphinx
| false
|
mean
|
def mean(
self,
numeric_only: bool = False,
skipna: bool = True,
engine: Literal["cython", "numba"] | None = None,
engine_kwargs: dict[str, bool] | None = None,
):
"""
Compute mean of groups, excluding missing values.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns.
.. versionchanged:: 2.0.0
numeric_only no longer accepts ``None`` and defaults to ``False``.
skipna : bool, default True
Exclude NA/null values. If an entire group is NA, the result will be NA.
engine : str, default None
* ``'cython'`` : Runs the operation through C-extensions from cython.
* ``'numba'`` : Runs the operation through JIT compiled code from numba.
* ``None`` : Defaults to ``'cython'`` or globally setting
``compute.use_numba``
engine_kwargs : dict, default None
* For ``'cython'`` engine, there are no accepted ``engine_kwargs``
* For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
and ``parallel`` dictionary keys. The values must either be ``True`` or
``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
``{{'nopython': True, 'nogil': False, 'parallel': False}}``
Returns
-------
pandas.Series or pandas.DataFrame
Mean of values within each group. Same object type as the caller.
%(see_also)s
Examples
--------
>>> df = pd.DataFrame(
... {"A": [1, 1, 2, 1, 2], "B": [np.nan, 2, 3, 4, 5], "C": [1, 2, 1, 1, 2]},
... columns=["A", "B", "C"],
... )
Groupby one column and return the mean of the remaining columns in
each group.
>>> df.groupby("A").mean()
B C
A
1 3.0 1.333333
2 4.0 1.500000
Groupby two columns and return the mean of the remaining column.
>>> df.groupby(["A", "B"]).mean()
C
A B
1 2.0 2.0
4.0 1.0
2 3.0 1.0
5.0 2.0
Groupby one column and return the mean of only particular column in
the group.
>>> df.groupby("A")["B"].mean()
A
1 3.0
2 4.0
Name: B, dtype: float64
"""
if maybe_use_numba(engine):
from pandas.core._numba.kernels import grouped_mean
return self._numba_agg_general(
grouped_mean,
executor.float_dtype_mapping,
engine_kwargs,
min_periods=0,
skipna=skipna,
)
else:
result = self._cython_agg_general(
"mean",
alt=lambda x: Series(x, copy=False).mean(
numeric_only=numeric_only, skipna=skipna
),
numeric_only=numeric_only,
skipna=skipna,
)
return result.__finalize__(self.obj, method="groupby")
|
Compute mean of groups, excluding missing values.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns.
.. versionchanged:: 2.0.0
numeric_only no longer accepts ``None`` and defaults to ``False``.
skipna : bool, default True
Exclude NA/null values. If an entire group is NA, the result will be NA.
engine : str, default None
* ``'cython'`` : Runs the operation through C-extensions from cython.
* ``'numba'`` : Runs the operation through JIT compiled code from numba.
* ``None`` : Defaults to ``'cython'`` or globally setting
``compute.use_numba``
engine_kwargs : dict, default None
* For ``'cython'`` engine, there are no accepted ``engine_kwargs``
* For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
and ``parallel`` dictionary keys. The values must either be ``True`` or
``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
``{{'nopython': True, 'nogil': False, 'parallel': False}}``
Returns
-------
pandas.Series or pandas.DataFrame
Mean of values within each group. Same object type as the caller.
%(see_also)s
Examples
--------
>>> df = pd.DataFrame(
... {"A": [1, 1, 2, 1, 2], "B": [np.nan, 2, 3, 4, 5], "C": [1, 2, 1, 1, 2]},
... columns=["A", "B", "C"],
... )
Groupby one column and return the mean of the remaining columns in
each group.
>>> df.groupby("A").mean()
B C
A
1 3.0 1.333333
2 4.0 1.500000
Groupby two columns and return the mean of the remaining column.
>>> df.groupby(["A", "B"]).mean()
C
A B
1 2.0 2.0
4.0 1.0
2 3.0 1.0
5.0 2.0
Groupby one column and return the mean of only particular column in
the group.
>>> df.groupby("A")["B"].mean()
A
1 3.0
2 4.0
Name: B, dtype: float64
|
python
|
pandas/core/groupby/groupby.py
| 2,206
|
[
"self",
"numeric_only",
"skipna",
"engine",
"engine_kwargs"
] | true
| 3
| 8.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
parse
|
boolean parse(String source, ParsePosition pos, Calendar calendar);
|
Parses a formatted date string according to the format. Updates the Calendar with parsed fields.
Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed.
Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to
the offset of the source text which does not match the supplied format.
@param source The text to parse.
@param pos On input, the position in the source to start parsing, on output, updated position.
@param calendar The calendar into which to set parsed fields.
@return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated)
@throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is
out of range.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/time/DateParser.java
| 103
|
[
"source",
"pos",
"calendar"
] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
format_dateaxis
|
def format_dateaxis(
subplot, freq: BaseOffset, index: DatetimeIndex | PeriodIndex
) -> None:
"""
Pretty-formats the date axis (x-axis).
Major and minor ticks are automatically set for the frequency of the
current underlying series. As the dynamic mode is activated by
default, changing the limits of the x axis will intelligently change
the positions of the ticks.
"""
import matplotlib.pyplot as plt
# handle index specific formatting
# Note: DatetimeIndex does not use this
# interface. DatetimeIndex uses matplotlib.date directly
if isinstance(index, ABCPeriodIndex):
majlocator = TimeSeries_DateLocator(
freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
)
minlocator = TimeSeries_DateLocator(
freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
)
subplot.xaxis.set_major_locator(majlocator)
subplot.xaxis.set_minor_locator(minlocator)
majformatter = TimeSeries_DateFormatter(
freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
)
minformatter = TimeSeries_DateFormatter(
freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
)
subplot.xaxis.set_major_formatter(majformatter)
subplot.xaxis.set_minor_formatter(minformatter)
# x and y coord info
subplot.format_coord = functools.partial(_format_coord, freq)
elif isinstance(index, ABCTimedeltaIndex):
subplot.xaxis.set_major_formatter(TimeSeries_TimedeltaFormatter(index.unit))
else:
raise TypeError("index type not supported")
plt.draw_if_interactive()
|
Pretty-formats the date axis (x-axis).
Major and minor ticks are automatically set for the frequency of the
current underlying series. As the dynamic mode is activated by
default, changing the limits of the x axis will intelligently change
the positions of the ticks.
|
python
|
pandas/plotting/_matplotlib/timeseries.py
| 305
|
[
"subplot",
"freq",
"index"
] |
None
| true
| 4
| 6
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
toString
|
@Override
public String toString() {
return getClass().getSimpleName() + "{" + toStringBase() + '}';
}
|
This method appends the instance variables together in a simple String of comma-separated key value pairs.
This allows subclasses to include these values and not have to duplicate each variable, helping to prevent
any variables from being omitted when new ones are added.
@return String version of instance variables.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestState.java
| 159
|
[] |
String
| true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
parseArrowFunctionExpressionBody
|
function parseArrowFunctionExpressionBody(isAsync: boolean, allowReturnTypeInArrowFunction: boolean): Block | Expression {
if (token() === SyntaxKind.OpenBraceToken) {
return parseFunctionBlock(isAsync ? SignatureFlags.Await : SignatureFlags.None);
}
if (
token() !== SyntaxKind.SemicolonToken &&
token() !== SyntaxKind.FunctionKeyword &&
token() !== SyntaxKind.ClassKeyword &&
isStartOfStatement() &&
!isStartOfExpressionStatement()
) {
// Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
//
// Here we try to recover from a potential error situation in the case where the
// user meant to supply a block. For example, if the user wrote:
//
// a =>
// let v = 0;
// }
//
// they may be missing an open brace. Check to see if that's the case so we can
// try to recover better. If we don't do this, then the next close curly we see may end
// up preemptively closing the containing construct.
//
// Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
return parseFunctionBlock(SignatureFlags.IgnoreMissingOpenBrace | (isAsync ? SignatureFlags.Await : SignatureFlags.None));
}
const savedYieldContext = inYieldContext();
setYieldContext(false);
const savedTopLevel = topLevel;
topLevel = false;
const node = isAsync
? doInAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction))
: doOutsideOfAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction));
topLevel = savedTopLevel;
setYieldContext(savedYieldContext);
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
| 5,533
|
[
"isAsync",
"allowReturnTypeInArrowFunction"
] | true
| 10
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
newTreeSet
|
@SuppressWarnings({
"rawtypes", // https://github.com/google/guava/issues/989
"NonApiType", // acts as a direct substitute for a constructor call
})
public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
Iterables.addAll(set, elements);
return set;
}
|
Creates a <i>mutable</i> {@code TreeSet} instance containing the given elements sorted by their
natural ordering.
<p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)}
instead.
<p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit comparator, this
method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code
TreeSet} with that comparator.
<p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
use the {@code TreeSet} constructor directly, taking advantage of <a
href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond"
syntax</a>.
<p>This method is just a small convenience for creating an empty set and then calling {@link
Iterables#addAll}. This method is not very useful and will likely be deprecated in the future.
@param elements the elements that the set should contain
@return a new {@code TreeSet} containing those elements (minus duplicates)
|
java
|
android/guava/src/com/google/common/collect/Sets.java
| 411
|
[
"elements"
] | true
| 1
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
|
isPreviousPropertyDeclarationTerminated
|
function isPreviousPropertyDeclarationTerminated(contextToken: Node, position: number) {
return contextToken.kind !== SyntaxKind.EqualsToken &&
(contextToken.kind === SyntaxKind.SemicolonToken
|| !positionsAreOnSameLine(contextToken.end, position, sourceFile));
}
|
@returns true if we are certain that the currently edited location must define a new location; false otherwise.
|
typescript
|
src/services/completions.ts
| 5,095
|
[
"contextToken",
"position"
] | false
| 3
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
currentAddress
|
private InetAddress currentAddress() throws UnknownHostException {
if (addresses.isEmpty()) {
resolveAddresses();
}
// Save the address that we return so that we don't try it twice in a row when we re-resolve due to
// disconnecting or exhausting the addresses
InetAddress currentAddress = addresses.get(addressIndex);
lastAttemptedAddress = currentAddress;
return currentAddress;
}
|
Fetches the current selected IP address for this node, resolving {@link #host()} if necessary.
@return the selected address
@throws UnknownHostException if resolving {@link #host()} fails
|
java
|
clients/src/main/java/org/apache/kafka/clients/ClusterConnectionStates.java
| 509
|
[] |
InetAddress
| true
| 2
| 7.44
|
apache/kafka
| 31,560
|
javadoc
| false
|
getNextUserArgs
|
function getNextUserArgs(callArgs: UserArgs, prevArgs: UserArgs, nextDataPath: string[]): UserArgs {
if (prevArgs === undefined) return callArgs ?? {}
return deepSet(prevArgs, nextDataPath, callArgs || true)
}
|
@see {getNextDataPath} for introduction. The goal of the fluent API is to
make it easy to retrieve nested relations. For this, we construct the query
args that are necessary to retrieve the nested relations. It consists of
nesting `select` statements each time that we access a relation.
@param callArgs usually passed on the last call of the chaining api
@param prevArgs when multiple chaining occurs, they are the previous
@param nextDataPath path where to set `callArgs` in `prevArgs`
@example
```ts
prisma.user.findUnique().link().user()
// will end up with an args like this:
// args {
// "where": {
// "email": "1639498523518@gmail.com"
// },
// "select": {
// "link": {
// "select": {
// "user": true
// }
// }
// }
// }
```
|
typescript
|
packages/client/src/runtime/core/model/applyFluent.ts
| 53
|
[
"callArgs",
"prevArgs",
"nextDataPath"
] | true
| 3
| 8.24
|
prisma/prisma
| 44,834
|
jsdoc
| false
|
|
get_connection
|
def get_connection(self, conn_id: str, session: Session = NEW_SESSION) -> Connection | None:
"""
Get Airflow Connection from Metadata DB.
:param conn_id: Connection ID
:param session: SQLAlchemy Session
:return: Connection Object
"""
from airflow.models import Connection
conn = session.scalar(select(Connection).where(Connection.conn_id == conn_id).limit(1))
session.expunge_all()
return conn
|
Get Airflow Connection from Metadata DB.
:param conn_id: Connection ID
:param session: SQLAlchemy Session
:return: Connection Object
|
python
|
airflow-core/src/airflow/secrets/metastore.py
| 39
|
[
"self",
"conn_id",
"session"
] |
Connection | None
| true
| 1
| 6.4
|
apache/airflow
| 43,597
|
sphinx
| false
|
obtainFromSupplier
|
private BeanWrapper obtainFromSupplier(Supplier<?> supplier, String beanName, RootBeanDefinition mbd) {
String outerBean = this.currentlyCreatedBean.get();
this.currentlyCreatedBean.set(beanName);
Object instance;
try {
instance = obtainInstanceFromSupplier(supplier, beanName, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeansException beansException) {
throw beansException;
}
throw new BeanCreationException(beanName, "Instantiation of supplied bean failed", ex);
}
finally {
if (outerBean != null) {
this.currentlyCreatedBean.set(outerBean);
}
else {
this.currentlyCreatedBean.remove();
}
}
if (instance == null) {
instance = new NullBean();
}
BeanWrapper bw = new BeanWrapperImpl(instance);
initBeanWrapper(bw);
return bw;
}
|
Obtain a bean instance from the given supplier.
@param supplier the configured supplier
@param beanName the corresponding bean name
@return a BeanWrapper for the new instance
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
| 1,240
|
[
"supplier",
"beanName",
"mbd"
] |
BeanWrapper
| true
| 5
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
canApply
|
public static boolean canApply(Advisor advisor, Class<?> targetClass) {
return canApply(advisor, targetClass, false);
}
|
Can the given advisor apply at all on the given class?
This is an important test as it can be used to optimize
out an advisor for a class.
@param advisor the advisor to check
@param targetClass class we're testing
@return whether the pointcut can apply on any method
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
| 284
|
[
"advisor",
"targetClass"
] | true
| 1
| 6.64
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
addDays
|
public static Date addDays(final Date date, final int amount) {
return add(date, Calendar.DAY_OF_MONTH, amount);
}
|
Adds a number of days to a date returning a new object.
The original {@link Date} is unchanged.
@param date the date, not null.
@param amount the amount to add, may be negative.
@return the new {@link Date} with the amount added.
@throws NullPointerException if the date is null.
|
java
|
src/main/java/org/apache/commons/lang3/time/DateUtils.java
| 237
|
[
"date",
"amount"
] |
Date
| true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
modify
|
private static String modify(final String str, final String[] set, final boolean expect) {
final CharSet chars = CharSet.getInstance(set);
final StringBuilder buffer = new StringBuilder(str.length());
final char[] chrs = str.toCharArray();
for (final char chr : chrs) {
if (chars.contains(chr) == expect) {
buffer.append(chr);
}
}
return buffer.toString();
}
|
Implements delete and keep.
@param str String to modify characters within
@param set String[] set of characters to modify
@param expect whether to evaluate on match, or non-match
@return the modified String, not null
|
java
|
src/main/java/org/apache/commons/lang3/CharSetUtils.java
| 175
|
[
"str",
"set",
"expect"
] |
String
| true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
takeWhile
|
function takeWhile<T>(predicate: (item: T) => boolean, list: T[]): T[] {
for (let i = 0; i < list.length; ++i) {
if (!predicate(list[i])) {
return list.slice(0, i);
}
}
return list.slice();
}
|
@param predicate ([a] -> Boolean) the function used to make the determination
@param list the input list
@returns the leading sequence of members in the given list that pass the given predicate
|
typescript
|
.eslint-plugin-local/code-no-unused-expressions.ts
| 77
|
[
"predicate",
"list"
] | true
| 3
| 7.6
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
toMediaType
|
public <T extends MediaType> T toMediaType(MediaTypeRegistry<T> mediaTypeRegistry) {
T someType = mediaTypeRegistry.typeWithSubtypeToMediaType(mediaTypeWithoutParameters());
if (someType != null) {
Map<String, Pattern> registeredParams = mediaTypeRegistry.parametersFor(mediaTypeWithoutParameters());
for (Map.Entry<String, String> givenParamEntry : parameters.entrySet()) {
if (isValidParameter(givenParamEntry.getKey(), givenParamEntry.getValue(), registeredParams) == false) {
return null;
}
}
return someType;
}
return null;
}
|
Resolves this instance to a MediaType instance defined in given MediaTypeRegistry.
Performs validation against parameters.
@param mediaTypeRegistry a registry where a mapping between a raw media type to an instance MediaType is defined
@return a MediaType instance or null if no media type could be found or if a known parameter do not passes validation
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/ParsedMediaType.java
| 128
|
[
"mediaTypeRegistry"
] |
T
| true
| 3
| 7.6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
get_crawler
|
def get_crawler(self, crawler_name: str) -> dict:
"""
Get crawler configurations.
.. seealso::
- :external+boto3:py:meth:`Glue.Client.get_crawler`
:param crawler_name: unique crawler name per AWS account
:return: Nested dictionary of crawler configurations
"""
return self.glue_client.get_crawler(Name=crawler_name)["Crawler"]
|
Get crawler configurations.
.. seealso::
- :external+boto3:py:meth:`Glue.Client.get_crawler`
:param crawler_name: unique crawler name per AWS account
:return: Nested dictionary of crawler configurations
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/glue_crawler.py
| 65
|
[
"self",
"crawler_name"
] |
dict
| true
| 1
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
determineProjectType
|
protected ProjectType determineProjectType(InitializrServiceMetadata metadata) {
if (this.type != null) {
ProjectType result = metadata.getProjectTypes().get(this.type);
if (result == null) {
throw new ReportableException(
("No project type with id '" + this.type + "' - check the service capabilities (--list)"));
}
return result;
}
else if (isDetectType()) {
Map<String, ProjectType> types = new HashMap<>(metadata.getProjectTypes());
if (this.build != null) {
filter(types, "build", this.build);
}
if (this.format != null) {
filter(types, "format", this.format);
}
if (types.size() == 1) {
return types.values().iterator().next();
}
else if (types.isEmpty()) {
throw new ReportableException("No type found with build '" + this.build + "' and format '" + this.format
+ "' check the service capabilities (--list)");
}
else {
throw new ReportableException("Multiple types found with build '" + this.build + "' and format '"
+ this.format + "' use --type with a more specific value " + types.keySet());
}
}
else {
ProjectType defaultType = metadata.getDefaultType();
if (defaultType == null) {
throw new ReportableException(("No project type is set and no default is defined. "
+ "Check the service capabilities (--list)"));
}
return defaultType;
}
}
|
Generates the URI to use to generate a project represented by this request.
@param metadata the metadata that describes the service
@return the project generation URI
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java
| 364
|
[
"metadata"
] |
ProjectType
| true
| 9
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
toArray
|
@Override
public @Nullable Object[] toArray() {
if (needsAllocArrays()) {
return new Object[0];
}
Set<E> delegate = delegateOrNull();
return (delegate != null) ? delegate.toArray() : Arrays.copyOf(requireElements(), size);
}
|
Updates the index an iterator is pointing to after a call to remove: returns the index of the
entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
index that *was* the next entry that would be looked at.
|
java
|
android/guava/src/com/google/common/collect/CompactHashSet.java
| 597
|
[] | true
| 3
| 6.4
|
google/guava
| 51,352
|
javadoc
| false
|
|
config
|
public MetricConfig config() {
return this.config;
}
|
Get the configuration of this metric.
This is supposed to be used by server only.
@return Return the config of this metric
|
java
|
clients/src/main/java/org/apache/kafka/common/metrics/KafkaMetric.java
| 56
|
[] |
MetricConfig
| true
| 1
| 6.96
|
apache/kafka
| 31,560
|
javadoc
| false
|
inject
|
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
element.inject(target, beanName, pvs);
}
}
}
|
Determine whether this metadata instance needs to be refreshed.
@param clazz the current target class
@return {@code true} indicating a refresh, {@code false} otherwise
@since 5.2.4
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/annotation/InjectionMetadata.java
| 140
|
[
"target",
"beanName",
"pvs"
] |
void
| true
| 3
| 7.92
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
onConfigDataOptions
|
default ConfigData.Options onConfigDataOptions(ConfigData configData, PropertySource<?> propertySource,
Options options) {
return options;
}
|
Called when config data options are obtained for a particular property source.
@param configData the config data
@param propertySource the property source
@param options the options as provided by
{@link ConfigData#getOptions(PropertySource)}
@return the actual options that should be used
@since 3.5.1
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentUpdateListener.java
| 68
|
[
"configData",
"propertySource",
"options"
] | true
| 1
| 6.16
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
getClassNames
|
function getClassNames(constructorDeclaration: ValidConstructor): (Identifier | Modifier)[] {
switch (constructorDeclaration.parent.kind) {
case SyntaxKind.ClassDeclaration:
const classDeclaration = constructorDeclaration.parent;
if (classDeclaration.name) return [classDeclaration.name];
// If the class declaration doesn't have a name, it should have a default modifier.
// We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
const defaultModifier = Debug.checkDefined(
findModifier(classDeclaration, SyntaxKind.DefaultKeyword),
"Nameless class declaration should be a default export",
);
return [defaultModifier];
case SyntaxKind.ClassExpression:
const classExpression = constructorDeclaration.parent;
const variableDeclaration = constructorDeclaration.parent.parent;
const className = classExpression.name;
if (className) return [className, variableDeclaration.name];
return [variableDeclaration.name];
}
}
|
Gets the symbol for the contextual type of the node if it is not a union or intersection.
|
typescript
|
src/services/refactors/convertParamsToDestructuredObject.ts
| 683
|
[
"constructorDeclaration"
] | true
| 3
| 6
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
toString
|
public static String toString(final char ch) {
if (ch < CHAR_STRING_ARRAY.length) {
return CHAR_STRING_ARRAY[ch];
}
return String.valueOf(ch);
}
|
Converts the character to a String that contains the one character.
<p>For ASCII 7 bit characters, this uses a cache that will return the
same String object each time.</p>
<pre>
CharUtils.toString(' ') = " "
CharUtils.toString('A') = "A"
</pre>
@param ch the character to convert
@return a String containing the one specified character
|
java
|
src/main/java/org/apache/commons/lang3/CharUtils.java
| 469
|
[
"ch"
] |
String
| true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
numRecords
|
public int numRecords() {
return numRecords;
}
|
@return the total number of non-control messages for this fetch, across all partitions
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetch.java
| 101
|
[] | true
| 1
| 6.32
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
serializeTypeNode
|
function serializeTypeNode(node: TypeNode | undefined): SerializedTypeNode {
if (node === undefined) {
return factory.createIdentifier("Object");
}
node = skipTypeParentheses(node);
switch (node.kind) {
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
return factory.createVoidZero();
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return factory.createIdentifier("Function");
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
return factory.createIdentifier("Array");
case SyntaxKind.TypePredicate:
return (node as TypePredicateNode).assertsModifier ?
factory.createVoidZero() :
factory.createIdentifier("Boolean");
case SyntaxKind.BooleanKeyword:
return factory.createIdentifier("Boolean");
case SyntaxKind.TemplateLiteralType:
case SyntaxKind.StringKeyword:
return factory.createIdentifier("String");
case SyntaxKind.ObjectKeyword:
return factory.createIdentifier("Object");
case SyntaxKind.LiteralType:
return serializeLiteralOfLiteralTypeNode((node as LiteralTypeNode).literal);
case SyntaxKind.NumberKeyword:
return factory.createIdentifier("Number");
case SyntaxKind.BigIntKeyword:
return getGlobalConstructor("BigInt", ScriptTarget.ES2020);
case SyntaxKind.SymbolKeyword:
return getGlobalConstructor("Symbol", ScriptTarget.ES2015);
case SyntaxKind.TypeReference:
return serializeTypeReferenceNode(node as TypeReferenceNode);
case SyntaxKind.IntersectionType:
return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ true);
case SyntaxKind.UnionType:
return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ false);
case SyntaxKind.ConditionalType:
return serializeUnionOrIntersectionConstituents([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType], /*isIntersection*/ false);
case SyntaxKind.TypeOperator:
if ((node as TypeOperatorNode).operator === SyntaxKind.ReadonlyKeyword) {
return serializeTypeNode((node as TypeOperatorNode).type);
}
break;
case SyntaxKind.TypeQuery:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.TypeLiteral:
case SyntaxKind.AnyKeyword:
case SyntaxKind.UnknownKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.ImportType:
break;
// handle JSDoc types from an invalid parse
case SyntaxKind.JSDocAllType:
case SyntaxKind.JSDocUnknownType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocVariadicType:
case SyntaxKind.JSDocNamepathType:
break;
case SyntaxKind.JSDocNullableType:
case SyntaxKind.JSDocNonNullableType:
case SyntaxKind.JSDocOptionalType:
return serializeTypeNode((node as JSDocNullableType | JSDocNonNullableType | JSDocOptionalType).type);
default:
return Debug.failBadSyntaxKind(node);
}
return factory.createIdentifier("Object");
}
|
Serializes a type node for use with decorator type metadata.
Types are serialized in the following fashion:
- Void types point to "undefined" (e.g. "void 0")
- Function and Constructor types point to the global "Function" constructor.
- Interface types with a call or construct signature types point to the global
"Function" constructor.
- Array and Tuple types point to the global "Array" constructor.
- Type predicates and booleans point to the global "Boolean" constructor.
- String literal types and strings point to the global "String" constructor.
- Enum and number types point to the global "Number" constructor.
- Symbol types point to the global "Symbol" constructor.
- Type references to classes (or class-like variables) point to the constructor for the class.
- Anything else points to the global "Object" constructor.
@param node The type node to serialize.
|
typescript
|
src/compiler/transformers/typeSerializer.ts
| 271
|
[
"node"
] | true
| 4
| 6.8
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.