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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
escape
|
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
|
Converts the characters "&", "<", ">", '"', and "'" in `string` to their
corresponding HTML entities.
**Note:** No other characters are escaped. To escape additional
characters use a third-party library like [_he_](https://mths.be/he).
Though the ">" character is escaped for symmetry, characters like
">" and "/" don't need escaping in HTML and have no special meaning
unless they're part of a tag or unquoted attribute value. See
[Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
(under "semi-related fun fact") for more details.
When working with HTML you should always
[quote attribute values](http://wonko.com/post/html-escaping) to reduce
XSS vectors.
@static
@since 0.1.0
@memberOf _
@category String
@param {string} [string=''] The string to escape.
@returns {string} Returns the escaped string.
@example
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
|
javascript
|
lodash.js
| 14,358
|
[
"string"
] | false
| 3
| 7.2
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
awaitTerminationPeriod
|
public ThreadPoolTaskSchedulerBuilder awaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) {
return new ThreadPoolTaskSchedulerBuilder(this.poolSize, this.awaitTermination, awaitTerminationPeriod,
this.threadNamePrefix, this.taskDecorator, this.customizers);
}
|
Set the maximum time the executor is supposed to block on shutdown. When set, the
executor blocks on shutdown in order to wait for remaining tasks to complete their
execution before the rest of the container continues to shut down. This is
particularly useful if your remaining tasks are likely to need access to other
resources that are also managed by the container.
@param awaitTerminationPeriod the await termination period to set
@return a new builder instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java
| 106
|
[
"awaitTerminationPeriod"
] |
ThreadPoolTaskSchedulerBuilder
| true
| 1
| 6.64
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
asCallable
|
public static <O> Callable<O> asCallable(final FailableCallable<O, ?> callable) {
return () -> call(callable);
}
|
Converts the given {@link FailableCallable} into a standard {@link Callable}.
@param <O> the type used by the callables
@param callable a {@link FailableCallable}
@return a standard {@link Callable}
@since 3.10
|
java
|
src/main/java/org/apache/commons/lang3/Functions.java
| 391
|
[
"callable"
] | true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
_apply
|
def _apply(
self,
func: Callable[[np.ndarray, int, int], np.ndarray],
name: str,
numeric_only: bool = False,
numba_args: tuple[Any, ...] = (),
**kwargs,
):
"""
Rolling with weights statistical measure using supplied function.
Designed to be used with passed-in Cython array-based functions.
Parameters
----------
func : callable function to apply
name : str,
numeric_only : bool, default False
Whether to only operate on bool, int, and float columns
numba_args : tuple
unused
**kwargs
additional arguments for scipy windows if necessary
Returns
-------
y : type of input
"""
# "None" not callable [misc]
window = self._scipy_weight_generator( # type: ignore[misc]
self.window, **kwargs
)
offset = (len(window) - 1) // 2 if self.center else 0
def homogeneous_func(values: np.ndarray):
# calculation function
if values.size == 0:
return values.copy()
def calc(x):
additional_nans = np.full(offset, np.nan)
x = np.concatenate((x, additional_nans))
return func(
x,
window,
self.min_periods if self.min_periods is not None else len(window),
)
with np.errstate(all="ignore"):
# Our weighted aggregations return memoryviews
result = np.asarray(calc(values))
if self.center:
result = self._center_window(result, offset)
return result
return self._apply_columnwise(homogeneous_func, name, numeric_only)[
:: self.step
]
|
Rolling with weights statistical measure using supplied function.
Designed to be used with passed-in Cython array-based functions.
Parameters
----------
func : callable function to apply
name : str,
numeric_only : bool, default False
Whether to only operate on bool, int, and float columns
numba_args : tuple
unused
**kwargs
additional arguments for scipy windows if necessary
Returns
-------
y : type of input
|
python
|
pandas/core/window/rolling.py
| 1,156
|
[
"self",
"func",
"name",
"numeric_only",
"numba_args"
] | true
| 5
| 6.48
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
canonicalPropertyName
|
public static String canonicalPropertyName(@Nullable String propertyName) {
if (propertyName == null) {
return "";
}
StringBuilder sb = new StringBuilder(propertyName);
int searchIndex = 0;
while (searchIndex != -1) {
int keyStart = sb.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex);
searchIndex = -1;
if (keyStart != -1) {
int keyEnd = sb.indexOf(
PropertyAccessor.PROPERTY_KEY_SUFFIX, keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length());
if (keyEnd != -1) {
String key = sb.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd);
if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
sb.delete(keyStart + 1, keyStart + 2);
sb.delete(keyEnd - 2, keyEnd - 1);
keyEnd = keyEnd - 2;
}
searchIndex = keyEnd + PropertyAccessor.PROPERTY_KEY_SUFFIX.length();
}
}
}
return sb.toString();
}
|
Determine the canonical name for the given property path.
Removes surrounding quotes from map keys:<br>
{@code map['key']} → {@code map[key]}<br>
{@code map["key"]} → {@code map[key]}
@param propertyName the bean property path
@return the canonical representation of the property path
|
java
|
spring-beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java
| 142
|
[
"propertyName"
] |
String
| true
| 9
| 7.28
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
convertLevel
|
private static int convertLevel(LogEvent event) {
return Severity.getSeverity(event.getLevel()).getCode();
}
|
Converts the log4j2 event level to the Syslog event level code.
@param event the log event
@return an integer representing the syslog log level code
@see Severity class from Log4j2 which contains the conversion logic
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/GraylogExtendedLogFormatStructuredLogFormatter.java
| 131
|
[
"event"
] | true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
buildRequest
|
AbstractRequest.Builder<?> buildRequest(Set<T> keys);
|
Build the lookup request for a set of keys. The grouping of the keys is controlled
through {@link #lookupScope(Object)}. In other words, each set of keys that map
to the same request scope object will be sent to this method.
@param keys the set of keys that require lookup
@return a builder for the lookup request
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/internals/AdminApiLookupStrategy.java
| 65
|
[
"keys"
] | true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
dtype_to_descr
|
def dtype_to_descr(dtype):
"""
Get a serializable descriptor from the dtype.
The .descr attribute of a dtype object cannot be round-tripped through
the dtype() constructor. Simple types, like dtype('float32'), have
a descr which looks like a record array with one field with '' as
a name. The dtype() constructor interprets this as a request to give
a default name. Instead, we construct descriptor that can be passed to
dtype().
Parameters
----------
dtype : dtype
The dtype of the array that will be written to disk.
Returns
-------
descr : object
An object that can be passed to `numpy.dtype()` in order to
replicate the input dtype.
"""
# NOTE: that drop_metadata may not return the right dtype e.g. for user
# dtypes. In that case our code below would fail the same, though.
new_dtype = drop_metadata(dtype)
if new_dtype is not dtype:
warnings.warn("metadata on a dtype is not saved to an npy/npz. "
"Use another format (such as pickle) to store it.",
UserWarning, stacklevel=2)
dtype = new_dtype
if dtype.names is not None:
# This is a record array. The .descr is fine. XXX: parts of the
# record array with an empty name, like padding bytes, still get
# fiddled with. This needs to be fixed in the C implementation of
# dtype().
return dtype.descr
elif not type(dtype)._legacy:
# this must be a user-defined dtype since numpy does not yet expose any
# non-legacy dtypes in the public API
#
# non-legacy dtypes don't yet have __array_interface__
# support. Instead, as a hack, we use pickle to save the array, and lie
# that the dtype is object. When the array is loaded, the descriptor is
# unpickled with the array and the object dtype in the header is
# discarded.
#
# a future NEP should define a way to serialize user-defined
# descriptors and ideally work out the possible security implications
warnings.warn("Custom dtypes are saved as python objects using the "
"pickle protocol. Loading this file requires "
"allow_pickle=True to be set.",
UserWarning, stacklevel=2)
return "|O"
else:
return dtype.str
|
Get a serializable descriptor from the dtype.
The .descr attribute of a dtype object cannot be round-tripped through
the dtype() constructor. Simple types, like dtype('float32'), have
a descr which looks like a record array with one field with '' as
a name. The dtype() constructor interprets this as a request to give
a default name. Instead, we construct descriptor that can be passed to
dtype().
Parameters
----------
dtype : dtype
The dtype of the array that will be written to disk.
Returns
-------
descr : object
An object that can be passed to `numpy.dtype()` in order to
replicate the input dtype.
|
python
|
numpy/lib/_format_impl.py
| 251
|
[
"dtype"
] | false
| 5
| 6.16
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
ClangIncludeFixerPluginAction
|
explicit ClangIncludeFixerPluginAction()
: SymbolIndexMgr(std::make_shared<SymbolIndexManager>()),
SemaSource(new IncludeFixerSemaSource(*SymbolIndexMgr,
/*MinimizeIncludePaths=*/true,
/*GenerateDiagnostics=*/true)) {}
|
Sema) but we have to keep the symbol index alive until sema is done.
|
cpp
|
clang-tools-extra/clang-include-fixer/plugin/IncludeFixerPlugin.cpp
| 33
|
[] | true
| 1
| 6
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
deduceBindMethod
|
static org.springframework.boot.context.properties.bind.BindMethod deduceBindMethod(Class<?> type) {
return deduceBindMethod(BindConstructorProvider.DEFAULT.getBindConstructor(type, false));
}
|
Deduce the {@code BindMethod} that should be used for the given type.
@param type the source type
@return the bind method to use
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java
| 300
|
[
"type"
] | true
| 1
| 6.32
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
buildToString
|
private String buildToString(ToStringFormat format) {
return switch (format) {
case DEFAULT -> buildDefaultToString();
case SYSTEM_ENVIRONMENT -> buildSimpleToString('_', (i) -> getElement(i, Form.UNIFORM));
case LEGACY_SYSTEM_ENVIRONMENT ->
buildSimpleToString('_', (i) -> getElement(i, Form.ORIGINAL).replace('-', '_'));
};
}
|
Returns {@code true} if this element is an ancestor (immediate or nested parent) of
the specified name.
@param name the name to check
@return {@code true} if this name is an ancestor
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
| 564
|
[
"format"
] |
String
| true
| 1
| 7.04
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
doGetObjectFromFactoryBean
|
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, @Nullable Class<?> requiredType, String beanName)
throws BeanCreationException {
Object object;
try {
object = (requiredType != null && factory instanceof SmartFactoryBean<?> smartFactoryBean ?
smartFactoryBean.getObject(requiredType) : factory.getObject());
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
|
Obtain an object to expose from the given FactoryBean.
@param factory the FactoryBean instance
@param beanName the name of the bean
@return the object obtained from the FactoryBean
@throws BeanCreationException if FactoryBean object creation failed
@see org.springframework.beans.factory.FactoryBean#getObject()
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java
| 197
|
[
"factory",
"requiredType",
"beanName"
] |
Object
| true
| 7
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
createCollection
|
Collection<V> createCollection(@ParametricNullness K key) {
return createCollection();
}
|
Creates the collection of values for an explicitly provided key. By default, it simply calls
{@link #createCollection()}, which is the correct behavior for most implementations. The {@link
LinkedHashMultimap} class overrides it.
@param key key to associate with values in the collection
@return an empty collection of values
|
java
|
android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
| 165
|
[
"key"
] | true
| 1
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
|
sendFetches
|
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
handleFetchSuccess(fetchTarget, data, clientResponse);
}
},
(fetchTarget, data, error) -> {
synchronized (Fetcher.this) {
handleFetchFailure(fetchTarget, data, error);
}
});
return fetchRequests.size();
}
|
Set up a fetch request for any node that we have assigned partitions for which doesn't already have
an in-flight fetch or pending fetch data.
@return number of fetches sent
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
| 105
|
[] | true
| 1
| 7.04
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
is_storage
|
def is_storage(obj: _Any, /) -> builtins.bool:
r"""Returns True if `obj` is a PyTorch storage object.
Args:
obj (Object): Object to test
Example::
>>> import torch
>>> # UntypedStorage (recommended)
>>> tensor = torch.tensor([1, 2, 3])
>>> storage = tensor.untyped_storage()
>>> torch.is_storage(storage)
True
>>>
>>> # TypedStorage (legacy)
>>> typed_storage = torch.TypedStorage(5, dtype=torch.float32)
>>> torch.is_storage(typed_storage)
True
>>>
>>> # regular tensor (should return False)
>>> torch.is_storage(tensor)
False
>>>
>>> # non-storage object
>>> torch.is_storage([1, 2, 3])
False
"""
return type(obj) in _storage_classes
|
r"""Returns True if `obj` is a PyTorch storage object.
Args:
obj (Object): Object to test
Example::
>>> import torch
>>> # UntypedStorage (recommended)
>>> tensor = torch.tensor([1, 2, 3])
>>> storage = tensor.untyped_storage()
>>> torch.is_storage(storage)
True
>>>
>>> # TypedStorage (legacy)
>>> typed_storage = torch.TypedStorage(5, dtype=torch.float32)
>>> torch.is_storage(typed_storage)
True
>>>
>>> # regular tensor (should return False)
>>> torch.is_storage(tensor)
False
>>>
>>> # non-storage object
>>> torch.is_storage([1, 2, 3])
False
|
python
|
torch/__init__.py
| 1,158
|
[
"obj"
] |
builtins.bool
| true
| 1
| 6.64
|
pytorch/pytorch
| 96,034
|
google
| false
|
format
|
public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) {
final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(date);
}
|
Formats a date/time into a specific pattern in a time zone and locale.
@param date the date to format, not null.
@param pattern the pattern to use to format the date, not null, not null.
@param timeZone the time zone to use, may be {@code null}.
@param locale the locale to use, may be {@code null}.
@return the formatted date.
|
java
|
src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java
| 303
|
[
"date",
"pattern",
"timeZone",
"locale"
] |
String
| true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
and
|
public static Boolean and(final Boolean... array) {
ObjectUtils.requireNonEmpty(array, "array");
return and(ArrayUtils.toPrimitive(array)) ? Boolean.TRUE : Boolean.FALSE;
}
|
Performs an 'and' operation on an array of Booleans.
<pre>
BooleanUtils.and(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
BooleanUtils.and(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
BooleanUtils.and(Boolean.TRUE, Boolean.FALSE) = Boolean.FALSE
BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
BooleanUtils.and(null, null) = Boolean.FALSE
</pre>
<p>
Null array elements map to false, like {@code Boolean.parseBoolean(null)} and its callers return false.
</p>
@param array an array of {@link Boolean}s
@return the result of the logical 'and' operation. That is {@code false}
if any of the parameters is {@code false} and {@code true} otherwise.
@throws NullPointerException if {@code array} is {@code null}
@throws IllegalArgumentException if {@code array} is empty.
@since 3.0.1
|
java
|
src/main/java/org/apache/commons/lang3/BooleanUtils.java
| 132
|
[] |
Boolean
| true
| 2
| 7.52
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
indexOf
|
public static int indexOf(final boolean[] array, final boolean valueToFind) {
return indexOf(array, valueToFind, 0);
}
|
Finds the index of the given value in the array.
<p>
This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
</p>
@param array the array to search for the object, may be {@code null}.
@param valueToFind the value to find.
@return the index of the value within the array, {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input.
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 2,369
|
[
"array",
"valueToFind"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
countNumberOfUnboundPrimitiveArguments
|
private int countNumberOfUnboundPrimitiveArguments() {
int count = 0;
for (int i = 0; i < this.argumentTypes.length; i++) {
if (isUnbound(i) && this.argumentTypes[i].isPrimitive()) {
count++;
}
}
return count;
}
|
Return {@code true} if the given argument type is a subclass
of the given supertype.
|
java
|
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java
| 709
|
[] | true
| 4
| 7.04
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
initAgentSystemProperties
|
public void initAgentSystemProperties(Settings settings) {
boolean tracing = TELEMETRY_TRACING_ENABLED_SETTING.get(settings);
boolean metrics = TELEMETRY_METRICS_ENABLED_SETTING.get(settings);
this.setAgentSetting("recording", Boolean.toString(tracing || metrics));
// Apply values from the settings in the cluster state
APM_AGENT_SETTINGS.getAsMap(settings).forEach(this::setAgentSetting);
}
|
Initialize APM settings from the provided settings object into the corresponding system properties.
Later updates to these settings are synchronized using update consumers.
@param settings the settings to apply
|
java
|
modules/apm/src/main/java/org/elasticsearch/telemetry/apm/internal/APMAgentSettings.java
| 68
|
[
"settings"
] |
void
| true
| 2
| 6.56
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
bind
|
<T> @Nullable T bind(ConfigurationPropertyName name, Bindable<T> target, Context context,
DataObjectPropertyBinder propertyBinder);
|
Return a bound instance or {@code null} if the {@link DataObjectBinder} does not
support the specified {@link Bindable}.
@param <T> the source type
@param name the name being bound
@param target the bindable to bind
@param context the bind context
@param propertyBinder property binder
@return a bound instance or {@code null}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DataObjectBinder.java
| 45
|
[
"name",
"target",
"context",
"propertyBinder"
] |
T
| true
| 1
| 6.48
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
toString
|
@Override
public String toString() {
// racy single-check idiom, safe because String is immutable
String result = toString;
if (result == null) {
result = computeToString();
toString = result;
}
return result;
}
|
Returns the string representation of this media type in the format described in <a
href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
|
java
|
android/guava/src/com/google/common/net/MediaType.java
| 1,227
|
[] |
String
| true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
init_PPC_32Bit
|
private static void init_PPC_32Bit() {
addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.PPC), "ppc", "power", "powerpc", "power_pc", "power_rs");
}
|
Gets a {@link Processor} object the given value {@link String}. The {@link String} must be like a value returned by the {@code "os.arch"} system
property.
@param value A {@link String} like a value returned by the {@code os.arch} System Property.
@return A {@link Processor} when it exists, else {@code null}.
|
java
|
src/main/java/org/apache/commons/lang3/ArchUtils.java
| 115
|
[] |
void
| true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
getWrapperOrPrimitiveFor
|
TypeMirror getWrapperOrPrimitiveFor(TypeMirror typeMirror) {
Class<?> candidate = getWrapperFor(typeMirror);
if (candidate != null) {
return this.env.getElementUtils().getTypeElement(candidate.getName()).asType();
}
TypeKind primitiveKind = getPrimitiveFor(typeMirror);
if (primitiveKind != null) {
return this.env.getTypeUtils().getPrimitiveType(primitiveKind);
}
return null;
}
|
Return the {@link PrimitiveType} of the specified type or {@code null} if the type
does not represent a valid wrapper type.
@param typeMirror a type
@return the primitive type or {@code null} if the type is not a wrapper type
|
java
|
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java
| 201
|
[
"typeMirror"
] |
TypeMirror
| true
| 3
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
register
|
@Override
protected void register(String description, ServletContext servletContext) {
try {
servletContext.addListener(this.listener);
}
catch (RuntimeException ex) {
throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex);
}
}
|
Return the listener to be registered.
@return the listener to be registered
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java
| 117
|
[
"description",
"servletContext"
] |
void
| true
| 2
| 6.88
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
substitutePropertyAccessExpression
|
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (node.expression.kind === SyntaxKind.SuperKeyword) {
return setTextRange(
factory.createPropertyAccessExpression(
factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel),
node.name,
),
node,
);
}
return node;
}
|
Hooks node substitutions.
@param hint The context for the emitter.
@param node The node to substitute.
|
typescript
|
src/compiler/transformers/es2018.ts
| 1,411
|
[
"node"
] | false
| 2
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
processDatabase
|
boolean processDatabase(String id, DatabaseConfiguration database) throws IOException {
final String name = database.name();
logger.debug("Processing database [{}] for configuration [{}]", name, database.id());
try (ProviderDownload downloader = downloaderFor(database)) {
if (downloader != null && downloader.validCredentials()) {
// the name that comes from the enterprise downloader cluster state doesn't include the .mmdb extension,
// but the downloading and indexing of database code expects it to be there, so we add it on here before continuing
final String fileName = name + ".mmdb";
processDatabase(fileName, downloader.checksum(), downloader.download());
return true;
} else {
logger.warn("No credentials found to download database [{}], skipping download...", id);
return false;
}
}
}
|
This method fetches the checksum and database for the given database from the Maxmind endpoint, then indexes that database
file into the .geoip_databases Elasticsearch index, deleting any old versions of the database from the index if they exist.
If the computed checksum does not match the expected checksum, an error will be logged and the database will not be put into
the Elasticsearch index.
<p>
As an implementation detail, this method retrieves the checksum of the database to download and then invokes
{@link EnterpriseGeoIpDownloader#processDatabase(String, Checksum, CheckedSupplier)} with that checksum,
deferring to that method to actually download and process the database file itself.
@param id The identifier for this database (just for logging purposes)
@param database The database to be downloaded and indexed into an Elasticsearch index
@return true if the file was processed, false if the file wasn't processed (for example if credentials haven't been configured)
@throws IOException If there is an error fetching the checksum or database file
|
java
|
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/EnterpriseGeoIpDownloader.java
| 251
|
[
"id",
"database"
] | true
| 3
| 7.92
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
removeAll
|
static Object removeAll(final Object array, final int... indices) {
if (array == null) {
return null;
}
final int length = getLength(array);
int diff = 0; // number of distinct indexes, i.e. number of entries that will be removed
final int[] clonedIndices = ArraySorter.sort(clone(indices));
// identify length of result array
if (isNotEmpty(clonedIndices)) {
int i = clonedIndices.length;
int prevIndex = length;
while (--i >= 0) {
final int index = clonedIndices[i];
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
if (index >= prevIndex) {
continue;
}
diff++;
prevIndex = index;
}
}
// create result array
final Object result = Array.newInstance(array.getClass().getComponentType(), length - diff);
if (diff < length && clonedIndices != null) {
int end = length; // index just after last copy
int dest = length - diff; // number of entries so far not copied
for (int i = clonedIndices.length - 1; i >= 0; i--) {
final int index = clonedIndices[i];
if (end - index > 1) { // same as (cp > 0)
final int cp = end - index - 1;
dest -= cp;
System.arraycopy(array, index + 1, result, dest, cp);
// After this copy, we still have room for dest items.
}
end = index;
}
if (end > 0) {
System.arraycopy(array, 0, result, 0, end);
}
}
return result;
}
|
Removes multiple array elements specified by index.
@param array source
@param indices to remove
@return new array of same type minus elements specified by unique values of {@code indices}
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 5,150
|
[
"array"
] |
Object
| true
| 12
| 7.76
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
collect
|
public <A, R> R collect(final Supplier<R> supplier, final BiConsumer<R, ? super T> accumulator, final BiConsumer<R, R> combiner) {
makeTerminated();
return stream().collect(supplier, accumulator, combiner);
}
|
Performs a mutable reduction operation on the elements of this FailableStream. A mutable reduction is one in which
the reduced value is a mutable result container, such as an {@link ArrayList}, and elements are incorporated by
updating the state of the result rather than by replacing the result. This produces a result equivalent to:
<pre>
{@code
R result = supplier.get();
for (T element : this stream)
accumulator.accept(result, element);
return result;
}
</pre>
<p>
Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can be parallelized without requiring
additional synchronization.
</p>
<p>
This is a terminal operation.
</p>
<p>
Note There are many existing classes in the JDK whose signatures are well-suited for use with method references as
arguments to {@code collect()}. For example, the following will accumulate strings into an {@link ArrayList}:
</p>
<pre>
{@code
List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
}
</pre>
<p>
The following will take a stream of strings and concatenates them into a single string:
</p>
<pre>
{@code
String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
}
</pre>
@param <R> type of the result
@param <A> Type of the accumulator.
@param supplier a function that creates a new result container. For a parallel execution, this function may be called
multiple times and must return a fresh value each time.
@param accumulator An associative, non-interfering, stateless function for incorporating an additional element into a
result
@param combiner An associative, non-interfering, stateless function for combining two values, which must be
compatible with the accumulator function
@return The result of the reduction
|
java
|
src/main/java/org/apache/commons/lang3/stream/Streams.java
| 348
|
[
"supplier",
"accumulator",
"combiner"
] |
R
| true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
_set_diag
|
def _set_diag(laplacian, value, norm_laplacian):
"""Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition.
Parameters
----------
laplacian : {ndarray, sparse matrix}
The graph laplacian.
value : float
The value of the diagonal.
norm_laplacian : bool
Whether the value of the diagonal should be changed or not.
Returns
-------
laplacian : {array, sparse matrix}
An array of matrix in a form that is well suited to fast
eigenvalue decomposition, depending on the band width of the
matrix.
"""
n_nodes = laplacian.shape[0]
# We need all entries in the diagonal to values
if not sparse.issparse(laplacian):
if norm_laplacian:
laplacian.flat[:: n_nodes + 1] = value
else:
laplacian = laplacian.tocoo()
if norm_laplacian:
diag_idx = laplacian.row == laplacian.col
laplacian.data[diag_idx] = value
# If the matrix has a small number of diagonals (as in the
# case of structured matrices coming from images), the
# dia format might be best suited for matvec products:
n_diags = np.unique(laplacian.row - laplacian.col).size
if n_diags <= 7:
# 3 or less outer diagonals on each side
laplacian = laplacian.todia()
else:
# csr has the fastest matvec and is thus best suited to
# arpack
laplacian = laplacian.tocsr()
return laplacian
|
Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition.
Parameters
----------
laplacian : {ndarray, sparse matrix}
The graph laplacian.
value : float
The value of the diagonal.
norm_laplacian : bool
Whether the value of the diagonal should be changed or not.
Returns
-------
laplacian : {array, sparse matrix}
An array of matrix in a form that is well suited to fast
eigenvalue decomposition, depending on the band width of the
matrix.
|
python
|
sklearn/manifold/_spectral_embedding.py
| 104
|
[
"laplacian",
"value",
"norm_laplacian"
] | false
| 7
| 6.08
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
or
|
default FailableIntPredicate<E> or(final FailableIntPredicate<E> other) {
Objects.requireNonNull(other);
return t -> test(t) || other.test(t);
}
|
Returns a composed {@link FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}.
@param other a predicate that will be logically-ORed with this predicate.
@return a composed {@link FailableIntPredicate} like {@link IntPredicate#and(IntPredicate)}.
@throws NullPointerException if other is null
|
java
|
src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
| 90
|
[
"other"
] | true
| 2
| 7.36
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
equals
|
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof ControlFlowPointcut that &&
this.clazz.equals(that.clazz)) && this.methodNamePatterns.equals(that.methodNamePatterns));
}
|
Determine if the given method name matches the method name pattern.
<p>This method is invoked by {@link #isMatch(String, int)}.
<p>The default implementation checks for direct equality as well as
{@code xxx*}, {@code *xxx}, {@code *xxx*}, and {@code xxx*yyy} matches.
<p>Can be overridden in subclasses — for example, to support a
different style of simple pattern matching.
@param methodName the method name to check
@param methodNamePattern the method name pattern
@return {@code true} if the method name matches the pattern
@since 6.1
@see #isMatch(String, int)
@see PatternMatchUtils#simpleMatch(String, String)
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/ControlFlowPointcut.java
| 237
|
[
"other"
] | true
| 4
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
forward
|
def forward(self, x, lengths):
"""
:param x: The input of size BxCxDxT
:param lengths: The actual length of each sequence in the batch
:return: Masked output from the module
"""
for module in self.seq_module:
x = module(x)
mask = torch.BoolTensor(x.size()).fill_(0)
if x.is_cuda:
mask = mask.cuda()
for i, length in enumerate(lengths):
length = length.item()
if (mask[i].size(2) - length) > 0:
mask[i].narrow(2, length, mask[i].size(2) - length).fill_(1)
x = x.masked_fill(mask, 0)
return x, lengths
|
:param x: The input of size BxCxDxT
:param lengths: The actual length of each sequence in the batch
:return: Masked output from the module
|
python
|
benchmarks/functional_autograd_benchmark/torchaudio_models.py
| 153
|
[
"self",
"x",
"lengths"
] | false
| 5
| 6.64
|
pytorch/pytorch
| 96,034
|
sphinx
| false
|
|
telemetryReporter
|
public static Optional<ClientTelemetryReporter> telemetryReporter(String clientId, AbstractConfig config) {
if (!config.getBoolean(CommonClientConfigs.ENABLE_METRICS_PUSH_CONFIG)) {
return Optional.empty();
}
ClientTelemetryReporter telemetryReporter = new ClientTelemetryReporter(Time.SYSTEM);
telemetryReporter.configure(config.originals(Collections.singletonMap(CommonClientConfigs.CLIENT_ID_CONFIG, clientId)));
return Optional.of(telemetryReporter);
}
|
Log warning if the exponential backoff is disabled due to initial backoff value is greater than max backoff value.
@param config The config object.
|
java
|
clients/src/main/java/org/apache/kafka/clients/CommonClientConfigs.java
| 321
|
[
"clientId",
"config"
] | true
| 2
| 6.56
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
_upsample
|
def _upsample(self, method, limit: int | None = None, fill_value=None):
"""
Parameters
----------
method : string {'backfill', 'bfill', 'pad',
'ffill', 'asfreq'} method for upsampling
limit : int, default None
Maximum size gap to fill when reindexing
fill_value : scalar, default None
Value to use for missing values
"""
if self._from_selection:
raise ValueError(
"Upsampling from level= or on= selection "
"is not supported, use .set_index(...) "
"to explicitly set index to datetime-like"
)
ax = self.ax
obj = self._selected_obj
binner = self.binner
res_index = self._adjust_binner_for_upsample(binner)
# if index exactly matches target grid (same freq & alignment), use fast path
if (
limit is None
and to_offset(ax.inferred_freq) == self.freq
and len(obj) == len(res_index)
and obj.index.equals(res_index)
):
result = obj.copy()
result.index = res_index
else:
if method == "asfreq":
method = None
result = obj.reindex(
res_index, method=method, limit=limit, fill_value=fill_value
)
return self._wrap_result(result)
|
Parameters
----------
method : string {'backfill', 'bfill', 'pad',
'ffill', 'asfreq'} method for upsampling
limit : int, default None
Maximum size gap to fill when reindexing
fill_value : scalar, default None
Value to use for missing values
|
python
|
pandas/core/resample.py
| 2,110
|
[
"self",
"method",
"limit",
"fill_value"
] | true
| 8
| 6.08
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
get_batch_is_authorized_single_result
|
def get_batch_is_authorized_single_result(
self,
*,
batch_is_authorized_results: list[dict],
request: IsAuthorizedRequest,
user: AwsAuthManagerUser,
) -> dict:
"""
Get a specific authorization result from the output of ``get_batch_is_authorized_results``.
:param batch_is_authorized_results: the response from the ``batch_is_authorized`` API
:param request: the request information. Used to find the result in the response.
:param user: the user
"""
request_payload = self._build_is_authorized_request_payload(request, user)
for result in batch_is_authorized_results:
if result["request"] == request_payload:
return result
self.log.error(
"Could not find the authorization result for request %s in results %s.",
request_payload,
batch_is_authorized_results,
)
raise AirflowException("Could not find the authorization result.")
|
Get a specific authorization result from the output of ``get_batch_is_authorized_results``.
:param batch_is_authorized_results: the response from the ``batch_is_authorized`` API
:param request: the request information. Used to find the result in the response.
:param user: the user
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/auth_manager/avp/facade.py
| 208
|
[
"self",
"batch_is_authorized_results",
"request",
"user"
] |
dict
| true
| 3
| 6.72
|
apache/airflow
| 43,597
|
sphinx
| false
|
iterator
|
@Override
public Iterator<Record> iterator() {
if (count() == 0)
return Collections.emptyIterator();
if (!isCompressed())
return uncompressedIterator();
// for a normal iterator, we cannot ensure that the underlying compression stream is closed,
// so we decompress the full record set here. Use cases which call for a lower memory footprint
// can use `streamingIterator` at the cost of additional complexity
try (CloseableIterator<Record> iterator = compressedIterator(BufferSupplier.NO_CACHING, false)) {
List<Record> records = new ArrayList<>(count());
while (iterator.hasNext())
records.add(iterator.next());
return records.iterator();
}
}
|
Gets the base timestamp of the batch which is used to calculate the record timestamps from the deltas.
@return The base timestamp
|
java
|
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
| 319
|
[] | true
| 4
| 8.24
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
join
|
public static String join(String separator, char... array) {
checkNotNull(separator);
int len = array.length;
if (len == 0) {
return "";
}
StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1));
builder.append(array[0]);
for (int i = 1; i < len; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
|
Returns a string containing the supplied {@code char} values separated by {@code separator}.
For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}.
@param separator the text that should appear between consecutive values in the resulting string
(but not at the start or end)
@param array an array of {@code char} values, possibly empty
|
java
|
android/guava/src/com/google/common/primitives/Chars.java
| 370
|
[
"separator"
] |
String
| true
| 3
| 6.56
|
google/guava
| 51,352
|
javadoc
| false
|
isHostType
|
function isHostType(object, property) {
if (object == null) {
return false;
}
var type = typeof object[property];
return !rePrimitive.test(type) && (type != 'object' || !!object[property]);
}
|
Host objects can return type values that are different from their actual
data type. The objects we are concerned with usually return non-primitive
types of "object", "function", or "unknown".
@private
@param {*} object The owner of the property.
@param {string} property The property to check.
@returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
|
javascript
|
perf/perf.js
| 167
|
[
"object",
"property"
] | false
| 4
| 6.24
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
tearDown
|
@TearDown(Level.Trial)
public void tearDown() {
if (executorService != null) {
executorService.shutdown();
try {
if (executorService.awaitTermination(30, TimeUnit.SECONDS) == false) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
|
Shuts down the executor service after the trial completes.
|
java
|
benchmarks/src/main/java/org/elasticsearch/benchmark/search/query/range/DateFieldMapperDocValuesSkipperBenchmark.java
| 332
|
[] |
void
| true
| 4
| 6.88
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
EffectWithState
|
function EffectWithState() {
const [didMount, setDidMount] = useState(0);
const renderCountRef = useRef(0);
renderCountRef.current++;
useLayoutEffect(() => {
if (!didMount) {
setDidMount(true);
}
}, [didMount]);
return (
<ul>
<li>Rendered {renderCountRef.current} times</li>
{didMount && <li>Mounted!</li>}
</ul>
);
}
|
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.
|
javascript
|
packages/react-devtools-shell/src/multi/right.js
| 20
|
[] | false
| 3
| 6.24
|
facebook/react
| 241,750
|
jsdoc
| false
|
|
copy
|
private Options copy(Consumer<EnumSet<Option>> processor) {
EnumSet<Option> options = (!this.options.isEmpty()) ? EnumSet.copyOf(this.options)
: EnumSet.noneOf(Option.class);
processor.accept(options);
return new Options(options);
}
|
Create a new {@link Options} instance that contains the options in this set
including the given option.
@param option the option to include
@return a new {@link Options} instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigData.java
| 243
|
[
"processor"
] |
Options
| true
| 2
| 8.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
buildListOffsetsRequests
|
private List<NetworkClientDelegate.UnsentRequest> buildListOffsetsRequests(
final Map<TopicPartition, Long> timestampsToSearch,
final boolean requireTimestamps,
final ListOffsetsRequestState listOffsetsRequestState) {
log.debug("Building ListOffsets request for partitions {}", timestampsToSearch);
Map<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> timestampsToSearchByNode =
groupListOffsetRequests(timestampsToSearch, Optional.of(listOffsetsRequestState));
if (timestampsToSearchByNode.isEmpty()) {
throw new StaleMetadataException();
}
final List<NetworkClientDelegate.UnsentRequest> unsentRequests = new ArrayList<>();
MultiNodeRequest multiNodeRequest = new MultiNodeRequest(timestampsToSearchByNode.size());
multiNodeRequest.onComplete((multiNodeResult, error) -> {
// Done sending request to a set of known leaders
if (error == null) {
listOffsetsRequestState.fetchedOffsets.putAll(multiNodeResult.fetchedOffsets);
listOffsetsRequestState.addPartitionsToRetry(multiNodeResult.partitionsToRetry);
offsetFetcherUtils.updateSubscriptionState(multiNodeResult.fetchedOffsets,
isolationLevel);
if (listOffsetsRequestState.remainingToSearch.isEmpty()) {
ListOffsetResult listOffsetResult =
new ListOffsetResult(listOffsetsRequestState.fetchedOffsets,
listOffsetsRequestState.remainingToSearch.keySet());
listOffsetsRequestState.globalResult.complete(listOffsetResult);
} else {
requestsToRetry.add(listOffsetsRequestState);
metadata.requestUpdate(false);
}
} else {
log.debug("ListOffsets request failed with error", error);
listOffsetsRequestState.globalResult.completeExceptionally(error);
}
});
for (Map.Entry<Node, Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition>> entry : timestampsToSearchByNode.entrySet()) {
Node node = entry.getKey();
CompletableFuture<ListOffsetResult> partialResult = buildListOffsetRequestToNode(
node,
entry.getValue(),
requireTimestamps,
unsentRequests);
partialResult.whenComplete((result, error) -> {
if (error != null) {
multiNodeRequest.resultFuture.completeExceptionally(error);
} else {
multiNodeRequest.addPartialResult(result);
}
});
}
return unsentRequests;
}
|
Build ListOffsets requests to fetch offsets by target times for the specified partitions.
@param timestampsToSearch the mapping between partitions and target time
@param requireTimestamps true if we should fail with an UnsupportedVersionException if the broker does
not support fetching precise timestamps for offsets
@return A list of
{@link org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest}
that can be polled to obtain the corresponding timestamps and offsets.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java
| 554
|
[
"timestampsToSearch",
"requireTimestamps",
"listOffsetsRequestState"
] | true
| 5
| 7.6
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
loadPreloadModules
|
function loadPreloadModules() {
// For user code, we preload modules if `-r` is passed
const preloadModules = getOptionValue('--require');
if (preloadModules && preloadModules.length > 0) {
const {
Module: {
_preloadModules,
},
} = require('internal/modules/cjs/loader');
_preloadModules(preloadModules);
}
}
|
Patch the process object with legacy properties and normalizations.
Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`.
Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found.
@param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of
the main entry point.
@returns {string}
|
javascript
|
lib/internal/process/pre_execution.js
| 700
|
[] | false
| 3
| 6.96
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
resolvePasswordSetting
|
private char[] resolvePasswordSetting(String secureSettingKey, String legacySettingKey) {
final char[] securePassword = resolveSecureSetting(secureSettingKey, null);
final String legacyPassword = stringSetting(legacySettingKey);
if (securePassword == null) {
if (legacyPassword == null) {
return EMPTY_PASSWORD;
} else {
return legacyPassword.toCharArray();
}
} else {
if (legacyPassword != null) {
throw new SslConfigException(
"cannot specify both [" + settingPrefix + secureSettingKey + "] and [" + settingPrefix + legacySettingKey + "]"
);
} else {
return securePassword;
}
}
}
|
Resolve all necessary configuration settings, and load a {@link SslConfiguration}.
@param basePath The base path to use for any settings that represent file paths. Typically points to the Elasticsearch
configuration directory.
@throws SslConfigException For any problems with the configuration, or with loading the required SSL classes.
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java
| 424
|
[
"secureSettingKey",
"legacySettingKey"
] | true
| 4
| 6.24
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
hash
|
static int hash(int initialHash, CharSequence charSequence, boolean addEndSlash) {
if (charSequence == null || charSequence.isEmpty()) {
return (!addEndSlash) ? EMPTY_HASH : EMPTY_SLASH_HASH;
}
boolean endsWithSlash = charSequence.charAt(charSequence.length() - 1) == '/';
int hash = initialHash;
if (charSequence instanceof String && initialHash == 0) {
// We're compatible with String.hashCode and it might be already calculated
hash = charSequence.hashCode();
}
else {
for (int i = 0; i < charSequence.length(); i++) {
char ch = charSequence.charAt(i);
hash = 31 * hash + ch;
}
}
hash = (addEndSlash && !endsWithSlash) ? 31 * hash + '/' : hash;
debug.log("%s calculated for charsequence '%s' (addEndSlash=%s)", hash, charSequence, endsWithSlash);
return hash;
}
|
Return a hash for a char sequence, optionally appending '/'.
@param initialHash the initial hash value
@param charSequence the source char sequence
@param addEndSlash if slash should be added to the string if it's not already
present
@return the hash
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipString.java
| 71
|
[
"initialHash",
"charSequence",
"addEndSlash"
] | true
| 9
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
getThrowableList
|
public static List<Throwable> getThrowableList(Throwable throwable) {
final List<Throwable> list = new ArrayList<>();
while (throwable != null && !list.contains(throwable)) {
list.add(throwable);
throwable = throwable.getCause();
}
return list;
}
|
Gets the list of {@link Throwable} objects in the
exception chain.
<p>A throwable without cause will return a list containing
one element - the input throwable.
A throwable with one cause will return a list containing
two elements. - the input throwable and the cause throwable.
A {@code null} throwable will return a list of size zero.</p>
<p>This method handles recursive cause chains that might
otherwise cause infinite loops. The cause chain is processed until
the end, or until the next item in the chain is already
in the result list.</p>
@param throwable the throwable to inspect, may be null.
@return the list of throwables, never null.
@since 2.2
|
java
|
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
| 513
|
[
"throwable"
] | true
| 3
| 8.24
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
consume
|
public void consume(PointError pointError) {
if (length > 1) {
// we need at least three points to calculate the error of the middle point
points[length - 1].error = calculator.calculateError(points[length - 2], points[length - 1], pointError);
queue.add(points[length - 1]);
}
if (length == maxPoints) {
// Remove point with the lowest error
PointError toRemove = queue.remove();
removeAndAdd(toRemove.index, pointError);
notifyMonitorPointRemoved(toRemove);
} else {
this.points[length] = pointError;
length++;
notifyMonitorPointAdded();
}
}
|
Consume a single point on the stream of points to be simplified.
No memory management of the points passed in is done, so only use this call if you manage these objects from calling code.
|
java
|
libs/geo/src/main/java/org/elasticsearch/geometry/simplify/StreamingGeometrySimplifier.java
| 81
|
[
"pointError"
] |
void
| true
| 3
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
apiVersion
|
public ApiVersion apiVersion(ApiKeys apiKey) {
return supportedVersions.get(apiKey);
}
|
Get the version information for a given API.
@param apiKey The api key to lookup
@return The api version information from the broker or null if it is unsupported
|
java
|
clients/src/main/java/org/apache/kafka/clients/NodeApiVersions.java
| 249
|
[
"apiKey"
] |
ApiVersion
| true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
read
|
@Override
public synchronized int read() throws IOException {
checkOpen();
requireNonNull(seq); // safe because of checkOpen
return hasRemaining() ? seq.charAt(pos++) : -1;
}
|
Creates a new reader wrapping the given character sequence.
|
java
|
android/guava/src/com/google/common/io/CharSequenceReader.java
| 92
|
[] | true
| 2
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
|
lookupMethods
|
Map<MethodKey, CheckMethod> lookupMethods(Class<?> clazz) throws ClassNotFoundException;
|
This method uses the method names of the provided class to identify the JDK method to instrument; it examines all methods prefixed
by {@code check$}, and parses the rest of the name to extract the JDK method:
<ul>
<li>
Instance methods have the fully qualified class name (with . replaced by _), followed by $, followed by the method name. Example:
{@link org.elasticsearch.entitlement.bridge.EntitlementChecker#check$java_lang_Runtime$halt}
</li>
<li>
Static methods have the fully qualified class name (with . replaced by _), followed by $$, followed by the method name. Example:
{@link org.elasticsearch.entitlement.bridge.EntitlementChecker#check$java_lang_System$$exit}
</li>
<li>
Constructors have the fully qualified class name (with . replaced by _), followed by $ and nothing else. Example:
{@link org.elasticsearch.entitlement.bridge.EntitlementChecker#check$java_lang_ClassLoader$}
</li>
</ul>
<p>
<strong>NOTE:</strong> look up of methods using this convention is the primary way we use to identify which methods to instrument,
but other methods can be added to the map of methods to instrument. See
{@link org.elasticsearch.entitlement.initialization.EntitlementInitialization#initialize} for details.
</p>
@param clazz the class to inspect to find methods to instrument
@throws ClassNotFoundException if the class is not defined or cannot be inspected
|
java
|
libs/entitlement/src/main/java/org/elasticsearch/entitlement/instrumentation/InstrumentationService.java
| 51
|
[
"clazz"
] | true
| 1
| 6.24
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
doubleValue
|
@Override
public double doubleValue() {
return (double) numerator / (double) denominator;
}
|
Gets the fraction as a {@code double}. This calculates the fraction
as the numerator divided by denominator.
@return the fraction as a {@code double}
|
java
|
src/main/java/org/apache/commons/lang3/math/Fraction.java
| 627
|
[] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
create
|
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
|
Creates an object that inherits from the `prototype` object. If a
`properties` object is given, its own enumerable string keyed properties
are assigned to the created object.
@static
@memberOf _
@since 2.3.0
@category Object
@param {Object} prototype The object to inherit from.
@param {Object} [properties] The properties to assign to the object.
@returns {Object} Returns the new object.
@example
function Shape() {
this.x = 0;
this.y = 0;
}
function Circle() {
Shape.call(this);
}
Circle.prototype = _.create(Shape.prototype, {
'constructor': Circle
});
var circle = new Circle;
circle instanceof Circle;
// => true
circle instanceof Shape;
// => true
|
javascript
|
lodash.js
| 12,867
|
[
"prototype",
"properties"
] | false
| 2
| 7.44
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
get_db_instance_status
|
def get_db_instance_status(self, instance_id: str) -> str:
"""
Get the status of a Neptune instance.
:param instance_id: The ID of the instance to get the status of.
:return: The status of the instance.
"""
return self.conn.describe_db_instances(DBInstanceIdentifier=instance_id)["DBInstances"][0][
"DBInstanceStatus"
]
|
Get the status of a Neptune instance.
:param instance_id: The ID of the instance to get the status of.
:return: The status of the instance.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/neptune.py
| 93
|
[
"self",
"instance_id"
] |
str
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
locate
|
private static long locate(DataBlock dataBlock, ByteBuffer buffer) throws IOException {
long endPos = dataBlock.size();
debug.log("Finding EndOfCentralDirectoryRecord starting at end position %s", endPos);
while (endPos > 0) {
buffer.clear();
long totalRead = dataBlock.size() - endPos;
if (totalRead > MAXIMUM_SIZE) {
throw new IOException(
"Zip 'End Of Central Directory Record' not found after reading " + totalRead + " bytes");
}
long startPos = endPos - buffer.limit();
if (startPos < 0) {
buffer.limit((int) startPos + buffer.limit());
startPos = 0;
}
debug.log("Finding EndOfCentralDirectoryRecord from %s with limit %s", startPos, buffer.limit());
dataBlock.readFully(buffer, startPos);
int offset = findInBuffer(buffer);
if (offset >= 0) {
debug.log("Found EndOfCentralDirectoryRecord at %s + %s", startPos, offset);
return startPos + offset;
}
endPos = endPos - BUFFER_SIZE + MINIMUM_SIZE;
}
throw new IOException("Zip 'End Of Central Directory Record' not found after reading entire data block");
}
|
Create a new {@link ZipEndOfCentralDirectoryRecord} instance from the specified
{@link DataBlock} by searching backwards from the end until a valid record is
located.
@param dataBlock the source data block
@return the {@link Located located} {@link ZipEndOfCentralDirectoryRecord}
@throws IOException if the {@link ZipEndOfCentralDirectoryRecord} cannot be read
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipEndOfCentralDirectoryRecord.java
| 113
|
[
"dataBlock",
"buffer"
] | true
| 5
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
unused
|
public Set<String> unused() {
Set<String> keys = new HashSet<>(originals.keySet());
keys.removeAll(used);
return keys;
}
|
Called directly after user configs got parsed (and thus default values got set).
This allows to change default values for "secondary defaults" if required.
@param parsedValues unmodifiable map of current configuration
@return a map of updates that should be applied to the configuration (will be validated to prevent bad updates)
|
java
|
clients/src/main/java/org/apache/kafka/common/config/AbstractConfig.java
| 237
|
[] | true
| 1
| 6.4
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
check_below_min_count
|
def check_below_min_count(
shape: tuple[int, ...], mask: npt.NDArray[np.bool_] | None, min_count: int
) -> bool:
"""
Check for the `min_count` keyword. Returns True if below `min_count` (when
missing value should be returned from the reduction).
Parameters
----------
shape : tuple
The shape of the values (`values.shape`).
mask : ndarray[bool] or None
Boolean numpy array (typically of same shape as `shape`) or None.
min_count : int
Keyword passed through from sum/prod call.
Returns
-------
bool
"""
if min_count > 0:
if mask is None:
# no missing values, only check size
non_nulls = np.prod(shape)
else:
non_nulls = mask.size - mask.sum()
if non_nulls < min_count:
return True
return False
|
Check for the `min_count` keyword. Returns True if below `min_count` (when
missing value should be returned from the reduction).
Parameters
----------
shape : tuple
The shape of the values (`values.shape`).
mask : ndarray[bool] or None
Boolean numpy array (typically of same shape as `shape`) or None.
min_count : int
Keyword passed through from sum/prod call.
Returns
-------
bool
|
python
|
pandas/core/nanops.py
| 1,581
|
[
"shape",
"mask",
"min_count"
] |
bool
| true
| 5
| 7.04
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
append
|
public ConfigurationPropertyName append(@Nullable ConfigurationPropertyName suffix) {
if (suffix == null) {
return this;
}
return new ConfigurationPropertyName(this.elements.append(suffix.elements));
}
|
Create a new {@link ConfigurationPropertyName} by appending the given suffix.
@param suffix the elements to append
@return a new {@link ConfigurationPropertyName}
@since 2.5.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
| 227
|
[
"suffix"
] |
ConfigurationPropertyName
| true
| 2
| 7.44
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
shared_task
|
def shared_task(*args, **kwargs):
"""Create shared task (decorator).
This can be used by library authors to create tasks that'll work
for any app environment.
Returns:
~celery.local.Proxy: A proxy that always takes the task from the
current apps task registry.
Example:
>>> from celery import Celery, shared_task
>>> @shared_task
... def add(x, y):
... return x + y
...
>>> app1 = Celery(broker='amqp://')
>>> add.app is app1
True
>>> app2 = Celery(broker='redis://')
>>> add.app is app2
True
"""
def create_shared_task(**options):
def __inner(fun):
name = options.get('name')
# Set as shared task so that unfinalized apps,
# and future apps will register a copy of this task.
_state.connect_on_app_finalize(
lambda app: app._task_from_fun(fun, **options)
)
# Force all finalized apps to take this task as well.
for app in _state._get_active_apps():
if app.finalized:
with app._finalize_mutex:
app._task_from_fun(fun, **options)
# Return a proxy that always gets the task from the current
# apps task registry.
def task_by_cons():
app = _state.get_current_app()
return app.tasks[
name or app.gen_task_name(fun.__name__, fun.__module__)
]
return Proxy(task_by_cons)
return __inner
if len(args) == 1 and callable(args[0]):
return create_shared_task(**kwargs)(args[0])
return create_shared_task(*args, **kwargs)
|
Create shared task (decorator).
This can be used by library authors to create tasks that'll work
for any app environment.
Returns:
~celery.local.Proxy: A proxy that always takes the task from the
current apps task registry.
Example:
>>> from celery import Celery, shared_task
>>> @shared_task
... def add(x, y):
... return x + y
...
>>> app1 = Celery(broker='amqp://')
>>> add.app is app1
True
>>> app2 = Celery(broker='redis://')
>>> add.app is app2
True
|
python
|
celery/app/__init__.py
| 24
|
[] | false
| 6
| 8.88
|
celery/celery
| 27,741
|
unknown
| false
|
|
toByteArray
|
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
|
Reads all bytes from a file into a byte array.
<p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
@param file the file to read from
@return a byte array containing all the bytes from file
@throws IllegalArgumentException if the file is bigger than the largest possible byte array
(2^31 - 1)
@throws IOException if an I/O error occurs
|
java
|
android/guava/src/com/google/common/io/Files.java
| 236
|
[
"file"
] | true
| 1
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
|
BinaryData
|
BinaryData(BinaryData &&) = default;
|
from \p Address - Section.getAddress() when the data has been reordered.
|
cpp
|
bolt/include/bolt/Core/BinaryData.h
| 79
|
[] | true
| 2
| 6.48
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
getPath
|
private Path getPath() {
if (this.path == null) {
this.pathLock.lock();
try {
if (this.path == null) {
String hash = HexFormat.of().withUpperCase().formatHex(generateHash(this.sourceClass));
this.path = createDirectory(getTempDirectory().resolve(hash));
}
}
finally {
this.pathLock.unlock();
}
}
Path path = this.path;
Assert.state(path != null, "'path' must not be null");
return path;
}
|
Return a subdirectory of the application temp.
@param subDir the subdirectory name
@return a subdirectory
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java
| 98
|
[] |
Path
| true
| 3
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
put
|
@CanIgnoreReturnValue
@Override
public @Nullable V put(@ParametricNullness K key, @ParametricNullness V value) {
return put(key, value, false);
}
|
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
|
android/guava/src/com/google/common/collect/HashBiMap.java
| 281
|
[
"key",
"value"
] |
V
| true
| 1
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
_median_nancheck
|
def _median_nancheck(data, result, axis):
"""
Utility function to check median result from data for NaN values at the end
and return NaN in that case. Input result can also be a MaskedArray.
Parameters
----------
data : array
Sorted input data to median function
result : Array or MaskedArray
Result of median function.
axis : int
Axis along which the median was computed.
Returns
-------
result : scalar or ndarray
Median or NaN in axes which contained NaN in the input. If the input
was an array, NaN will be inserted in-place. If a scalar, either the
input itself or a scalar NaN.
"""
if data.size == 0:
return result
potential_nans = data.take(-1, axis=axis)
n = np.isnan(potential_nans)
# masked NaN values are ok, although for masked the copyto may fail for
# unmasked ones (this was always broken) when the result is a scalar.
if np.ma.isMaskedArray(n):
n = n.filled(False)
if not n.any():
return result
# Without given output, it is possible that the current result is a
# numpy scalar, which is not writeable. If so, just return nan.
if isinstance(result, np.generic):
return potential_nans
# Otherwise copy NaNs (if there are any)
np.copyto(result, potential_nans, where=n)
return result
|
Utility function to check median result from data for NaN values at the end
and return NaN in that case. Input result can also be a MaskedArray.
Parameters
----------
data : array
Sorted input data to median function
result : Array or MaskedArray
Result of median function.
axis : int
Axis along which the median was computed.
Returns
-------
result : scalar or ndarray
Median or NaN in axes which contained NaN in the input. If the input
was an array, NaN will be inserted in-place. If a scalar, either the
input itself or a scalar NaN.
|
python
|
numpy/lib/_utils_impl.py
| 407
|
[
"data",
"result",
"axis"
] | false
| 5
| 6.08
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
attributesForRepeatable
|
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
Class<? extends Annotation> annotationType, Class<? extends Annotation> containerType,
Predicate<MergedAnnotation<? extends Annotation>> predicate) {
return metadata.getMergedRepeatableAnnotationAttributes(annotationType, containerType, predicate, false, false);
}
|
Register all relevant annotation post processors in the given registry.
@param registry the registry to operate on
@param source the configuration source element (already extracted)
that this registration was triggered from. May be {@code null}.
@return a Set of BeanDefinitionHolders, containing all bean definitions
that have actually been registered by this call
|
java
|
spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
| 297
|
[
"metadata",
"annotationType",
"containerType",
"predicate"
] | true
| 1
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
findPathTo
|
private @Nullable ExampleStackTrace findPathTo(LockGraphNode node, Set<LockGraphNode> seen) {
if (!seen.add(this)) {
return null; // Already traversed this node.
}
ExampleStackTrace found = allowedPriorLocks.get(node);
if (found != null) {
return found; // Found a path ending at the node!
}
// Recurse the edges.
for (Entry<LockGraphNode, ExampleStackTrace> entry : allowedPriorLocks.entrySet()) {
LockGraphNode preAcquiredLock = entry.getKey();
found = preAcquiredLock.findPathTo(node, seen);
if (found != null) {
// One of this node's allowedPriorLocks found a path. Prepend an
// ExampleStackTrace(preAcquiredLock, this) to the returned chain of
// ExampleStackTraces.
ExampleStackTrace path = new ExampleStackTrace(preAcquiredLock, this);
path.setStackTrace(entry.getValue().getStackTrace());
path.initCause(found);
return path;
}
}
return null;
}
|
Performs a depth-first traversal of the graph edges defined by each node's {@code
allowedPriorLocks} to find a path between {@code this} and the specified {@code lock}.
@return If a path was found, a chained {@link ExampleStackTrace} illustrating the path to the
{@code lock}, or {@code null} if no path was found.
|
java
|
android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
| 685
|
[
"node",
"seen"
] |
ExampleStackTrace
| true
| 4
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
leaderEpoch
|
public Optional<Integer> leaderEpoch() {
return leaderEpoch;
}
|
Get the leader epoch for the partition.
@return The leader epoch of the partition.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/SharePartitionOffsetInfo.java
| 62
|
[] | true
| 1
| 6.96
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
toString
|
@Override
public String toString() {
return "RecordBatch(magic=" + magic() + ", offsets=[" + baseOffset() + ", " + lastOffset() + "], " +
"sequence=[" + baseSequence() + ", " + lastSequence() + "], " +
"partitionLeaderEpoch=" + partitionLeaderEpoch() + ", " +
"isTransactional=" + isTransactional() + ", isControlBatch=" + isControlBatch() + ", " +
"compression=" + compressionType() + ", timestampType=" + timestampType() + ", crc=" + checksum() + ")";
}
|
Gets the base timestamp of the batch which is used to calculate the record timestamps from the deltas.
@return The base timestamp
|
java
|
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
| 501
|
[] |
String
| true
| 1
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
visitCallExpressionWithPotentialCapturedThisAssignment
|
function visitCallExpressionWithPotentialCapturedThisAssignment(node: CallExpression, assignToCapturedThis: boolean): CallExpression | BinaryExpression {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
if (
node.transformFlags & TransformFlags.ContainsRestOrSpread ||
node.expression.kind === SyntaxKind.SuperKeyword ||
isSuperProperty(skipOuterExpressions(node.expression))
) {
const { target, thisArg } = factory.createCallBinding(node.expression, hoistVariableDeclaration);
if (node.expression.kind === SyntaxKind.SuperKeyword) {
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
}
let resultingCall: CallExpression | BinaryExpression;
if (node.transformFlags & TransformFlags.ContainsRestOrSpread) {
// [source]
// f(...a, b)
// x.m(...a, b)
// super(...a, b)
// super.m(...a, b) // in static
// super.m(...a, b) // in instance
//
// [output]
// f.apply(void 0, a.concat([b]))
// (_a = x).m.apply(_a, a.concat([b]))
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
resultingCall = factory.createFunctionApplyCall(
Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)),
node.expression.kind === SyntaxKind.SuperKeyword ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)),
transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false),
);
}
else {
// [source]
// super(a)
// super.m(a) // in static
// super.m(a) // in instance
//
// [output]
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
resultingCall = setTextRange(
factory.createFunctionCallCall(
Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)),
node.expression.kind === SyntaxKind.SuperKeyword ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)),
visitNodes(node.arguments, visitor, isExpression),
),
node,
);
}
if (node.expression.kind === SyntaxKind.SuperKeyword) {
const initializer = factory.createLogicalOr(
resultingCall,
createActualThis(),
);
resultingCall = assignToCapturedThis
? factory.createAssignment(createCapturedThis(), initializer)
: initializer;
}
return setOriginalNode(resultingCall, node);
}
if (isSuperCall(node)) {
hierarchyFacts |= HierarchyFacts.CapturedLexicalThis;
}
return visitEachChild(node, visitor, context);
}
|
Visits a CallExpression that contains either a spread element or `super`.
@param node a CallExpression.
|
typescript
|
src/compiler/transformers/es2015.ts
| 4,522
|
[
"node",
"assignToCapturedThis"
] | true
| 12
| 6.64
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
loads
|
def loads(s: str | bytes, **kwargs: t.Any) -> t.Any:
"""Deserialize data as JSON.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.loads() <flask.json.provider.JSONProvider.loads>`
method, otherwise it will use :func:`json.loads`.
:param s: Text or UTF-8 bytes.
:param kwargs: Arguments passed to the ``loads`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.loads``, allowing an app to override
the behavior.
.. versionchanged:: 2.0
``encoding`` will be removed in Flask 2.1. The data must be a
string or UTF-8 bytes.
.. versionchanged:: 1.0.3
``app`` can be passed directly, rather than requiring an app
context for configuration.
"""
if current_app:
return current_app.json.loads(s, **kwargs)
return _json.loads(s, **kwargs)
|
Deserialize data as JSON.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.loads() <flask.json.provider.JSONProvider.loads>`
method, otherwise it will use :func:`json.loads`.
:param s: Text or UTF-8 bytes.
:param kwargs: Arguments passed to the ``loads`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.loads``, allowing an app to override
the behavior.
.. versionchanged:: 2.0
``encoding`` will be removed in Flask 2.1. The data must be a
string or UTF-8 bytes.
.. versionchanged:: 1.0.3
``app`` can be passed directly, rather than requiring an app
context for configuration.
|
python
|
src/flask/json/__init__.py
| 77
|
[
"s"
] |
t.Any
| true
| 2
| 6.4
|
pallets/flask
| 70,946
|
sphinx
| false
|
transformAndEmitContinueStatement
|
function transformAndEmitContinueStatement(node: ContinueStatement): void {
const label = findContinueTarget(node.label ? idText(node.label) : undefined);
if (label > 0) {
emitBreak(label, /*location*/ node);
}
else {
// invalid continue without a containing loop. Leave the node as is, per #17875.
emitStatement(node);
}
}
|
Visits an ElementAccessExpression that contains a YieldExpression.
@param node The node to visit.
|
typescript
|
src/compiler/transformers/generators.ts
| 1,742
|
[
"node"
] | true
| 4
| 6.24
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
hermeadd
|
def hermeadd(c1, c2):
"""
Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the Hermite series of their sum.
See Also
--------
hermesub, hermemulx, hermemul, hermediv, hermepow
Notes
-----
Unlike multiplication, division, etc., the sum of two Hermite series
is a Hermite series (without having to "reproject" the result onto
the basis set) so addition, just like that of "standard" polynomials,
is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite_e import hermeadd
>>> hermeadd([1, 2, 3], [1, 2, 3, 4])
array([2., 4., 6., 4.])
"""
return pu._add(c1, c2)
|
Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the Hermite series of their sum.
See Also
--------
hermesub, hermemulx, hermemul, hermediv, hermepow
Notes
-----
Unlike multiplication, division, etc., the sum of two Hermite series
is a Hermite series (without having to "reproject" the result onto
the basis set) so addition, just like that of "standard" polynomials,
is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite_e import hermeadd
>>> hermeadd([1, 2, 3], [1, 2, 3, 4])
array([2., 4., 6., 4.])
|
python
|
numpy/polynomial/hermite_e.py
| 312
|
[
"c1",
"c2"
] | false
| 1
| 6.32
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
buildNewKeyStore
|
private static KeyStore buildNewKeyStore(String type) throws GeneralSecurityException {
KeyStore keyStore = KeyStore.getInstance(type);
try {
keyStore.load(null, null);
} catch (IOException e) {
// This should never happen so callers really shouldn't be forced to deal with it themselves.
throw new SslConfigException("Unexpected error initializing a new in-memory keystore", e);
}
return keyStore;
}
|
Construct an in-memory keystore with multiple trusted cert entries.
@param certificates The root certificates to trust
|
java
|
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/KeyStoreUtil.java
| 128
|
[
"type"
] |
KeyStore
| true
| 2
| 6.56
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
get_window_bounds
|
def get_window_bounds(
self,
num_values: int = 0,
min_periods: int | None = None,
center: bool | None = None,
closed: str | None = None,
step: int | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""
Computes the bounds of a window.
Parameters
----------
num_values : int, default 0
number of values that will be aggregated over
window_size : int, default 0
the number of rows in a window
min_periods : int, default None
min_periods passed from the top level rolling API
center : bool, default None
center passed from the top level rolling API
closed : str, default None
closed passed from the top level rolling API
step : int, default None
step passed from the top level rolling API
win_type : str, default None
win_type passed from the top level rolling API
Returns
-------
A tuple of ndarray[int64]s, indicating the boundaries of each
window
"""
# 1) For each group, get the indices that belong to the group
# 2) Use the indices to calculate the start & end bounds of the window
# 3) Append the window bounds in group order
start_arrays = []
end_arrays = []
window_indices_start = 0
for indices in self.groupby_indices.values():
index_array: np.ndarray | None
if self.index_array is not None:
index_array = self.index_array.take(ensure_platform_int(indices))
else:
index_array = self.index_array
indexer = self.window_indexer(
index_array=index_array,
window_size=self.window_size,
**self.indexer_kwargs,
)
start, end = indexer.get_window_bounds(
len(indices), min_periods, center, closed, step
)
start = start.astype(np.int64)
end = end.astype(np.int64)
assert len(start) == len(end), (
"these should be equal in length from get_window_bounds"
)
# Cannot use groupby_indices as they might not be monotonic with the object
# we're rolling over
window_indices = np.arange(
window_indices_start, window_indices_start + len(indices)
)
window_indices_start += len(indices)
# Extend as we'll be slicing window like [start, end)
window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype(
np.int64, copy=False
)
start_arrays.append(window_indices.take(ensure_platform_int(start)))
end_arrays.append(window_indices.take(ensure_platform_int(end)))
if len(start_arrays) == 0:
return np.array([], dtype=np.int64), np.array([], dtype=np.int64)
start = np.concatenate(start_arrays)
end = np.concatenate(end_arrays)
return start, end
|
Computes the bounds of a window.
Parameters
----------
num_values : int, default 0
number of values that will be aggregated over
window_size : int, default 0
the number of rows in a window
min_periods : int, default None
min_periods passed from the top level rolling API
center : bool, default None
center passed from the top level rolling API
closed : str, default None
closed passed from the top level rolling API
step : int, default None
step passed from the top level rolling API
win_type : str, default None
win_type passed from the top level rolling API
Returns
-------
A tuple of ndarray[int64]s, indicating the boundaries of each
window
|
python
|
pandas/core/indexers/objects.py
| 569
|
[
"self",
"num_values",
"min_periods",
"center",
"closed",
"step"
] |
tuple[np.ndarray, np.ndarray]
| true
| 5
| 6.48
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
clear
|
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
incrementModCount();
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
metadata =
Ints.constrainToRange(size(), CompactHashing.DEFAULT_SIZE, CompactHashing.MAX_SIZE);
delegate.clear(); // invalidate any iterators left over!
table = null;
size = 0;
} else {
Arrays.fill(requireKeys(), 0, size, null);
Arrays.fill(requireValues(), 0, size, null);
CompactHashing.tableClear(requireTable());
Arrays.fill(requireEntries(), 0, size, 0);
this.size = 0;
}
}
|
Ensures that this {@code CompactHashMap} has the smallest representation in memory, given its
current size.
|
java
|
android/guava/src/com/google/common/collect/CompactHashMap.java
| 972
|
[] |
void
| true
| 3
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
copyTo
|
@CanIgnoreReturnValue
public long copyTo(OutputStream output) throws IOException {
checkNotNull(output);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.copy(in, output);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
|
Copies the contents of this byte source to the given {@code OutputStream}. Does not close
{@code output}.
@return the number of bytes copied
@throws IOException if an I/O error occurs while reading from this source or writing to {@code
output}
|
java
|
android/guava/src/com/google/common/io/ByteSource.java
| 249
|
[
"output"
] | true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
isTeredoAddress
|
public static boolean isTeredoAddress(Inet6Address ip) {
byte[] bytes = ip.getAddress();
return (bytes[0] == (byte) 0x20)
&& (bytes[1] == (byte) 0x01)
&& (bytes[2] == 0)
&& (bytes[3] == 0);
}
|
Evaluates whether the argument is a Teredo address.
<p>Teredo addresses begin with the {@code "2001::/32"} prefix.
@param ip {@link Inet6Address} to be examined for Teredo address format
@return {@code true} if the argument is a Teredo address
|
java
|
android/guava/src/com/google/common/net/InetAddresses.java
| 808
|
[
"ip"
] | true
| 4
| 8.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
computeError
|
void computeError( InputArray _m1, InputArray _m2, InputArray _model, OutputArray _err ) const CV_OVERRIDE
{
Mat __m1 = _m1.getMat(), __m2 = _m2.getMat(), __model = _model.getMat();
int i, count = __m1.checkVector(2);
const Point2f* m1 = __m1.ptr<Point2f>();
const Point2f* m2 = __m2.ptr<Point2f>();
const double* F = __model.ptr<double>();
_err.create(count, 1, CV_32F);
float* err = _err.getMat().ptr<float>();
for( i = 0; i < count; i++ )
{
double a, b, c, d1, d2, s1, s2;
a = F[0]*m1[i].x + F[1]*m1[i].y + F[2];
b = F[3]*m1[i].x + F[4]*m1[i].y + F[5];
c = F[6]*m1[i].x + F[7]*m1[i].y + F[8];
s2 = 1./(a*a + b*b);
d2 = m2[i].x*a + m2[i].y*b + c;
a = F[0]*m2[i].x + F[3]*m2[i].y + F[6];
b = F[1]*m2[i].x + F[4]*m2[i].y + F[7];
c = F[2]*m2[i].x + F[5]*m2[i].y + F[8];
s1 = 1./(a*a + b*b);
d1 = m1[i].x*a + m1[i].y*b + c;
err[i] = (float)std::max(d1*d1*s1, d2*d2*s2);
}
}
|
Compute the fundamental matrix using the 8-point algorithm.
\f[
(\mathrm{m2}_i,1)^T \mathrm{fmatrix} (\mathrm{m1}_i,1) = 0
\f]
@param _m1 Contain points in the reference view. Depth CV_32F with 2-channel
1 column or 1-channel 2 columns. It has 8 rows.
@param _m2 Contain points in the other view. Depth CV_32F with 2-channel
1 column or 1-channel 2 columns. It has 8 rows.
@param _fmatrix Output fundamental matrix (or matrices) of type CV_64FC1.
The user is responsible for allocating the memory before calling
this function.
@return 1 on success, 0 on failure.
Note that the computed fundamental matrix is normalized, i.e.,
the last element \f$F_{33}\f$ is 1.
|
cpp
|
modules/calib3d/src/fundam.cpp
| 817
|
[
"_m1",
"_m2",
"_model",
"_err"
] | true
| 2
| 7.84
|
opencv/opencv
| 85,374
|
doxygen
| false
|
|
insert
|
def insert(
self,
loc: int,
column: Hashable,
value: object,
allow_duplicates: bool | lib.NoDefault = lib.no_default,
) -> None:
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hashable object
Label of the inserted column.
value : Scalar, Series, or array-like
Content of the inserted column.
allow_duplicates : bool, optional, default lib.no_default
Allow duplicate column labels to be created.
See Also
--------
Index.insert : Insert new item by index.
Examples
--------
>>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
>>> df
col1 col2
0 1 3
1 2 4
>>> df.insert(1, "newcol", [99, 99])
>>> df
col1 newcol col2
0 1 99 3
1 2 99 4
>>> df.insert(0, "col1", [100, 100], allow_duplicates=True)
>>> df
col1 col1 newcol col2
0 100 1 99 3
1 100 2 99 4
Notice that pandas uses index alignment in case of `value` from type `Series`:
>>> df.insert(0, "col0", pd.Series([5, 6], index=[1, 2]))
>>> df
col0 col1 col1 newcol col2
0 NaN 100 1 99 3
1 5.0 100 2 99 4
"""
if allow_duplicates is lib.no_default:
allow_duplicates = False
if allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
if not allow_duplicates and column in self.columns:
# Should this be a different kind of error??
raise ValueError(f"cannot insert {column}, already exists")
if not is_integer(loc):
raise TypeError("loc must be int")
# convert non stdlib ints to satisfy typing checks
loc = int(loc)
if isinstance(value, DataFrame) and len(value.columns) > 1:
raise ValueError(
f"Expected a one-dimensional object, got a DataFrame with "
f"{len(value.columns)} columns instead."
)
elif isinstance(value, DataFrame):
value = value.iloc[:, 0]
value, refs = self._sanitize_column(value)
self._mgr.insert(loc, column, value, refs=refs)
|
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hashable object
Label of the inserted column.
value : Scalar, Series, or array-like
Content of the inserted column.
allow_duplicates : bool, optional, default lib.no_default
Allow duplicate column labels to be created.
See Also
--------
Index.insert : Insert new item by index.
Examples
--------
>>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
>>> df
col1 col2
0 1 3
1 2 4
>>> df.insert(1, "newcol", [99, 99])
>>> df
col1 newcol col2
0 1 99 3
1 2 99 4
>>> df.insert(0, "col1", [100, 100], allow_duplicates=True)
>>> df
col1 col1 newcol col2
0 100 1 99 3
1 100 2 99 4
Notice that pandas uses index alignment in case of `value` from type `Series`:
>>> df.insert(0, "col0", pd.Series([5, 6], index=[1, 2]))
>>> df
col0 col1 col1 newcol col2
0 NaN 100 1 99 3
1 5.0 100 2 99 4
|
python
|
pandas/core/frame.py
| 5,366
|
[
"self",
"loc",
"column",
"value",
"allow_duplicates"
] |
None
| true
| 10
| 8.56
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
print
|
public String print(Period value) {
return print(value, null);
}
|
Print the specified period.
@param value the value to print
@return the printed result
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java
| 166
|
[
"value"
] |
String
| true
| 1
| 6.96
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
joinWith
|
private Joiner joinWith(String delimiter) {
return (prefix, name) -> {
StringBuilder joined = new StringBuilder(prefix.length() + delimiter.length() + name.length());
joined.append(prefix);
if (!prefix.isEmpty() && !prefix.endsWith(delimiter) && !name.startsWith(delimiter)) {
joined.append(delimiter);
}
joined.append(name);
return joined.toString();
};
}
|
Add pairs using nested naming (for example as used in ECS).
@param <T> the item type
@param pairs callback to add all the pairs
@return a {@link BiConsumer} for use with the {@link JsonWriter}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/ContextPairs.java
| 89
|
[
"delimiter"
] |
Joiner
| true
| 4
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
getAndIncrement
|
public double getAndIncrement() {
final double last = value;
value++;
return last;
}
|
Increments this instance's value by 1; this method returns the value associated with the instance
immediately prior to the increment operation. This method is not thread safe.
@return the value associated with the instance before it was incremented.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java
| 264
|
[] | true
| 1
| 6.88
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
from_fields
|
def from_fields(
cls,
*,
year=None,
quarter=None,
month=None,
day=None,
hour=None,
minute=None,
second=None,
freq=None,
) -> Self:
"""
Construct a PeriodIndex from fields (year, month, day, etc.).
Parameters
----------
year : int, array, or Series, default None
Year for the PeriodIndex.
quarter : int, array, or Series, default None
Quarter for the PeriodIndex.
month : int, array, or Series, default None
Month for the PeriodIndex.
day : int, array, or Series, default None
Day for the PeriodIndex.
hour : int, array, or Series, default None
Hour for the PeriodIndex.
minute : int, array, or Series, default None
Minute for the PeriodIndex.
second : int, array, or Series, default None
Second for the PeriodIndex.
freq : str or period object, optional
One of pandas period strings or corresponding objects.
Returns
-------
PeriodIndex
See Also
--------
PeriodIndex.from_ordinals : Construct a PeriodIndex from ordinals.
PeriodIndex.to_timestamp : Cast to DatetimeArray/Index.
Examples
--------
>>> idx = pd.PeriodIndex.from_fields(year=[2000, 2002], quarter=[1, 3])
>>> idx
PeriodIndex(['2000Q1', '2002Q3'], dtype='period[Q-DEC]')
"""
fields = {
"year": year,
"quarter": quarter,
"month": month,
"day": day,
"hour": hour,
"minute": minute,
"second": second,
}
fields = {key: value for key, value in fields.items() if value is not None}
arr = PeriodArray._from_fields(fields=fields, freq=freq)
return cls._simple_new(arr)
|
Construct a PeriodIndex from fields (year, month, day, etc.).
Parameters
----------
year : int, array, or Series, default None
Year for the PeriodIndex.
quarter : int, array, or Series, default None
Quarter for the PeriodIndex.
month : int, array, or Series, default None
Month for the PeriodIndex.
day : int, array, or Series, default None
Day for the PeriodIndex.
hour : int, array, or Series, default None
Hour for the PeriodIndex.
minute : int, array, or Series, default None
Minute for the PeriodIndex.
second : int, array, or Series, default None
Second for the PeriodIndex.
freq : str or period object, optional
One of pandas period strings or corresponding objects.
Returns
-------
PeriodIndex
See Also
--------
PeriodIndex.from_ordinals : Construct a PeriodIndex from ordinals.
PeriodIndex.to_timestamp : Cast to DatetimeArray/Index.
Examples
--------
>>> idx = pd.PeriodIndex.from_fields(year=[2000, 2002], quarter=[1, 3])
>>> idx
PeriodIndex(['2000Q1', '2002Q3'], dtype='period[Q-DEC]')
|
python
|
pandas/core/indexes/period.py
| 259
|
[
"cls",
"year",
"quarter",
"month",
"day",
"hour",
"minute",
"second",
"freq"
] |
Self
| true
| 1
| 6.56
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
read
|
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
Optional<Long> size = sizeIfKnown();
return size.isPresent()
? ByteStreams.toByteArray(in, size.get())
: ByteStreams.toByteArray(in);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
|
Reads the full contents of this byte source as a byte array.
@throws IOException if an I/O error occurs while reading from this source
|
java
|
android/guava/src/com/google/common/io/ByteSource.java
| 292
|
[] | true
| 3
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
|
is_complex_dtype
|
def is_complex_dtype(arr_or_dtype) -> bool:
"""
Check whether the provided array or dtype is of a complex dtype.
Parameters
----------
arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a complex dtype.
See Also
--------
api.types.is_complex: Return True if given object is complex.
api.types.is_numeric_dtype: Check whether the provided array or
dtype is of a numeric dtype.
api.types.is_integer_dtype: Check whether the provided array or
dtype is of an integer dtype.
Examples
--------
>>> from pandas.api.types import is_complex_dtype
>>> is_complex_dtype(str)
False
>>> is_complex_dtype(int)
False
>>> is_complex_dtype(np.complex128)
True
>>> is_complex_dtype(np.array(["a", "b"]))
False
>>> is_complex_dtype(pd.Series([1, 2]))
False
>>> is_complex_dtype(np.array([1 + 1j, 5]))
True
"""
return _is_dtype_type(arr_or_dtype, classes(np.complexfloating))
|
Check whether the provided array or dtype is of a complex dtype.
Parameters
----------
arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a complex dtype.
See Also
--------
api.types.is_complex: Return True if given object is complex.
api.types.is_numeric_dtype: Check whether the provided array or
dtype is of a numeric dtype.
api.types.is_integer_dtype: Check whether the provided array or
dtype is of an integer dtype.
Examples
--------
>>> from pandas.api.types import is_complex_dtype
>>> is_complex_dtype(str)
False
>>> is_complex_dtype(int)
False
>>> is_complex_dtype(np.complex128)
True
>>> is_complex_dtype(np.array(["a", "b"]))
False
>>> is_complex_dtype(pd.Series([1, 2]))
False
>>> is_complex_dtype(np.array([1 + 1j, 5]))
True
|
python
|
pandas/core/dtypes/common.py
| 1,559
|
[
"arr_or_dtype"
] |
bool
| true
| 1
| 6.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
split
|
public static String[] split(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
|
Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.
<p>
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the
StrTokenizer class.
</p>
<p>
A {@code null} input String returns {@code null}. A {@code null} separatorChars splits on whitespace.
</p>
<pre>
StringUtils.split(null, *) = null
StringUtils.split("", *) = []
StringUtils.split("abc def", null) = ["abc", "def"]
StringUtils.split("abc def", " ") = ["abc", "def"]
StringUtils.split("abc def", " ") = ["abc", "def"]
StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
</pre>
@param str the String to parse, may be null.
@param separatorChars the characters used as the delimiters, {@code null} splits on whitespace.
@return an array of parsed Strings, {@code null} if null String input.
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 7,093
|
[
"str",
"separatorChars"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
filteredTransactionalIdPattern
|
public String filteredTransactionalIdPattern() {
return 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
| 122
|
[] |
String
| true
| 1
| 6
|
apache/kafka
| 31,560
|
javadoc
| false
|
opj_int_fix_mul
|
static INLINE OPJ_INT32 opj_int_fix_mul(OPJ_INT32 a, OPJ_INT32 b)
{
#if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(__INTEL_COMPILER) && defined(_M_IX86)
OPJ_INT64 temp = __emul(a, b);
#else
OPJ_INT64 temp = (OPJ_INT64) a * (OPJ_INT64) b ;
#endif
temp += 4096;
assert((temp >> 13) <= (OPJ_INT64)0x7FFFFFFF);
assert((temp >> 13) >= (-(OPJ_INT64)0x7FFFFFFF - (OPJ_INT64)1));
return (OPJ_INT32)(temp >> 13);
}
|
Multiply two fixed-precision rational numbers.
@param a
@param b
@return Returns a * b
|
cpp
|
3rdparty/openjpeg/openjp2/opj_intmath.h
| 263
|
[
"a",
"b"
] | true
| 4
| 8.24
|
opencv/opencv
| 85,374
|
doxygen
| false
|
|
resolveSignature
|
public static @Nullable Method resolveSignature(String signature, Class<?> clazz) {
Assert.hasText(signature, "'signature' must not be empty");
Assert.notNull(clazz, "Class must not be null");
int startParen = signature.indexOf('(');
int endParen = signature.indexOf(')');
if (startParen > -1 && endParen == -1) {
throw new IllegalArgumentException("Invalid method signature '" + signature +
"': expected closing ')' for args list");
}
else if (startParen == -1 && endParen > -1) {
throw new IllegalArgumentException("Invalid method signature '" + signature +
"': expected opening '(' for args list");
}
else if (startParen == -1) {
return findMethodWithMinimalParameters(clazz, signature);
}
else {
String methodName = signature.substring(0, startParen);
String[] parameterTypeNames =
StringUtils.commaDelimitedListToStringArray(signature.substring(startParen + 1, endParen));
Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];
for (int i = 0; i < parameterTypeNames.length; i++) {
String parameterTypeName = parameterTypeNames[i].trim();
try {
parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader());
}
catch (Throwable ex) {
throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" +
parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
}
}
return findMethod(clazz, methodName, parameterTypes);
}
}
|
Parse a method signature in the form {@code methodName[([arg_list])]},
where {@code arg_list} is an optional, comma-separated list of fully-qualified
type names, and attempts to resolve that signature against the supplied {@code Class}.
<p>When not supplying an argument list ({@code methodName}) the method whose name
matches and has the least number of parameters will be returned. When supplying an
argument type list, only the method whose name and argument types match will be returned.
<p>Note then that {@code methodName} and {@code methodName()} are <strong>not</strong>
resolved in the same way. The signature {@code methodName} means the method called
{@code methodName} with the least number of arguments, whereas {@code methodName()}
means the method called {@code methodName} with exactly 0 arguments.
<p>If no method can be found, then {@code null} is returned.
@param signature the method signature as String representation
@param clazz the class to resolve the method signature against
@return the resolved Method
@see #findMethod
@see #findMethodWithMinimalParameters
|
java
|
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
| 452
|
[
"signature",
"clazz"
] |
Method
| true
| 8
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
as_array
|
def as_array(obj, shape=None):
"""
Create a numpy array from a ctypes array or POINTER.
The numpy array shares the memory with the ctypes object.
The shape parameter must be given if converting from a ctypes POINTER.
The shape parameter is ignored if converting from a ctypes array
Examples
--------
Converting a ctypes integer array:
>>> import ctypes
>>> ctypes_array = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
>>> np_array = np.ctypeslib.as_array(ctypes_array)
>>> np_array
array([0, 1, 2, 3, 4], dtype=int32)
Converting a ctypes POINTER:
>>> import ctypes
>>> buffer = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
>>> pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_int))
>>> np_array = np.ctypeslib.as_array(pointer, (5,))
>>> np_array
array([0, 1, 2, 3, 4], dtype=int32)
"""
if isinstance(obj, ctypes._Pointer):
# convert pointers to an array of the desired shape
if shape is None:
raise TypeError(
'as_array() requires a shape argument when called on a '
'pointer')
p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape))
obj = ctypes.cast(obj, p_arr_type).contents
return np.asarray(obj)
|
Create a numpy array from a ctypes array or POINTER.
The numpy array shares the memory with the ctypes object.
The shape parameter must be given if converting from a ctypes POINTER.
The shape parameter is ignored if converting from a ctypes array
Examples
--------
Converting a ctypes integer array:
>>> import ctypes
>>> ctypes_array = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
>>> np_array = np.ctypeslib.as_array(ctypes_array)
>>> np_array
array([0, 1, 2, 3, 4], dtype=int32)
Converting a ctypes POINTER:
>>> import ctypes
>>> buffer = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
>>> pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_int))
>>> np_array = np.ctypeslib.as_array(pointer, (5,))
>>> np_array
array([0, 1, 2, 3, 4], dtype=int32)
|
python
|
numpy/ctypeslib/_ctypeslib.py
| 521
|
[
"obj",
"shape"
] | false
| 3
| 6.8
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
maybeBindThrowingVariable
|
private void maybeBindThrowingVariable() {
if (this.throwingName == null) {
return;
}
// So there is binding work to do...
int throwableIndex = -1;
for (int i = 0; i < this.argumentTypes.length; i++) {
if (isUnbound(i) && isSubtypeOf(Throwable.class, i)) {
if (throwableIndex == -1) {
throwableIndex = i;
}
else {
// Second candidate we've found - ambiguous binding
throw new AmbiguousBindingException("Binding of throwing parameter '" +
this.throwingName + "' is ambiguous: could be bound to argument " +
throwableIndex + " or " + i);
}
}
}
if (throwableIndex == -1) {
throw new IllegalStateException("Binding of throwing parameter '" + this.throwingName +
"' could not be completed as no available arguments are a subtype of Throwable");
}
else {
bindParameterName(throwableIndex, this.throwingName);
}
}
|
If a throwing name was specified and there is exactly one choice remaining
(argument that is a subtype of Throwable) then bind it.
|
java
|
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java
| 329
|
[] |
void
| true
| 7
| 7.04
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
create
|
public static URL create(File file, String nestedEntryName, String path) {
try {
path = (path != null) ? path : "";
return new URL(null, "jar:" + getJarReference(file, nestedEntryName) + "!/" + path, Handler.INSTANCE);
}
catch (MalformedURLException ex) {
throw new IllegalStateException("Unable to create JarFileArchive URL", ex);
}
}
|
Create a new jar URL.
@param file the jar file
@param nestedEntryName the nested entry name or {@code null}
@param path the path within the jar or nested jar
@return a jar file URL
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrl.java
| 71
|
[
"file",
"nestedEntryName",
"path"
] |
URL
| true
| 3
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
flatten_mask
|
def flatten_mask(mask):
"""
Returns a completely flattened version of the mask, where nested fields
are collapsed.
Parameters
----------
mask : array_like
Input array, which will be interpreted as booleans.
Returns
-------
flattened_mask : ndarray of bools
The flattened input.
Examples
--------
>>> import numpy as np
>>> mask = np.array([0, 0, 1])
>>> np.ma.flatten_mask(mask)
array([False, False, True])
>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> np.ma.flatten_mask(mask)
array([False, False, False, True])
>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> np.ma.flatten_mask(mask)
array([False, False, False, False, False, True])
"""
def _flatmask(mask):
"Flatten the mask and returns a (maybe nested) sequence of booleans."
mnames = mask.dtype.names
if mnames is not None:
return [flatten_mask(mask[name]) for name in mnames]
else:
return mask
def _flatsequence(sequence):
"Generates a flattened version of the sequence."
try:
for element in sequence:
if hasattr(element, '__iter__'):
yield from _flatsequence(element)
else:
yield element
except TypeError:
yield sequence
mask = np.asarray(mask)
flattened = _flatsequence(_flatmask(mask))
return np.array(list(flattened), dtype=bool)
|
Returns a completely flattened version of the mask, where nested fields
are collapsed.
Parameters
----------
mask : array_like
Input array, which will be interpreted as booleans.
Returns
-------
flattened_mask : ndarray of bools
The flattened input.
Examples
--------
>>> import numpy as np
>>> mask = np.array([0, 0, 1])
>>> np.ma.flatten_mask(mask)
array([False, False, True])
>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> np.ma.flatten_mask(mask)
array([False, False, False, True])
>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> np.ma.flatten_mask(mask)
array([False, False, False, False, False, True])
|
python
|
numpy/ma/core.py
| 1,805
|
[
"mask"
] | false
| 6
| 7.36
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
writeLines
|
function writeLines(text: string): void {
const lines = text.split(/\r\n?|\n/);
const indentation = guessIndentation(lines);
for (const lineText of lines) {
const line = indentation ? lineText.slice(indentation) : lineText;
if (line.length) {
writeLine();
write(line);
}
}
}
|
Emits a list without brackets or raising events.
NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead.
|
typescript
|
src/compiler/emitter.ts
| 4,958
|
[
"text"
] | true
| 3
| 6.56
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
listConsumerGroupOffsets
|
default ListConsumerGroupOffsetsResult listConsumerGroupOffsets(String groupId, ListConsumerGroupOffsetsOptions options) {
ListConsumerGroupOffsetsSpec groupSpec = new ListConsumerGroupOffsetsSpec();
// We can use the provided options with the batched API, which uses topic partitions from
// the group spec and ignores any topic partitions set in the options.
return listConsumerGroupOffsets(Collections.singletonMap(groupId, groupSpec), options);
}
|
List the consumer group offsets available in the cluster.
@param options The options to use when listing the consumer group offsets.
@return The ListConsumerGroupOffsetsResult
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 910
|
[
"groupId",
"options"
] |
ListConsumerGroupOffsetsResult
| true
| 1
| 6.4
|
apache/kafka
| 31,560
|
javadoc
| false
|
create_tuning_job
|
def create_tuning_job(
self,
config: dict,
wait_for_completion: bool = True,
check_interval: int = 30,
max_ingestion_time: int | None = None,
):
"""
Start a hyperparameter tuning job.
A hyperparameter tuning job finds the best version of a model by running
many training jobs on your dataset using the algorithm you choose and
values for hyperparameters within ranges that you specify. It then
chooses the hyperparameter values that result in a model that performs
the best, as measured by an objective metric that you choose.
:param config: the config for tuning
:param wait_for_completion: if the program should keep running until job finishes
:param check_interval: the time interval in seconds which the operator
will check the status of any SageMaker job
:param max_ingestion_time: the maximum ingestion time in seconds. Any
SageMaker jobs that run longer than this will fail. Setting this to
None implies no timeout for any SageMaker job.
:return: A response to tuning job creation
"""
self.check_tuning_config(config)
response = self.get_conn().create_hyper_parameter_tuning_job(**config)
if wait_for_completion:
self.check_status(
config["HyperParameterTuningJobName"],
"HyperParameterTuningJobStatus",
self.describe_tuning_job,
check_interval,
max_ingestion_time,
)
return response
|
Start a hyperparameter tuning job.
A hyperparameter tuning job finds the best version of a model by running
many training jobs on your dataset using the algorithm you choose and
values for hyperparameters within ranges that you specify. It then
chooses the hyperparameter values that result in a model that performs
the best, as measured by an objective metric that you choose.
:param config: the config for tuning
:param wait_for_completion: if the program should keep running until job finishes
:param check_interval: the time interval in seconds which the operator
will check the status of any SageMaker job
:param max_ingestion_time: the maximum ingestion time in seconds. Any
SageMaker jobs that run longer than this will fail. Setting this to
None implies no timeout for any SageMaker job.
:return: A response to tuning job creation
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 342
|
[
"self",
"config",
"wait_for_completion",
"check_interval",
"max_ingestion_time"
] | true
| 2
| 7.92
|
apache/airflow
| 43,597
|
sphinx
| false
|
|
truncateSync
|
function truncateSync(path, len) {
if (len === undefined) {
len = 0;
}
// Allow error to be thrown, but still close fd.
const fd = fs.openSync(path, 'r+');
try {
fs.ftruncateSync(fd, len);
} finally {
fs.closeSync(fd);
}
}
|
Synchronously truncates the file.
@param {string | Buffer | URL} path
@param {number} [len]
@returns {void}
|
javascript
|
lib/fs.js
| 1,057
|
[
"path",
"len"
] | false
| 2
| 6.16
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
isTypeArgumentOrParameterOrAssertion
|
function isTypeArgumentOrParameterOrAssertion(token: TextRangeWithKind, parent: Node): boolean {
if (token.kind !== SyntaxKind.LessThanToken && token.kind !== SyntaxKind.GreaterThanToken) {
return false;
}
switch (parent.kind) {
case SyntaxKind.TypeReference:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ExpressionWithTypeArguments:
return true;
default:
return false;
}
}
|
A rule takes a two tokens (left/right) and a particular context
for which you're meant to look at them. You then declare what should the
whitespace annotation be between these tokens via the action param.
@param debugName Name to print
@param left The left side of the comparison
@param right The right side of the comparison
@param context A set of filters to narrow down the space in which this formatter rule applies
@param action a declaration of the expected whitespace
@param flags whether the rule deletes a line or not, defaults to no-op
|
typescript
|
src/services/formatting/rules.ts
| 840
|
[
"token",
"parent"
] | true
| 3
| 6.24
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
create
|
@SafeVarargs
public static <E extends @Nullable Object> CompactHashSet<E> create(E... elements) {
CompactHashSet<E> set = createWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
|
Creates a <i>mutable</i> {@code CompactHashSet} instance containing the given elements in
unspecified order.
@param elements the elements that the set should contain
@return a new {@code CompactHashSet} containing those elements (minus duplicates)
|
java
|
android/guava/src/com/google/common/collect/CompactHashSet.java
| 106
|
[] | true
| 1
| 6.08
|
google/guava
| 51,352
|
javadoc
| false
|
|
getLastModified
|
@Override
public long getLastModified(Object templateSource) {
Resource resource = (Resource) templateSource;
try {
return resource.lastModified();
}
catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not obtain last-modified timestamp for FreeMarker template in " +
resource + ": " + ex);
}
return -1;
}
}
|
Create a new {@code SpringTemplateLoader}.
@param resourceLoader the Spring ResourceLoader to use
@param templateLoaderPath the template loader path to use
|
java
|
spring-context-support/src/main/java/org/springframework/ui/freemarker/SpringTemplateLoader.java
| 93
|
[
"templateSource"
] | true
| 3
| 6.4
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.