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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
extract
|
@Nullable T extract(@Nullable Object instance);
|
Extract the value from the given instance.
@param instance the source instance
@return the extracted value or {@link #SKIP}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
| 705
|
[
"instance"
] |
T
| true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
initCloneArray
|
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
|
Initializes an array clone.
@private
@param {Array} array The array to clone.
@returns {Array} Returns the initialized clone.
|
javascript
|
lodash.js
| 6,251
|
[
"array"
] | false
| 4
| 6.08
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
process
|
private void process(final ShareUnsubscribeEvent event) {
if (requestManagers.shareHeartbeatRequestManager.isEmpty()) {
KafkaException error = new KafkaException("Group membership manager not present when processing an unsubscribe event");
event.future().completeExceptionally(error);
return;
}
subscriptions.unsubscribe();
CompletableFuture<Void> future = requestManagers.shareHeartbeatRequestManager.get().membershipManager().leaveGroup();
// The future will be completed on heartbeat sent
future.whenComplete(complete(event.future()));
}
|
Process event indicating that the consumer unsubscribed from all topics. This will make
the consumer release its assignment and send a request to leave the share group.
@param event Unsubscribe event containing a future that will complete when the callback
execution for releasing the assignment completes, and the request to leave
the group is sent out.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
| 559
|
[
"event"
] |
void
| true
| 2
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
pullAllWith
|
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
|
This method is like `_.pullAll` except that it accepts `comparator` which
is invoked to compare elements of `array` to `values`. The comparator is
invoked with two arguments: (arrVal, othVal).
**Note:** Unlike `_.differenceWith`, this method mutates `array`.
@static
@memberOf _
@since 4.6.0
@category Array
@param {Array} array The array to modify.
@param {Array} values The values to remove.
@param {Function} [comparator] The comparator invoked per element.
@returns {Array} Returns `array`.
@example
var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
_.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
console.log(array);
// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
|
javascript
|
lodash.js
| 7,881
|
[
"array",
"values",
"comparator"
] | false
| 5
| 7.52
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
_get_resampler
|
def _get_resampler(self, obj: NDFrame) -> Resampler:
"""
Return my resampler or raise if we have an invalid axis.
Parameters
----------
obj : Series or DataFrame
Returns
-------
Resampler
Raises
------
TypeError if incompatible axis
"""
_, ax, _ = self._set_grouper(obj, gpr_index=None)
if isinstance(ax, DatetimeIndex):
return DatetimeIndexResampler(
obj,
timegrouper=self,
group_keys=self.group_keys,
gpr_index=ax,
)
elif isinstance(ax, PeriodIndex):
return PeriodIndexResampler(
obj,
timegrouper=self,
group_keys=self.group_keys,
gpr_index=ax,
)
elif isinstance(ax, TimedeltaIndex):
return TimedeltaIndexResampler(
obj,
timegrouper=self,
group_keys=self.group_keys,
gpr_index=ax,
)
raise TypeError(
"Only valid with DatetimeIndex, "
"TimedeltaIndex or PeriodIndex, "
f"but got an instance of '{type(ax).__name__}'"
)
|
Return my resampler or raise if we have an invalid axis.
Parameters
----------
obj : Series or DataFrame
Returns
-------
Resampler
Raises
------
TypeError if incompatible axis
|
python
|
pandas/core/resample.py
| 2,494
|
[
"self",
"obj"
] |
Resampler
| true
| 4
| 6.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
writeFile
|
function writeFile(path, data, options, callback) {
callback ||= options;
validateFunction(callback, 'cb');
options = getOptions(options, {
encoding: 'utf8',
mode: 0o666,
flag: 'w',
flush: false,
});
const flag = options.flag || 'w';
const flush = options.flush ?? false;
validateBoolean(flush, 'options.flush');
if (!isArrayBufferView(data)) {
validateStringAfterArrayBufferView(data, 'data');
data = Buffer.from(data, options.encoding || 'utf8');
}
if (isFd(path)) {
const isUserFd = true;
const signal = options.signal;
writeAll(path, isUserFd, data, 0, data.byteLength, signal, flush, callback);
return;
}
if (checkAborted(options.signal, callback))
return;
fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
} else {
const isUserFd = false;
const signal = options.signal;
writeAll(fd, isUserFd, data, 0, data.byteLength, signal, flush, callback);
}
});
}
|
Asynchronously writes data to the file.
@param {string | Buffer | URL | number} path
@param {string | Buffer | TypedArray | DataView} data
@param {{
encoding?: string | null;
mode?: number;
flag?: string;
signal?: AbortSignal;
flush?: boolean;
} | string} [options]
@param {(err?: Error) => any} callback
@returns {void}
|
javascript
|
lib/fs.js
| 2,320
|
[
"path",
"data",
"options",
"callback"
] | false
| 8
| 6.08
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
keySet
|
@Override
public ImmutableSet<K> keySet() {
ImmutableSet<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
|
Returns an immutable set of the keys in this map, in the same order that they appear in {@link
#entrySet}.
|
java
|
android/guava/src/com/google/common/collect/ImmutableMap.java
| 950
|
[] | true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
magnitude
|
private static double magnitude(double x, double y, double z) {
return Math.sqrt(square(x) + square(y) + square(z));
}
|
Calculate the magnitude of 3D coordinates.
@param x The first 3D coordinate.
@param y The second 3D coordinate.
@param z The third 3D coordinate.
@return The magnitude of the provided coordinates.
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/Vec3d.java
| 230
|
[
"x",
"y",
"z"
] | true
| 1
| 6.96
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
invokeAnd
|
public <R> InvocationResult<R> invokeAnd(Function<C, @Nullable R> invoker) {
Supplier<@Nullable R> supplier = () -> invoker.apply(this.callbackInstance);
return invoke(this.callbackInstance, supplier);
}
|
Invoke the callback instance where the callback method returns a result.
@param invoker the invoker used to invoke the callback
@param <R> the result type
@return the result of the invocation (may be {@link InvocationResult#noResult}
if the callback was not invoked)
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java
| 270
|
[
"invoker"
] | true
| 1
| 6.48
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
configure
|
@Override
protected void configure(FilterRegistration.Dynamic registration) {
super.configure(registration);
EnumSet<DispatcherType> dispatcherTypes = determineDispatcherTypes();
Set<String> servletNames = new LinkedHashSet<>();
for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) {
servletNames.add(servletRegistrationBean.getServletName());
}
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
}
else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(this.urlPatterns));
}
}
}
|
Configure registration settings. Subclasses can override this method to perform
additional configuration if required.
@param registration the registration
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java
| 241
|
[
"registration"
] |
void
| true
| 5
| 6.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
createInternal
|
static KafkaAdminClient createInternal(AdminClientConfig config,
AdminMetadataManager metadataManager,
KafkaClient client,
Time time) {
Metrics metrics = null;
String clientId = generateClientId(config);
List<MetricsReporter> reporters = CommonClientConfigs.metricsReporters(clientId, config);
Optional<ClientTelemetryReporter> clientTelemetryReporter = CommonClientConfigs.telemetryReporter(clientId, config);
clientTelemetryReporter.ifPresent(reporters::add);
try {
metrics = new Metrics(new MetricConfig(), reporters, time);
LogContext logContext = createLogContext(clientId);
return new KafkaAdminClient(config, clientId, time, metadataManager, metrics,
client, null, logContext, clientTelemetryReporter);
} catch (Throwable exc) {
closeQuietly(metrics, "Metrics");
throw new KafkaException("Failed to create new KafkaAdminClient", exc);
}
}
|
Pretty-print an exception.
@param throwable The exception.
@return A compact human-readable string.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
| 576
|
[
"config",
"metadataManager",
"client",
"time"
] |
KafkaAdminClient
| true
| 2
| 7.92
|
apache/kafka
| 31,560
|
javadoc
| false
|
toHtml
|
public String toHtml(int headerDepth, Function<String, String> idGenerator,
Map<String, String> dynamicUpdateModes) {
boolean hasUpdateModes = !dynamicUpdateModes.isEmpty();
List<ConfigKey> configs = sortedConfigs();
StringBuilder b = new StringBuilder();
b.append("<ul class=\"config-list\">\n");
for (ConfigKey key : configs) {
if (key.internalConfig) {
continue;
}
b.append("<li>\n");
b.append(String.format("<h%1$d>" +
"<a id=\"%3$s\"></a><a id=\"%2$s\" href=\"#%2$s\">%3$s</a>" +
"</h%1$d>%n", headerDepth, idGenerator.apply(key.name), key.name));
b.append("<p>");
if (key.documentation != null) {
b.append(key.documentation.replaceAll("\n", "<br>"));
}
b.append("</p>\n");
b.append("<table>" +
"<tbody>\n");
for (String detail : headers()) {
if (detail.equals("Name") || detail.equals("Description")) continue;
if (detail.equals("Default") && key.alternativeString != null) {
addConfigDetail(b, detail, key.alternativeString);
continue;
}
addConfigDetail(b, detail, getConfigValue(key, detail));
}
if (hasUpdateModes) {
String updateMode = dynamicUpdateModes.get(key.name);
if (updateMode == null)
updateMode = "read-only";
addConfigDetail(b, "Update Mode", updateMode);
}
b.append("</tbody></table>\n");
b.append("</li>\n");
}
b.append("</ul>\n");
return b.toString();
}
|
Converts this config into an HTML list that can be embedded into docs.
If <code>dynamicUpdateModes</code> is non-empty, a "Dynamic Update Mode" label
will be included in the config details with the value of the update mode. Default
mode is "read-only".
@param headerDepth The top level header depth in the generated HTML.
@param idGenerator A function for computing the HTML id attribute in the generated HTML from a given config name.
@param dynamicUpdateModes Config name -> update mode mapping.
|
java
|
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
| 1,724
|
[
"headerDepth",
"idGenerator",
"dynamicUpdateModes"
] |
String
| true
| 9
| 6.72
|
apache/kafka
| 31,560
|
javadoc
| false
|
getAndAdd
|
public float getAndAdd(final Number operand) {
final float last = value;
this.value += operand.floatValue();
return last;
}
|
Increments this instance's value by {@code operand}; this method returns the value associated with the instance
immediately prior to the addition operation. This method is not thread safe.
@param operand the quantity to add, not null.
@throws NullPointerException if {@code operand} is null.
@return the value associated with this instance immediately before the operand was added.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java
| 242
|
[
"operand"
] | true
| 1
| 6.56
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getEarlyBeanReference
|
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
exposedObject = bp.getEarlyBeanReference(exposedObject, beanName);
}
}
return exposedObject;
}
|
Obtain a reference for early access to the specified bean,
typically for the purpose of resolving a circular reference.
@param beanName the name of the bean (for error handling purposes)
@param mbd the merged bean definition for the bean
@param bean the raw bean instance
@return the object to expose as bean reference
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
| 968
|
[
"beanName",
"mbd",
"bean"
] |
Object
| true
| 3
| 7.76
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
hash
|
static int hash(ByteBuffer buffer, DataBlock dataBlock, long pos, int len, boolean addEndSlash) throws IOException {
if (len == 0) {
return (!addEndSlash) ? EMPTY_HASH : EMPTY_SLASH_HASH;
}
buffer = (buffer != null) ? buffer : ByteBuffer.allocate(BUFFER_SIZE);
byte[] bytes = buffer.array();
int hash = 0;
char lastChar = 0;
int codePointSize = 1;
while (len > 0) {
int count = readInBuffer(dataBlock, pos, buffer, len, codePointSize);
for (int byteIndex = 0; byteIndex < count;) {
codePointSize = getCodePointSize(bytes, byteIndex);
if (!hasEnoughBytes(byteIndex, codePointSize, count)) {
break;
}
int codePoint = getCodePoint(bytes, byteIndex, codePointSize);
if (codePoint <= 0xFFFF) {
lastChar = (char) (codePoint & 0xFFFF);
hash = 31 * hash + lastChar;
}
else {
lastChar = 0;
hash = 31 * hash + Character.highSurrogate(codePoint);
hash = 31 * hash + Character.lowSurrogate(codePoint);
}
byteIndex += codePointSize;
pos += codePointSize;
len -= codePointSize;
codePointSize = 1;
}
}
hash = (addEndSlash && lastChar != '/') ? 31 * hash + '/' : hash;
debug.log("%08X calculated for datablock position %s size %s (addEndSlash=%s)", hash, pos, len, addEndSlash);
return hash;
}
|
Return a hash for bytes read from a {@link DataBlock}, optionally appending '/'.
@param buffer the buffer to use or {@code null}
@param dataBlock the source data block
@param pos the position in the data block where the string starts
@param len the number of bytes to read from the block
@param addEndSlash if slash should be added to the string if it's not already
present
@return the hash
@throws IOException on I/O error
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipString.java
| 103
|
[
"buffer",
"dataBlock",
"pos",
"len",
"addEndSlash"
] | true
| 10
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
describe_training_job_with_log_async
|
async def describe_training_job_with_log_async(
self,
job_name: str,
positions: dict[str, Any],
stream_names: list[str],
instance_count: int,
state: int,
last_description: dict[str, Any],
last_describe_job_call: float,
) -> tuple[int, dict[str, Any], float]:
"""
Return the training job info associated with job_name and print CloudWatch logs.
:param job_name: name of the job to check status
:param positions: A list of pairs of (timestamp, skip) which represents the last record
read from each stream.
:param stream_names: A list of the log stream names. The position of the stream in this list is
the stream number.
:param instance_count: Count of the instance created for the job initially
:param state: log state
:param last_description: Latest description of the training job
:param last_describe_job_call: previous job called time
"""
log_group = "/aws/sagemaker/TrainingJobs"
if len(stream_names) < instance_count:
logs_hook = AwsLogsHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
streams = await logs_hook.describe_log_streams_async(
log_group=log_group,
stream_prefix=job_name + "/",
order_by="LogStreamName",
count=instance_count,
)
stream_names = [s["logStreamName"] for s in streams["logStreams"]] if streams else []
positions.update([(s, Position(timestamp=0, skip=0)) for s in stream_names if s not in positions])
if len(stream_names) > 0:
async for idx, event in self.get_multi_stream(log_group, stream_names, positions):
self.log.info(event["message"])
ts, count = positions[stream_names[idx]]
if event["timestamp"] == ts:
positions[stream_names[idx]] = Position(timestamp=ts, skip=count + 1)
else:
positions[stream_names[idx]] = Position(timestamp=event["timestamp"], skip=1)
if state == LogState.COMPLETE:
return state, last_description, last_describe_job_call
if state == LogState.JOB_COMPLETE:
state = LogState.COMPLETE
elif time.time() - last_describe_job_call >= 30:
description = await self.describe_training_job_async(job_name)
last_describe_job_call = time.time()
if await sync_to_async(secondary_training_status_changed)(description, last_description):
self.log.info(
await sync_to_async(secondary_training_status_message)(description, last_description)
)
last_description = description
status = description["TrainingJobStatus"]
if status not in self.non_terminal_states:
state = LogState.JOB_COMPLETE
return state, last_description, last_describe_job_call
|
Return the training job info associated with job_name and print CloudWatch logs.
:param job_name: name of the job to check status
:param positions: A list of pairs of (timestamp, skip) which represents the last record
read from each stream.
:param stream_names: A list of the log stream names. The position of the stream in this list is
the stream number.
:param instance_count: Count of the instance created for the job initially
:param state: log state
:param last_description: Latest description of the training job
:param last_describe_job_call: previous job called time
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
| 1,326
|
[
"self",
"job_name",
"positions",
"stream_names",
"instance_count",
"state",
"last_description",
"last_describe_job_call"
] |
tuple[int, dict[str, Any], float]
| true
| 12
| 6.8
|
apache/airflow
| 43,597
|
sphinx
| false
|
debounce
|
function debounce<P extends any[], R>(fn: (...args: P) => R, time: number) {
let timeoutId: number | NodeJS.Timeout | undefined
return (...args: P): void => {
clearTimeout(timeoutId as NodeJS.Timeout)
timeoutId = setTimeout(() => fn(...args), time)
}
}
|
Makes that a function is only executed after repeated calls (usually
excessive calls) stop for a defined amount of {@link time}.
@param fn to debounce
@param time to unlock
@returns
|
typescript
|
helpers/blaze/debounce.ts
| 8
|
[
"fn",
"time"
] | false
| 1
| 6.08
|
prisma/prisma
| 44,834
|
jsdoc
| false
|
|
Subprocess
|
Subprocess(Subprocess&&) = default;
|
Class representing various options: file descriptor behavior, and
whether to use $PATH for searching for the executable,
By default, we don't use $PATH, file descriptors are closed if
the close-on-exec flag is set (fcntl FD_CLOEXEC) and inherited
otherwise.
|
cpp
|
folly/Subprocess.h
| 577
|
[] | true
| 2
| 6.48
|
facebook/folly
| 30,157
|
doxygen
| false
|
|
equalJumpTables
|
static bool equalJumpTables(const JumpTable &JumpTableA,
const JumpTable &JumpTableB,
const BinaryFunction &FunctionA,
const BinaryFunction &FunctionB) {
if (JumpTableA.EntrySize != JumpTableB.EntrySize)
return false;
if (JumpTableA.Type != JumpTableB.Type)
return false;
if (JumpTableA.getSize() != JumpTableB.getSize())
return false;
for (uint64_t Index = 0; Index < JumpTableA.Entries.size(); ++Index) {
const MCSymbol *LabelA = JumpTableA.Entries[Index];
const MCSymbol *LabelB = JumpTableB.Entries[Index];
const BinaryBasicBlock *TargetA = FunctionA.getBasicBlockForLabel(LabelA);
const BinaryBasicBlock *TargetB = FunctionB.getBasicBlockForLabel(LabelB);
if (!TargetA || !TargetB) {
assert((TargetA || LabelA == FunctionA.getFunctionEndLabel()) &&
"no target basic block found");
assert((TargetB || LabelB == FunctionB.getFunctionEndLabel()) &&
"no target basic block found");
if (TargetA != TargetB)
return false;
continue;
}
assert(TargetA && TargetB && "cannot locate target block(s)");
if (TargetA->getLayoutIndex() != TargetB->getLayoutIndex())
return false;
}
return true;
}
|
ordering of basic blocks in both binary functions (e.g. DFS).
|
cpp
|
bolt/lib/Passes/IdenticalCodeFolding.cpp
| 83
|
[] | true
| 15
| 7.04
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
getBean
|
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
String beanName = BeanFactoryUtils.transformedBeanName(name);
Object bean = obtainBean(beanName);
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (!(bean instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, bean.getClass());
}
}
else if (bean instanceof FactoryBean<?> factoryBean) {
try {
Object exposedObject =
(factoryBean instanceof SmartFactoryBean<?> smartFactoryBean && requiredType != null ?
smartFactoryBean.getObject(requiredType) : factoryBean.getObject());
if (exposedObject == null) {
throw new BeanCreationException(beanName, "FactoryBean exposed null object");
}
bean = exposedObject;
}
catch (Exception ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
}
if (requiredType != null && !requiredType.isInstance(bean)) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return (T) bean;
}
|
Add a new singleton bean.
<p>Will overwrite any existing instance for the given name.
@param name the name of the bean
@param bean the bean instance
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java
| 120
|
[
"name",
"requiredType"
] |
T
| true
| 10
| 6.88
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
equals
|
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
ItemIgnore that = (ItemIgnore) o;
return this.type == that.type && Objects.equals(this.name, that.name);
}
|
Create an ignore for a property with the given name.
@param name the name
@return the item ignore
|
java
|
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemIgnore.java
| 68
|
[
"o"
] | true
| 4
| 8.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
swap
|
public synchronized Object swap(Object newTarget) throws IllegalArgumentException {
Assert.notNull(newTarget, "Target object must not be null");
Object old = this.target;
this.target = newTarget;
return old;
}
|
Swap the target, returning the old target object.
@param newTarget the new target object
@return the old target object
@throws IllegalArgumentException if the new target is invalid
|
java
|
spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java
| 82
|
[
"newTarget"
] |
Object
| true
| 1
| 6.56
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
get_plain_output_and_tangent_nodes
|
def get_plain_output_and_tangent_nodes(
graph: fx.Graph,
) -> dict[PlainAOTOutput, tuple[fx.Node, Optional[fx.Node]]]:
"""Get plain output nodes and their corresponding tangent nodes from a joint graph.
Args:
graph: The FX joint graph with descriptors
Returns:
A dictionary mapping each PlainAOTOutput descriptor to a tuple containing:
- The plain output node
- The tangent (input) node if it exists, None otherwise
"""
return {
desc: (n, g)
for desc, (n, g) in get_all_output_and_tangent_nodes(graph).items()
if isinstance(desc, PlainAOTOutput)
}
|
Get plain output nodes and their corresponding tangent nodes from a joint graph.
Args:
graph: The FX joint graph with descriptors
Returns:
A dictionary mapping each PlainAOTOutput descriptor to a tuple containing:
- The plain output node
- The tangent (input) node if it exists, None otherwise
|
python
|
torch/_functorch/_aot_autograd/fx_utils.py
| 187
|
[
"graph"
] |
dict[PlainAOTOutput, tuple[fx.Node, Optional[fx.Node]]]
| true
| 1
| 6.56
|
pytorch/pytorch
| 96,034
|
google
| false
|
_reorder_fw_output
|
def _reorder_fw_output(self) -> None:
"""
Before the pass, fw_gm returns (*fw_outputs, *intermediates1)
and bw_gm takes (*intermediates2, *grad_fw_outputs) as input.
intermediates1 and intermediates2 share the same node names but
they might be in different order. E.g. this could happen if there
are inputs that contain symints.
To simplify downstream processing, this graph pass normalizes the output of fw_gm
to be consistent with the bacwkard inputs:
fw_gm:
- input: fw_args
- output: (*fw_outputs, *intermediates)
bw_gm:
- input: (*intermediates, *grad_fw_outputs)
- output: grad_fw_args
Example:
def fw_gm(x, y, z):
a, b, c = f(x), g(y), k(z)
return a, b, c, f_tmp, g_tmp, k_tmp
, where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates
The corresponding bw_gm has the following signature:
def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac):
return grad_x, grad_y, grad_z
"""
fw_gm_output_nodes = _find_hop_subgraph_outputs(self.fw_gm)
fw_outputs_nodes = fw_gm_output_nodes[: self.n_fw_outputs]
fw_intermediates_nodes = fw_gm_output_nodes[self.n_fw_outputs :]
if len(fw_intermediates_nodes) > 0:
fw_intermediates_name_to_node = {n.name: n for n in fw_intermediates_nodes}
# First n_intermediates placeholders
bw_names: list[str] = [
ph.name
for ph in list(self.bw_gm.graph.find_nodes(op="placeholder"))[
: self.n_intermediates
]
]
new_fw_outputs = list(fw_outputs_nodes) + [
fw_intermediates_name_to_node[name] for name in bw_names
]
output_node = self.fw_gm.graph.find_nodes(op="output")[0]
output_node.args = (tuple(new_fw_outputs),)
self.fw_gm.graph.lint()
self.fw_gm.recompile()
|
Before the pass, fw_gm returns (*fw_outputs, *intermediates1)
and bw_gm takes (*intermediates2, *grad_fw_outputs) as input.
intermediates1 and intermediates2 share the same node names but
they might be in different order. E.g. this could happen if there
are inputs that contain symints.
To simplify downstream processing, this graph pass normalizes the output of fw_gm
to be consistent with the bacwkard inputs:
fw_gm:
- input: fw_args
- output: (*fw_outputs, *intermediates)
bw_gm:
- input: (*intermediates, *grad_fw_outputs)
- output: grad_fw_args
Example:
def fw_gm(x, y, z):
a, b, c = f(x), g(y), k(z)
return a, b, c, f_tmp, g_tmp, k_tmp
, where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates
The corresponding bw_gm has the following signature:
def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac):
return grad_x, grad_y, grad_z
|
python
|
torch/_higher_order_ops/partitioner.py
| 113
|
[
"self"
] |
None
| true
| 2
| 8.48
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
getElementAtRank
|
private static ValueAndPreviousValue getElementAtRank(ExponentialHistogram histo, long rank) {
long negativeValuesCount = histo.negativeBuckets().valueCount();
long zeroCount = histo.zeroBucket().count();
if (rank < negativeValuesCount) {
if (rank == 0) {
return new ValueAndPreviousValue(Double.NaN, -getLastBucketMidpoint(histo.negativeBuckets()));
} else {
return getBucketMidpointForRank(histo.negativeBuckets().iterator(), negativeValuesCount - rank).negateAndSwap();
}
} else if (rank < (negativeValuesCount + zeroCount)) {
if (rank == negativeValuesCount) {
// the element at the previous rank falls into the negative bucket range
return new ValueAndPreviousValue(-getFirstBucketMidpoint(histo.negativeBuckets()), 0.0);
} else {
return new ValueAndPreviousValue(0.0, 0.0);
}
} else {
ValueAndPreviousValue result = getBucketMidpointForRank(
histo.positiveBuckets().iterator(),
rank - negativeValuesCount - zeroCount
);
if ((rank - 1) < negativeValuesCount) {
// previous value falls into the negative bucket range or has rank -1 and therefore doesn't exist
return new ValueAndPreviousValue(-getFirstBucketMidpoint(histo.negativeBuckets()), result.valueAtRank);
} else if ((rank - 1) < (negativeValuesCount + zeroCount)) {
// previous value falls into the zero bucket
return new ValueAndPreviousValue(0.0, result.valueAtRank);
} else {
return result;
}
}
}
|
Estimates the rank of a given value in the distribution represented by the histogram.
In other words, returns the number of values which are less than (or less-or-equal, if {@code inclusive} is true)
the provided value.
@param histo the histogram to query
@param value the value to estimate the rank for
@param inclusive if true, counts values equal to the given value as well
@return the number of elements less than (or less-or-equal, if {@code inclusive} is true) the given value
|
java
|
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramQuantile.java
| 127
|
[
"histo",
"rank"
] |
ValueAndPreviousValue
| true
| 7
| 8.24
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
_lru_cache
|
def _lru_cache(fn: Callable[P, R]) -> Callable[P, R]:
"""LRU cache decorator with TypeError fallback.
Provides LRU caching with a fallback mechanism that calls the original
function if caching fails due to unhashable arguments. Uses a cache
size of 64 with typed comparison.
Args:
fn: The function to be cached.
Returns:
A wrapper function that attempts caching with fallback to original function.
"""
cached_fn = lru_cache(maxsize=64, typed=True)(fn)
@wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[type-var]
try:
return cached_fn(*args, **kwargs) # type: ignore[arg-type]
except TypeError:
return fn(*args, **kwargs)
return wrapper
|
LRU cache decorator with TypeError fallback.
Provides LRU caching with a fallback mechanism that calls the original
function if caching fails due to unhashable arguments. Uses a cache
size of 64 with typed comparison.
Args:
fn: The function to be cached.
Returns:
A wrapper function that attempts caching with fallback to original function.
|
python
|
torch/_inductor/runtime/caching/utils.py
| 18
|
[
"fn"
] |
Callable[P, R]
| true
| 1
| 6.72
|
pytorch/pytorch
| 96,034
|
google
| false
|
wrapValueSupplier
|
private static <C, V> Function<C, V> wrapValueSupplier(@Nullable Supplier<V> valueSupplier) {
return valueSupplier == null ? c -> { throw new NullPointerException(); } : c -> valueSupplier.get();
}
|
Creates a new ObjectParser.
@param name the parsers name, used to reference the parser in exceptions and messages.
@param ignoreUnknownFields Should this parser ignore unknown fields? This should generally be set to true only when parsing
responses from external systems, never when parsing requests from users.
@param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser.
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java
| 204
|
[
"valueSupplier"
] | true
| 2
| 6.64
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
install_global_by_id
|
def install_global_by_id(self, prefix: str, value: Any) -> str:
"""
Installs a global if it hasn't been installed already.
This is determined by (prefix, id(value)) pair.
Returns the name of the newly installed global.
"""
# NB: need self.compile_id to distinguish this global
# from another global created in a different torch.compile instance
name = f"{prefix}_{id(value)}_c{self.compile_id}"
if name in self.installed_globals:
return name
self.install_global_unsafe(name, value)
return name
|
Installs a global if it hasn't been installed already.
This is determined by (prefix, id(value)) pair.
Returns the name of the newly installed global.
|
python
|
torch/_dynamo/output_graph.py
| 2,707
|
[
"self",
"prefix",
"value"
] |
str
| true
| 2
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
_
|
def _(group: SerializedTaskGroup, run_id: str, *, session: Session) -> int:
"""
Return the number of instances a task in this group should be mapped to at run time.
This considers both literal and non-literal mapped arguments, and the
result is therefore available when all depended tasks have finished. The
return value should be identical to ``parse_time_mapped_ti_count`` if
all mapped arguments are literal.
If this group is inside mapped task groups, all the nested counts are
multiplied and accounted.
:raise NotFullyPopulated: If upstream tasks are not all complete yet.
:return: Total number of mapped TIs this task should have.
"""
from airflow.serialization.serialized_objects import BaseSerialization, _ExpandInputRef
def iter_mapped_task_group_lengths(group) -> Iterator[int]:
while group is not None:
if isinstance(group, SerializedMappedTaskGroup):
exp_input = group._expand_input
# TODO (GH-52141): 'group' here should be scheduler-bound and returns scheduler expand input.
if not hasattr(exp_input, "get_total_map_length"):
if TYPE_CHECKING:
assert isinstance(group.dag, SerializedDAG)
exp_input = _ExpandInputRef(
exp_input.EXPAND_INPUT_TYPE,
BaseSerialization.deserialize(BaseSerialization.serialize(exp_input.value)),
).deref(group.dag)
yield exp_input.get_total_map_length(run_id, session=session)
group = group.parent_group
return functools.reduce(operator.mul, iter_mapped_task_group_lengths(group))
|
Return the number of instances a task in this group should be mapped to at run time.
This considers both literal and non-literal mapped arguments, and the
result is therefore available when all depended tasks have finished. The
return value should be identical to ``parse_time_mapped_ti_count`` if
all mapped arguments are literal.
If this group is inside mapped task groups, all the nested counts are
multiplied and accounted.
:raise NotFullyPopulated: If upstream tasks are not all complete yet.
:return: Total number of mapped TIs this task should have.
|
python
|
airflow-core/src/airflow/models/mappedoperator.py
| 552
|
[
"group",
"run_id",
"session"
] |
int
| true
| 5
| 6.88
|
apache/airflow
| 43,597
|
unknown
| false
|
getVirtualThreads
|
@SuppressWarnings("unchecked")
public @Nullable VirtualThreadsInfo getVirtualThreads() {
if (!VIRTUAL_THREAD_SCHEDULER_CLASS_PRESENT) {
return null;
}
try {
Class<PlatformManagedObject> mxbeanClass = (Class<PlatformManagedObject>) ClassUtils
.forName(VIRTUAL_THREAD_SCHEDULER_CLASS, null);
PlatformManagedObject mxbean = ManagementFactory.getPlatformMXBean(mxbeanClass);
int mountedVirtualThreadCount = invokeMethod(mxbeanClass, mxbean, "getMountedVirtualThreadCount");
long queuedVirtualThreadCount = invokeMethod(mxbeanClass, mxbean, "getQueuedVirtualThreadCount");
int parallelism = invokeMethod(mxbeanClass, mxbean, "getParallelism");
int poolSize = invokeMethod(mxbeanClass, mxbean, "getPoolSize");
return new VirtualThreadsInfo(mountedVirtualThreadCount, queuedVirtualThreadCount, parallelism, poolSize);
}
catch (ReflectiveOperationException ex) {
return null;
}
}
|
Virtual threads information for the process. These values provide details about the
current state of virtual threads, including the number of mounted threads, queued
threads, the parallelism level, and the thread pool size.
@return an instance of {@link VirtualThreadsInfo} containing information about
virtual threads, or {@code null} if the VirtualThreadSchedulerMXBean is not
available
@since 3.5.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/info/ProcessInfo.java
| 98
|
[] |
VirtualThreadsInfo
| true
| 3
| 7.44
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
setAsText
|
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (!StringUtils.hasText(text)) {
setValue(null);
return;
}
// Check whether we got an absolute file path without "file:" prefix.
// For backwards compatibility, we'll consider those as straight file path.
File file = null;
if (!ResourceUtils.isUrl(text)) {
file = new File(text);
if (file.isAbsolute()) {
setValue(file);
return;
}
}
// Proceed with standard resource location parsing.
this.resourceEditor.setAsText(text);
Resource resource = (Resource) this.resourceEditor.getValue();
// If it's a URL or a path pointing to an existing resource, use it as-is.
if (file == null || resource.exists()) {
try {
setValue(resource.getFile());
}
catch (IOException ex) {
throw new IllegalArgumentException(
"Could not retrieve file for " + resource + ": " + ex.getMessage());
}
}
else {
// Set a relative File reference and hope for the best.
setValue(file);
}
}
|
Create a new FileEditor, using the given ResourceEditor underneath.
@param resourceEditor the ResourceEditor to use
|
java
|
spring-beans/src/main/java/org/springframework/beans/propertyeditors/FileEditor.java
| 78
|
[
"text"
] |
void
| true
| 7
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
parsePostfixTypeOrHigher
|
function parsePostfixTypeOrHigher(): TypeNode {
const pos = getNodePos();
let type = parseNonArrayType();
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case SyntaxKind.ExclamationToken:
nextToken();
type = finishNode(factory.createJSDocNonNullableType(type, /*postfix*/ true), pos);
break;
case SyntaxKind.QuestionToken:
// If next token is start of a type we have a conditional type
if (lookAhead(nextTokenIsStartOfType)) {
return type;
}
nextToken();
type = finishNode(factory.createJSDocNullableType(type, /*postfix*/ true), pos);
break;
case SyntaxKind.OpenBracketToken:
parseExpected(SyntaxKind.OpenBracketToken);
if (isStartOfType()) {
const indexType = parseType();
parseExpected(SyntaxKind.CloseBracketToken);
type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
}
else {
parseExpected(SyntaxKind.CloseBracketToken);
type = finishNode(factory.createArrayTypeNode(type), pos);
}
break;
default:
return type;
}
}
return type;
}
|
Reports a diagnostic error for the current token being an invalid name.
@param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
@param nameDiagnostic Diagnostic to report for all other cases.
@param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
|
typescript
|
src/compiler/parser.ts
| 4,716
|
[] | true
| 5
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
prepareScheduler
|
private Scheduler prepareScheduler(SchedulerFactory schedulerFactory) throws SchedulerException {
if (this.resourceLoader != null) {
// Make given ResourceLoader available for SchedulerFactory configuration.
configTimeResourceLoaderHolder.set(this.resourceLoader);
}
if (this.taskExecutor != null) {
// Make given TaskExecutor available for SchedulerFactory configuration.
configTimeTaskExecutorHolder.set(this.taskExecutor);
}
if (this.dataSource != null) {
// Make given DataSource available for SchedulerFactory configuration.
configTimeDataSourceHolder.set(this.dataSource);
}
if (this.nonTransactionalDataSource != null) {
// Make given non-transactional DataSource available for SchedulerFactory configuration.
configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
}
// Get Scheduler instance from SchedulerFactory.
try {
Scheduler scheduler = createScheduler(schedulerFactory, this.schedulerName);
populateSchedulerContext(scheduler);
if (!this.jobFactorySet && !(scheduler instanceof RemoteScheduler)) {
// Use AdaptableJobFactory as default for a local Scheduler, unless when
// explicitly given a null value through the "jobFactory" bean property.
this.jobFactory = new AdaptableJobFactory();
}
if (this.jobFactory != null) {
if (this.applicationContext != null && this.jobFactory instanceof ApplicationContextAware applicationContextAware) {
applicationContextAware.setApplicationContext(this.applicationContext);
}
if (this.jobFactory instanceof SchedulerContextAware schedulerContextAware) {
schedulerContextAware.setSchedulerContext(scheduler.getContext());
}
scheduler.setJobFactory(this.jobFactory);
}
return scheduler;
}
finally {
if (this.resourceLoader != null) {
configTimeResourceLoaderHolder.remove();
}
if (this.taskExecutor != null) {
configTimeTaskExecutorHolder.remove();
}
if (this.dataSource != null) {
configTimeDataSourceHolder.remove();
}
if (this.nonTransactionalDataSource != null) {
configTimeNonTransactionalDataSourceHolder.remove();
}
}
}
|
Initialize the given SchedulerFactory, applying locally defined Quartz properties to it.
@param schedulerFactory the SchedulerFactory to initialize
|
java
|
spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java
| 584
|
[
"schedulerFactory"
] |
Scheduler
| true
| 15
| 6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
updateGroupSubscription
|
private void updateGroupSubscription(Set<String> topics) {
// the leader will begin watching for changes to any of the topics the group is interested in,
// which ensures that all metadata changes will eventually be seen
if (this.subscriptions.groupSubscribe(topics))
metadata.requestUpdateForNewTopics();
// update metadata (if needed) and keep track of the metadata used for assignment so that
// we can check after rebalance completion whether anything has changed
if (!client.ensureFreshMetadata(time.timer(Long.MAX_VALUE)))
throw new TimeoutException();
maybeUpdateSubscriptionMetadata();
}
|
Return the time to the next needed invocation of {@link ConsumerNetworkClient#poll(Timer)}.
@param now current time in milliseconds
@return the maximum time in milliseconds the caller should wait before the next invocation of poll()
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java
| 591
|
[
"topics"
] |
void
| true
| 3
| 7.44
|
apache/kafka
| 31,560
|
javadoc
| false
|
toPath
|
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
|
Converts `value` to a property path array.
@static
@memberOf _
@since 4.0.0
@category Util
@param {*} value The value to convert.
@returns {Array} Returns the new property path array.
@example
_.toPath('a.b.c');
// => ['a', 'b', 'c']
_.toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']
|
javascript
|
lodash.js
| 16,282
|
[
"value"
] | false
| 3
| 7.68
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
parseUnsignedByte
|
@CanIgnoreReturnValue
public static byte parseUnsignedByte(String string, int radix) {
int parse = Integer.parseInt(checkNotNull(string), radix);
// We need to throw a NumberFormatException, so we have to duplicate checkedCast. =(
if (parse >> Byte.SIZE == 0) {
return (byte) parse;
} else {
throw new NumberFormatException("out of range: " + parse);
}
}
|
Returns the unsigned {@code byte} value represented by a string with the given radix.
@param string the string containing the unsigned {@code byte} representation to be parsed.
@param radix the radix to use while parsing {@code string}
@throws NumberFormatException if the string does not contain a valid unsigned {@code byte} with
the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link
Character#MAX_RADIX}.
@throws NullPointerException if {@code string} is null (in contrast to {@link
Byte#parseByte(String)})
@since 13.0
|
java
|
android/guava/src/com/google/common/primitives/UnsignedBytes.java
| 228
|
[
"string",
"radix"
] | true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
|
_get_task_team_name
|
def _get_task_team_name(self, task_instance: TaskInstance, session: Session) -> str | None:
"""
Resolve team name for a task instance using the DAG > Bundle > Team relationship chain.
TaskInstance > DagModel (via dag_id) > DagBundleModel (via bundle_name) > Team
:param task_instance: The TaskInstance to resolve team name for
:param session: Database session for queries
:return: Team name if found or None
"""
# Use the batch query function with a single DAG ID
dag_id_to_team_name = self._get_team_names_for_dag_ids([task_instance.dag_id], session)
team_name = dag_id_to_team_name.get(task_instance.dag_id)
if team_name:
self.log.debug(
"Resolved team name '%s' for task %s (dag_id=%s)",
team_name,
task_instance.task_id,
task_instance.dag_id,
)
else:
self.log.debug(
"No team found for task %s (dag_id=%s) - DAG may not have bundle or team association",
task_instance.task_id,
task_instance.dag_id,
)
return team_name
|
Resolve team name for a task instance using the DAG > Bundle > Team relationship chain.
TaskInstance > DagModel (via dag_id) > DagBundleModel (via bundle_name) > Team
:param task_instance: The TaskInstance to resolve team name for
:param session: Database session for queries
:return: Team name if found or None
|
python
|
airflow-core/src/airflow/jobs/scheduler_job_runner.py
| 324
|
[
"self",
"task_instance",
"session"
] |
str | None
| true
| 3
| 7.92
|
apache/airflow
| 43,597
|
sphinx
| false
|
newEnumMap
|
public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap(
Class<K> type) {
return new EnumMap<>(checkNotNull(type));
}
|
Creates an {@code EnumMap} instance.
@param type the key type for this map
@return a new, empty {@code EnumMap}
|
java
|
android/guava/src/com/google/common/collect/Maps.java
| 421
|
[
"type"
] | true
| 1
| 6.32
|
google/guava
| 51,352
|
javadoc
| false
|
|
writeBlock
|
private void writeBlock() throws IOException {
if (bufferOffset == 0) {
return;
}
int compressedLength = compressor.compress(buffer, 0, bufferOffset, compressedBuffer, 0);
byte[] bufferToWrite = compressedBuffer;
int compressMethod = 0;
// Store block uncompressed if compressed length is greater (incompressible)
if (compressedLength >= bufferOffset) {
bufferToWrite = buffer;
compressedLength = bufferOffset;
compressMethod = LZ4_FRAME_INCOMPRESSIBLE_MASK;
}
// Write content
ByteUtils.writeUnsignedIntLE(out, compressedLength | compressMethod);
out.write(bufferToWrite, 0, compressedLength);
// Calculate and write block checksum
if (flg.isBlockChecksumSet()) {
int hash = checksum.hash(bufferToWrite, 0, compressedLength, 0);
ByteUtils.writeUnsignedIntLE(out, hash);
}
bufferOffset = 0;
}
|
Compresses buffered data, optionally computes an XXHash32 checksum, and writes the result to the underlying
{@link OutputStream}.
@throws IOException
|
java
|
clients/src/main/java/org/apache/kafka/common/compress/Lz4BlockOutputStream.java
| 148
|
[] |
void
| true
| 4
| 6.24
|
apache/kafka
| 31,560
|
javadoc
| false
|
log10
|
def log10(x):
"""
Compute the logarithm base 10 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this
is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)``
returns ``inf``). Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose log base 10 is (are) required.
Returns
-------
out : ndarray or scalar
The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`,
otherwise an array object is returned.
See Also
--------
numpy.log10
Notes
-----
For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10`
(note, however, that otherwise `numpy.log10` and this `log10` are
identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`,
and, notably, the complex principle value if ``x.imag != 0``).
Examples
--------
>>> import numpy as np
(We set the printing precision so the example can be auto-tested)
>>> np.set_printoptions(precision=4)
>>> np.emath.log10(10**1)
1.0
>>> np.emath.log10([-10**1, -10**2, 10**2])
array([1.+1.3644j, 2.+1.3644j, 2.+0.j ])
"""
x = _fix_real_lt_zero(x)
return nx.log10(x)
|
Compute the logarithm base 10 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this
is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)``
returns ``inf``). Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose log base 10 is (are) required.
Returns
-------
out : ndarray or scalar
The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`,
otherwise an array object is returned.
See Also
--------
numpy.log10
Notes
-----
For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10`
(note, however, that otherwise `numpy.log10` and this `log10` are
identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`,
and, notably, the complex principle value if ``x.imag != 0``).
Examples
--------
>>> import numpy as np
(We set the printing precision so the example can be auto-tested)
>>> np.set_printoptions(precision=4)
>>> np.emath.log10(10**1)
1.0
>>> np.emath.log10([-10**1, -10**2, 10**2])
array([1.+1.3644j, 2.+1.3644j, 2.+0.j ])
|
python
|
numpy/lib/_scimath_impl.py
| 293
|
[
"x"
] | false
| 1
| 6.48
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
isTriviallyAllowed
|
boolean isTriviallyAllowed(Class<?> requestingClass) {
// note: do not log exceptions in here, this could interfere with loading of additionally necessary classes such as ThrowableProxy
if (requestingClass == null) {
generalLogger.trace("Entitlement trivially allowed: no caller frames outside the entitlement library");
return true;
}
if (requestingClass == NO_CLASS) {
generalLogger.trace("Entitlement trivially allowed from outermost frame");
return true;
}
if (isTrustedSystemClass(requestingClass)) {
// note: no logging here, this has caused ClassCircularityErrors in certain cases
return true;
}
generalLogger.trace("Entitlement not trivially allowed");
return false;
}
|
@return true if permission is granted regardless of the entitlement
|
java
|
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/PolicyManager.java
| 384
|
[
"requestingClass"
] | true
| 4
| 6.4
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
removeLast
|
@CanIgnoreReturnValue
public E removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return removeAndGet(getMaxElementIndex());
}
|
Removes and returns the greatest element of this queue.
@throws NoSuchElementException if the queue is empty
|
java
|
android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
| 377
|
[] |
E
| true
| 2
| 6.72
|
google/guava
| 51,352
|
javadoc
| false
|
lastNode
|
private @Nullable AvlNode<E> lastNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasUpperBound()) {
// The cast is safe because of the hasUpperBound check.
E endpoint = uncheckedCastNullableTToT(range.getUpperEndpoint());
node = root.floor(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getUpperBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.pred();
}
} else {
node = header.pred();
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
|
Returns the first node in the tree that is in range.
|
java
|
android/guava/src/com/google/common/collect/TreeMultiset.java
| 423
|
[] | true
| 8
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
|
_describe_with_dom_dow_fix
|
def _describe_with_dom_dow_fix(self, expression: str) -> str:
"""
Return cron description with fix for DOM+DOW conflicts.
If both DOM and DOW are restricted, explain them as OR.
"""
cron_fields = expression.split()
if len(cron_fields) < 5:
return ExpressionDescriptor(
expression, casing_type=CasingTypeEnum.Sentence, use_24hour_time_format=True
).get_description()
dom = cron_fields[2]
dow = cron_fields[4]
if dom != "*" and dow != "*":
# Case: conflict → DOM OR DOW
cron_fields_dom = cron_fields.copy()
cron_fields_dom[4] = "*"
day_of_month_desc = ExpressionDescriptor(
" ".join(cron_fields_dom), casing_type=CasingTypeEnum.Sentence, use_24hour_time_format=True
).get_description()
cron_fields_dow = cron_fields.copy()
cron_fields_dow[2] = "*"
day_of_week_desc = ExpressionDescriptor(
" ".join(cron_fields_dow), casing_type=CasingTypeEnum.Sentence, use_24hour_time_format=True
).get_description()
return f"{day_of_month_desc} (or) {day_of_week_desc}"
# no conflict → return normal description
return ExpressionDescriptor(
expression, casing_type=CasingTypeEnum.Sentence, use_24hour_time_format=True
).get_description()
|
Return cron description with fix for DOM+DOW conflicts.
If both DOM and DOW are restricted, explain them as OR.
|
python
|
airflow-core/src/airflow/timetables/_cron.py
| 84
|
[
"self",
"expression"
] |
str
| true
| 4
| 6
|
apache/airflow
| 43,597
|
unknown
| false
|
_convert_to_color
|
def _convert_to_color(cls, color_spec):
"""
Convert ``color_spec`` to an openpyxl v2 Color object.
Parameters
----------
color_spec : str, dict
A 32-bit ARGB hex string, or a dict with zero or more of the
following keys.
'rgb'
'indexed'
'auto'
'theme'
'tint'
'index'
'type'
Returns
-------
color : openpyxl.styles.Color
"""
from openpyxl.styles import Color
if isinstance(color_spec, str):
return Color(color_spec)
else:
return Color(**color_spec)
|
Convert ``color_spec`` to an openpyxl v2 Color object.
Parameters
----------
color_spec : str, dict
A 32-bit ARGB hex string, or a dict with zero or more of the
following keys.
'rgb'
'indexed'
'auto'
'theme'
'tint'
'index'
'type'
Returns
-------
color : openpyxl.styles.Color
|
python
|
pandas/io/excel/_openpyxl.py
| 155
|
[
"cls",
"color_spec"
] | false
| 3
| 6.08
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
_acquire_flock_with_timeout
|
def _acquire_flock_with_timeout(
flock: BaseFileLock,
timeout: float | None = None,
) -> Generator[None, None, None]:
"""Context manager that safely acquires a FileLock with timeout and automatically releases it.
This function provides a safe way to acquire a file lock with timeout support, ensuring
the lock is always released even if an exception occurs during execution.
Args:
flock: The FileLock object to acquire
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
- Use _BLOCKING (-1.0) for infinite wait
- Use _NON_BLOCKING (0.0) for immediate return
- Use positive value for finite timeout
Yields:
None: Yields control to the caller while holding the file lock
Raises:
FileLockTimeoutError: If the file lock cannot be acquired within the timeout period
Example:
flock = FileLock("/tmp/my_process.lock")
with _acquire_flock_with_timeout(flock, timeout=30.0):
# Critical section - file lock is held
perform_exclusive_file_operation()
# File lock is automatically released here
"""
_unsafe_acquire_flock_with_timeout(flock, timeout=timeout)
try:
yield
finally:
flock.release()
|
Context manager that safely acquires a FileLock with timeout and automatically releases it.
This function provides a safe way to acquire a file lock with timeout support, ensuring
the lock is always released even if an exception occurs during execution.
Args:
flock: The FileLock object to acquire
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
- Use _BLOCKING (-1.0) for infinite wait
- Use _NON_BLOCKING (0.0) for immediate return
- Use positive value for finite timeout
Yields:
None: Yields control to the caller while holding the file lock
Raises:
FileLockTimeoutError: If the file lock cannot be acquired within the timeout period
Example:
flock = FileLock("/tmp/my_process.lock")
with _acquire_flock_with_timeout(flock, timeout=30.0):
# Critical section - file lock is held
perform_exclusive_file_operation()
# File lock is automatically released here
|
python
|
torch/_inductor/runtime/caching/locks.py
| 121
|
[
"flock",
"timeout"
] |
Generator[None, None, None]
| true
| 1
| 6.8
|
pytorch/pytorch
| 96,034
|
google
| false
|
resolveCache
|
protected Cache resolveCache(CacheOperationInvocationContext<O> context) {
Collection<? extends Cache> caches = context.getOperation().getCacheResolver().resolveCaches(context);
Cache cache = extractFrom(caches);
if (cache == null) {
throw new IllegalStateException("Cache could not have been resolved for " + context.getOperation());
}
return cache;
}
|
Resolve the cache to use.
@param context the invocation context
@return the cache to use (never {@code null})
|
java
|
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractCacheInterceptor.java
| 63
|
[
"context"
] |
Cache
| true
| 2
| 8.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
set_nulls
|
def set_nulls(
data: np.ndarray | pd.Series,
col: Column,
validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
allow_modify_inplace: bool = True,
) -> np.ndarray | pd.Series:
"""
Set null values for the data according to the column null kind.
Parameters
----------
data : np.ndarray or pd.Series
Data to set nulls in.
col : Column
Column object that describes the `data`.
validity : tuple(Buffer, dtype) or None
The return value of ``col.buffers()``. We do not access the ``col.buffers()``
here to not take the ownership of the memory of buffer objects.
allow_modify_inplace : bool, default: True
Whether to modify the `data` inplace when zero-copy is possible (True) or always
modify a copy of the `data` (False).
Returns
-------
np.ndarray or pd.Series
Data with the nulls being set.
"""
if validity is None:
return data
null_kind, sentinel_val = col.describe_null
null_pos = None
if null_kind == ColumnNullType.USE_SENTINEL:
null_pos = pd.Series(data) == sentinel_val
elif null_kind in (ColumnNullType.USE_BITMASK, ColumnNullType.USE_BYTEMASK):
valid_buff, valid_dtype = validity
null_pos = buffer_to_ndarray(
valid_buff, valid_dtype, offset=col.offset, length=col.size()
)
if sentinel_val == 0:
null_pos = ~null_pos
elif null_kind in (ColumnNullType.NON_NULLABLE, ColumnNullType.USE_NAN):
pass
else:
raise NotImplementedError(f"Null kind {null_kind} is not yet supported.")
if null_pos is not None and np.any(null_pos):
if not allow_modify_inplace:
data = data.copy()
try:
data[null_pos] = None
except TypeError:
# TypeError happens if the `data` dtype appears to be non-nullable
# in numpy notation (bool, int, uint). If this happens,
# cast the `data` to nullable float dtype.
data = data.astype(float)
data[null_pos] = None
return data
|
Set null values for the data according to the column null kind.
Parameters
----------
data : np.ndarray or pd.Series
Data to set nulls in.
col : Column
Column object that describes the `data`.
validity : tuple(Buffer, dtype) or None
The return value of ``col.buffers()``. We do not access the ``col.buffers()``
here to not take the ownership of the memory of buffer objects.
allow_modify_inplace : bool, default: True
Whether to modify the `data` inplace when zero-copy is possible (True) or always
modify a copy of the `data` (False).
Returns
-------
np.ndarray or pd.Series
Data with the nulls being set.
|
python
|
pandas/core/interchange/from_dataframe.py
| 555
|
[
"data",
"col",
"validity",
"allow_modify_inplace"
] |
np.ndarray | pd.Series
| true
| 10
| 6.96
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
description
|
public String description() {
return this.description;
}
|
Get the description of the metric.
@return the metric description; never null
|
java
|
clients/src/main/java/org/apache/kafka/common/MetricNameTemplate.java
| 96
|
[] |
String
| true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
createHeaderFilters
|
function createHeaderFilters (matchOptions = {}) {
const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions
return {
ignore: new Set(ignoreHeaders.map(header => caseSensitive ? header : header.toLowerCase())),
exclude: new Set(excludeHeaders.map(header => caseSensitive ? header : header.toLowerCase())),
match: new Set(matchHeaders.map(header => caseSensitive ? header : header.toLowerCase()))
}
}
|
Creates cached header sets for performance
@param {import('./snapshot-recorder').SnapshotRecorderMatchOptions} matchOptions - Matching options for headers
@returns {HeaderFilters} - Cached sets for ignore, exclude, and match headers
|
javascript
|
deps/undici/src/lib/mock/snapshot-utils.js
| 18
|
[] | false
| 4
| 6.16
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
pendingToString
|
@Override
protected @Nullable String pendingToString() {
@RetainedLocalRef ListenableFuture<? extends I> localInputFuture = inputFuture;
@RetainedLocalRef F localFunction = function;
String superString = super.pendingToString();
String resultString = "";
if (localInputFuture != null) {
resultString = "inputFuture=[" + localInputFuture + "], ";
}
if (localFunction != null) {
return resultString + "function=[" + localFunction + "]";
} else if (superString != null) {
return resultString + superString;
}
return null;
}
|
Template method for subtypes to actually set the result.
|
java
|
android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
| 192
|
[] |
String
| true
| 4
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
check_and_run_migrations
|
def check_and_run_migrations():
"""Check and run migrations if necessary. Only use in a tty."""
with _configured_alembic_environment() as env:
context = env.get_context()
source_heads = set(env.script.get_heads())
db_heads = set(context.get_current_heads())
db_command = None
command_name = None
verb = None
if len(db_heads) < 1:
db_command = initdb
command_name = "migrate"
verb = "initialize"
elif source_heads != db_heads:
db_command = upgradedb
command_name = "migrate"
verb = "migrate"
if sys.stdout.isatty() and verb:
print()
question = f"Please confirm database {verb} (or wait 4 seconds to skip it). Are you sure? [y/N]"
try:
answer = helpers.prompt_with_timeout(question, timeout=4, default=False)
if answer:
try:
db_command()
print(f"DB {verb} done")
except Exception as error:
from airflow.version import version
print(error)
print(
"You still have unapplied migrations. "
f"You may need to {verb} the database by running `airflow db {command_name}`. ",
f"Make sure the command is run using Airflow version {version}.",
file=sys.stderr,
)
sys.exit(1)
except AirflowException:
pass
elif source_heads != db_heads:
from airflow.version import version
print(
f"ERROR: You need to {verb} the database. Please run `airflow db {command_name}`. "
f"Make sure the command is run using Airflow version {version}.",
file=sys.stderr,
)
sys.exit(1)
|
Check and run migrations if necessary. Only use in a tty.
|
python
|
airflow-core/src/airflow/utils/db.py
| 842
|
[] | false
| 7
| 6.24
|
apache/airflow
| 43,597
|
unknown
| false
|
|
run_fuzzer_with_seed
|
def run_fuzzer_with_seed(
seed: int,
template: str = "default",
supported_ops: str | None = None,
) -> FuzzerResult:
"""
Run fuzzer.py with a specific seed.
Args:
seed: The seed value to pass to fuzzer.py
template: The template to use for code generation
supported_ops: Comma-separated ops string with optional weights
Returns:
FuzzerResult dataclass instance
"""
start_time = time.time()
try:
# Run fuzzer.py with the specified seed and template
cmd = [
sys.executable,
"fuzzer.py",
"--single",
"--seed",
str(seed),
"--template",
template,
]
# Append supported ops if provided
if supported_ops:
cmd.extend(["--supported-ops", supported_ops])
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=300, # 5 minute timeout per seed
)
duration = time.time() - start_time
success = result.returncode == 0
# Combine stdout and stderr for output
output = ""
if result.stdout:
output += f"STDOUT:\n{result.stdout}\n"
if result.stderr:
output += f"STDERR:\n{result.stderr}\n"
output += f"Return code: {result.returncode}"
# Parse operation statistics from the output
operation_stats = {}
if result.stdout:
lines = result.stdout.split("\n")
in_stats_section = False
for line in lines:
if line.strip() == "OPERATION_STATS:":
in_stats_section = True
continue
elif in_stats_section:
if line.startswith(" ") and ":" in line:
# Parse line like " torch.add: 3"
op_line = line.strip()
if ": " in op_line:
op_name, count_str = op_line.split(": ", 1)
try:
count = int(count_str)
operation_stats[op_name] = count
except ValueError:
pass # Skip malformed lines
else:
# End of stats section
in_stats_section = False
# Check if output should be ignored and which pattern matched
ignored_pattern_idx = is_ignored_output(output)
if ignored_pattern_idx != -1:
# Mark as ignored (could also return a special flag if needed)
output = "[IGNORED] " + output
return FuzzerResult(
seed, success, output, duration, ignored_pattern_idx, operation_stats
)
except subprocess.TimeoutExpired:
duration = time.time() - start_time
return FuzzerResult(
seed, False, "Process timed out after 300 seconds", duration, -1, {}
)
except Exception as e:
duration = time.time() - start_time
return FuzzerResult(
seed, False, f"Exception occurred: {str(e)}", duration, -1, {}
)
|
Run fuzzer.py with a specific seed.
Args:
seed: The seed value to pass to fuzzer.py
template: The template to use for code generation
supported_ops: Comma-separated ops string with optional weights
Returns:
FuzzerResult dataclass instance
|
python
|
tools/experimental/torchfuzz/multi_process_fuzzer.py
| 83
|
[
"seed",
"template",
"supported_ops"
] |
FuzzerResult
| true
| 13
| 7.68
|
pytorch/pytorch
| 96,034
|
google
| false
|
subscription
|
public Set<String> subscription() {
return delegate.subscription();
}
|
Get the current subscription. Will return the same topics used in the most recent call to
{@link #subscribe(Collection, ConsumerRebalanceListener)}, or an empty set if no such call has been made.
@return The set of topics currently subscribed to
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java
| 651
|
[] | true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
pearsonsCorrelationCoefficient
|
public double pearsonsCorrelationCoefficient() {
checkState(count() > 1);
if (isNaN(sumOfProductsOfDeltas)) {
return NaN;
}
double xSumOfSquaresOfDeltas = xStats().sumOfSquaresOfDeltas();
double ySumOfSquaresOfDeltas = yStats().sumOfSquaresOfDeltas();
checkState(xSumOfSquaresOfDeltas > 0.0);
checkState(ySumOfSquaresOfDeltas > 0.0);
// The product of two positive numbers can be zero if the multiplication underflowed. We
// force a positive value by effectively rounding up to MIN_VALUE.
double productOfSumsOfSquaresOfDeltas =
ensurePositive(xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas);
return ensureInUnitRange(sumOfProductsOfDeltas / Math.sqrt(productOfSumsOfSquaresOfDeltas));
}
|
Returns the <a href="http://mathworld.wolfram.com/CorrelationCoefficient.html">Pearson's or
product-moment correlation coefficient</a> of the values. The count must greater than one, and
the {@code x} and {@code y} values must both have non-zero population variance (i.e. {@code
xStats().populationVariance() > 0.0 && yStats().populationVariance() > 0.0}). The result is not
guaranteed to be exactly +/-1 even when the data are perfectly (anti-)correlated, due to
numerical errors. However, it is guaranteed to be in the inclusive range [-1, +1].
<h3>Non-finite values</h3>
<p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
@throws IllegalStateException if the dataset is empty or contains a single pair of values, or
either the {@code x} and {@code y} dataset has zero population variance
|
java
|
android/guava/src/com/google/common/math/PairedStats.java
| 134
|
[] | true
| 2
| 6.4
|
google/guava
| 51,352
|
javadoc
| false
|
|
apply_list_or_dict_like
|
def apply_list_or_dict_like(self) -> DataFrame | Series:
"""
Compute apply in case of a list-like or dict-like.
Returns
-------
result: Series, DataFrame, or None
Result when self.func is a list-like or dict-like, None otherwise.
"""
if self.engine == "numba":
raise NotImplementedError(
"The 'numba' engine doesn't support list-like/"
"dict likes of callables yet."
)
if self.axis == 1 and isinstance(self.obj, ABCDataFrame):
return self.obj.T.apply(self.func, 0, args=self.args, **self.kwargs).T
func = self.func
kwargs = self.kwargs
if is_dict_like(func):
result = self.agg_or_apply_dict_like(op_name="apply")
else:
result = self.agg_or_apply_list_like(op_name="apply")
result = reconstruct_and_relabel_result(result, func, **kwargs)
return result
|
Compute apply in case of a list-like or dict-like.
Returns
-------
result: Series, DataFrame, or None
Result when self.func is a list-like or dict-like, None otherwise.
|
python
|
pandas/core/apply.py
| 703
|
[
"self"
] |
DataFrame | Series
| true
| 6
| 6.88
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
maybeUnwrapException
|
public static Throwable maybeUnwrapException(Throwable t) {
if (t instanceof CompletionException || t instanceof ExecutionException) {
return t.getCause();
} else {
return t;
}
}
|
Check if a Throwable is a commonly wrapped exception type (e.g. `CompletionException`) and return
the cause if so. This is useful to handle cases where exceptions may be raised from a future or a
completion stage (as might be the case for requests sent to the controller in `ControllerApis`).
@param t The Throwable to check
@return The throwable itself or its cause if it is an instance of a commonly wrapped exception type
|
java
|
clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
| 541
|
[
"t"
] |
Throwable
| true
| 3
| 8.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
check_max_runs_and_schedule_interval_compatibility
|
def check_max_runs_and_schedule_interval_compatibility(
performance_dag_conf: dict[str, str],
) -> None:
"""
Validate max_runs value.
Check if max_runs and schedule_interval values create a valid combination.
:param performance_dag_conf: dict with environment variables as keys and their values as values
:raises: ValueError:
if max_runs is specified when schedule_interval is not a duration time expression
if max_runs is not specified when schedule_interval is a duration time expression
if max_runs, schedule_interval and start_ago form a combination which causes end_date
to be in the future
"""
schedule_interval = get_performance_dag_environment_variable(
performance_dag_conf, "PERF_SCHEDULE_INTERVAL"
)
max_runs = get_performance_dag_environment_variable(performance_dag_conf, "PERF_MAX_RUNS")
start_ago = get_performance_dag_environment_variable(performance_dag_conf, "PERF_START_AGO")
if schedule_interval == "@once":
if max_runs is not None:
raise ValueError(
"PERF_MAX_RUNS is allowed only if PERF_SCHEDULE_INTERVAL is provided as a time expression."
)
# if dags are set to be scheduled once, we do not need to check end_date
return
if max_runs is None:
raise ValueError(
"PERF_MAX_RUNS must be specified if PERF_SCHEDULE_INTERVAL is provided as a time expression."
)
max_runs = int(max_runs)
# make sure that the end_date does not occur in future
current_date = datetime.now()
start_date = current_date - check_and_parse_time_delta("PERF_START_AGO", start_ago)
end_date = start_date + (
check_and_parse_time_delta("PERF_SCHEDULE_INTERVAL", schedule_interval) * (max_runs - 1)
)
if current_date < end_date:
raise ValueError(
f"PERF_START_AGO ({start_ago}), "
f"PERF_SCHEDULE_INTERVAL ({schedule_interval}) "
f"and PERF_MAX_RUNS ({max_runs}) "
f"must be specified in such a way that end_date does not occur in the future "
f"(end_date with provided values: {end_date})."
)
|
Validate max_runs value.
Check if max_runs and schedule_interval values create a valid combination.
:param performance_dag_conf: dict with environment variables as keys and their values as values
:raises: ValueError:
if max_runs is specified when schedule_interval is not a duration time expression
if max_runs is not specified when schedule_interval is a duration time expression
if max_runs, schedule_interval and start_ago form a combination which causes end_date
to be in the future
|
python
|
performance/src/performance_dags/performance_dag/performance_dag_utils.py
| 342
|
[
"performance_dag_conf"
] |
None
| true
| 5
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
overlay
|
public static String overlay(final String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
final int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
final int temp = start;
start = end;
end = temp;
}
return str.substring(0, start) + overlay + str.substring(end);
}
|
Overlays part of a String with another String.
<p>
A {@code null} string input returns {@code null}. A negative index is treated as zero. An index greater than the string length is treated as the string
length. The start index is always the smaller of the two indices.
</p>
<pre>
StringUtils.overlay(null, *, *, *) = null
StringUtils.overlay("", "abc", 0, 0) = "abc"
StringUtils.overlay("abcdef", null, 2, 4) = "abef"
StringUtils.overlay("abcdef", "", 2, 4) = "abef"
StringUtils.overlay("abcdef", "", 4, 2) = "abef"
StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
</pre>
@param str the String to do overlaying in, may be null.
@param overlay the String to overlay, may be null.
@param start the position to start overlaying at.
@param end the position to stop overlaying before.
@return overlayed String, {@code null} if null String input.
@since 2.0
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 5,543
|
[
"str",
"overlay",
"start",
"end"
] |
String
| true
| 8
| 7.6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
hideOverlayWeb
|
function hideOverlayWeb(): void {
timeoutID = null;
if (overlay !== null) {
overlay.remove();
overlay = null;
}
}
|
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@flow
|
javascript
|
packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js
| 26
|
[] | false
| 2
| 6.24
|
facebook/react
| 241,750
|
jsdoc
| false
|
|
toArray
|
@GwtIncompatible // Array.newInstance(Class, int)
public static <T extends @Nullable Object> T[] toArray(
Iterator<? extends T> iterator, Class<@NonNull T> type) {
List<T> list = Lists.newArrayList(iterator);
return Iterables.<T>toArray(list, type);
}
|
Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code
hasNext()} method will return {@code false}.
@param iterator the iterator to copy
@param type the type of the elements
@return a newly-allocated array into which all the elements of the iterator have been copied
|
java
|
android/guava/src/com/google/common/collect/Iterators.java
| 350
|
[
"iterator",
"type"
] | true
| 1
| 6.56
|
google/guava
| 51,352
|
javadoc
| false
|
|
decrementAndGet
|
public long decrementAndGet() {
value--;
return value;
}
|
Decrements this instance's value by 1; this method returns the value associated with the instance
immediately after the decrement operation. This method is not thread safe.
@return the value associated with the instance after it is decremented.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableLong.java
| 157
|
[] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
parseDefaults
|
private Map<String, String> parseDefaults(JSONObject root) throws JSONException {
Map<String, String> result = new HashMap<>();
Iterator<?> keys = root.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Object o = root.get(key);
if (o instanceof JSONObject child) {
if (child.has(DEFAULT_ATTRIBUTE)) {
result.put(key, child.getString(DEFAULT_ATTRIBUTE));
}
}
}
return result;
}
|
Returns the defaults applicable to the service.
@return the defaults of the service
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java
| 163
|
[
"root"
] | true
| 4
| 6.88
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
clone
|
@Override
public Object clone() {
return new FluentBitSet((BitSet) bitSet.clone());
}
|
Cloning this {@link BitSet} produces a new {@link BitSet} that is equal to it. The clone of the bit set is another
bit set that has exactly the same bits set to {@code true} as this bit set.
@return a clone of this bit set
@see #size()
|
java
|
src/main/java/org/apache/commons/lang3/util/FluentBitSet.java
| 191
|
[] |
Object
| true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
asanyarray
|
def asanyarray(a, dtype=None, order=None):
"""
Convert the input to a masked array, conserving subclasses.
If `a` is a subclass of `MaskedArray`, its class is conserved.
No copy is performed if the input is already an `ndarray`.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F', 'A', 'K'}, optional
Memory layout. 'A' and 'K' depend on the order of input array ``a``.
'C' row-major (C-style),
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if ``a`` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'K'.
Returns
-------
out : MaskedArray
MaskedArray interpretation of `a`.
See Also
--------
asarray : Similar to `asanyarray`, but does not conserve subclass.
Examples
--------
>>> import numpy as np
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(
data=[[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]],
mask=False,
fill_value=1e+20)
>>> type(np.ma.asanyarray(x))
<class 'numpy.ma.MaskedArray'>
"""
# workaround for #8666, to preserve identity. Ideally the bottom line
# would handle this for us.
if (
isinstance(a, MaskedArray)
and (dtype is None or dtype == a.dtype)
and (
order in {None, 'A', 'K'}
or order == 'C' and a.flags.carray
or order == 'F' and a.flags.f_contiguous
)
):
return a
return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True,
order=order)
|
Convert the input to a masked array, conserving subclasses.
If `a` is a subclass of `MaskedArray`, its class is conserved.
No copy is performed if the input is already an `ndarray`.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F', 'A', 'K'}, optional
Memory layout. 'A' and 'K' depend on the order of input array ``a``.
'C' row-major (C-style),
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if ``a`` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'K'.
Returns
-------
out : MaskedArray
MaskedArray interpretation of `a`.
See Also
--------
asarray : Similar to `asanyarray`, but does not conserve subclass.
Examples
--------
>>> import numpy as np
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(
data=[[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]],
mask=False,
fill_value=1e+20)
>>> type(np.ma.asanyarray(x))
<class 'numpy.ma.MaskedArray'>
|
python
|
numpy/ma/core.py
| 8,605
|
[
"a",
"dtype",
"order"
] | false
| 9
| 7.76
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
delay
|
def delay(delay: int | float | None = None) -> None:
"""
Pause execution for ``delay`` seconds.
:param delay: a delay to pause execution using ``time.sleep(delay)``;
a small 1 second jitter is applied to the delay.
.. note::
This method uses a default random delay, i.e.
``random.uniform(DEFAULT_DELAY_MIN, DEFAULT_DELAY_MAX)``;
using a random interval helps to avoid AWS API throttle limits
when many concurrent tasks request job-descriptions.
"""
if delay is None:
delay = random.uniform(BatchClientHook.DEFAULT_DELAY_MIN, BatchClientHook.DEFAULT_DELAY_MAX)
else:
delay = BatchClientHook.add_jitter(delay)
time.sleep(delay)
|
Pause execution for ``delay`` seconds.
:param delay: a delay to pause execution using ``time.sleep(delay)``;
a small 1 second jitter is applied to the delay.
.. note::
This method uses a default random delay, i.e.
``random.uniform(DEFAULT_DELAY_MIN, DEFAULT_DELAY_MAX)``;
using a random interval helps to avoid AWS API throttle limits
when many concurrent tasks request job-descriptions.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_client.py
| 552
|
[
"delay"
] |
None
| true
| 3
| 6.24
|
apache/airflow
| 43,597
|
sphinx
| false
|
replaceValueInEntry
|
private void replaceValueInEntry(int entry, @ParametricNullness V newValue, boolean force) {
checkArgument(entry != ABSENT);
int newValueHash = Hashing.smearedHash(newValue);
int newValueIndex = findEntryByValue(newValue, newValueHash);
if (newValueIndex != ABSENT) {
if (force) {
removeEntryValueHashKnown(newValueIndex, newValueHash);
if (entry == size) { // this entry got moved to newValueIndex
entry = newValueIndex;
}
} else {
throw new IllegalArgumentException("Value already present in map: " + newValue);
}
}
// we do *not* update insertion order, and it isn't a structural modification!
deleteFromTableVToK(entry, Hashing.smearedHash(values[entry]));
values[entry] = newValue;
insertIntoTableVToK(entry, newValueHash);
}
|
Updates the specified entry to point to the new value: removes the old value from the V-to-K
mapping and puts the new one in. The entry does not move in the insertion order of the bimap.
|
java
|
android/guava/src/com/google/common/collect/HashBiMap.java
| 477
|
[
"entry",
"newValue",
"force"
] |
void
| true
| 4
| 6
|
google/guava
| 51,352
|
javadoc
| false
|
polygrid2d
|
def polygrid2d(x, y, c):
"""
Evaluate a 2-D polynomial on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j
where the points ``(a, b)`` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
polyval, polyval2d, polyval3d, polygrid3d
Examples
--------
>>> from numpy.polynomial import polynomial as P
>>> c = ((1, 2, 3), (4, 5, 6))
>>> P.polygrid2d([0, 1], [0, 1], c)
array([[ 1., 6.],
[ 5., 21.]])
"""
return pu._gridnd(polyval, c, x, y)
|
Evaluate a 2-D polynomial on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j
where the points ``(a, b)`` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
polyval, polyval2d, polyval3d, polygrid3d
Examples
--------
>>> from numpy.polynomial import polynomial as P
>>> c = ((1, 2, 3), (4, 5, 6))
>>> P.polygrid2d([0, 1], [0, 1], c)
array([[ 1., 6.],
[ 5., 21.]])
|
python
|
numpy/polynomial/polynomial.py
| 906
|
[
"x",
"y",
"c"
] | false
| 1
| 6.32
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
upperCase
|
public static String upperCase(final String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
|
Converts a String to upper case as per {@link String#toUpperCase()}.
<p>
A {@code null} input String returns {@code null}.
</p>
<pre>
StringUtils.upperCase(null) = null
StringUtils.upperCase("") = ""
StringUtils.upperCase("aBc") = "ABC"
</pre>
<p>
<strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()}, the result of this method is affected by the current locale.
For platform-independent case transformations, the method {@link #upperCase(String, Locale)} should be used with a specific locale (e.g.
{@link Locale#ENGLISH}).
</p>
@param str the String to upper case, may be null.
@return the upper-cased String, {@code null} if null String input.
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 9,009
|
[
"str"
] |
String
| true
| 2
| 7.6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
maybeRejoinStaleMember
|
public void maybeRejoinStaleMember() {
isPollTimerExpired = false;
if (state == MemberState.STALE) {
log.debug("Expired poll timer has been reset so stale member {} will rejoin the group " +
"when it completes releasing its previous assignment.", memberId);
staleMemberAssignmentRelease.whenComplete((__, error) -> transitionToJoining());
}
}
|
Transition a {@link MemberState#STALE} member to {@link MemberState#JOINING} when it completes
releasing its assignment. This is expected to be used when the poll timer is reset.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
| 776
|
[] |
void
| true
| 2
| 6.56
|
apache/kafka
| 31,560
|
javadoc
| false
|
magic
|
public byte magic() {
return buffer.get(MAGIC_OFFSET);
}
|
The magic value (i.e. message format version) of this record
@return the magic value
|
java
|
clients/src/main/java/org/apache/kafka/common/record/LegacyRecord.java
| 197
|
[] | true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
equals
|
def equals(self, other: object) -> bool:
"""
Return if another array is equivalent to this array.
Equivalent means that both arrays have the same shape and dtype, and
all values compare equal. Missing values in the same location are
considered equal (in contrast with normal equality).
Parameters
----------
other : ExtensionArray
Array to compare to this Array.
Returns
-------
boolean
Whether the arrays are equivalent.
See Also
--------
numpy.array_equal : Equivalent method for numpy array.
Series.equals : Equivalent method for Series.
DataFrame.equals : Equivalent method for DataFrame.
Examples
--------
>>> arr1 = pd.array([1, 2, np.nan])
>>> arr2 = pd.array([1, 2, np.nan])
>>> arr1.equals(arr2)
True
>>> arr1 = pd.array([1, 3, np.nan])
>>> arr2 = pd.array([1, 2, np.nan])
>>> arr1.equals(arr2)
False
"""
if type(self) != type(other):
return False
other = cast(ExtensionArray, other)
if self.dtype != other.dtype:
return False
elif len(self) != len(other):
return False
else:
equal_values = self == other
if isinstance(equal_values, ExtensionArray):
# boolean array with NA -> fill with False
equal_values = equal_values.fillna(False)
# error: Unsupported left operand type for & ("ExtensionArray")
equal_na = self.isna() & other.isna() # type: ignore[operator]
return bool((equal_values | equal_na).all())
|
Return if another array is equivalent to this array.
Equivalent means that both arrays have the same shape and dtype, and
all values compare equal. Missing values in the same location are
considered equal (in contrast with normal equality).
Parameters
----------
other : ExtensionArray
Array to compare to this Array.
Returns
-------
boolean
Whether the arrays are equivalent.
See Also
--------
numpy.array_equal : Equivalent method for numpy array.
Series.equals : Equivalent method for Series.
DataFrame.equals : Equivalent method for DataFrame.
Examples
--------
>>> arr1 = pd.array([1, 2, np.nan])
>>> arr2 = pd.array([1, 2, np.nan])
>>> arr1.equals(arr2)
True
>>> arr1 = pd.array([1, 3, np.nan])
>>> arr2 = pd.array([1, 2, np.nan])
>>> arr1.equals(arr2)
False
|
python
|
pandas/core/arrays/base.py
| 1,521
|
[
"self",
"other"
] |
bool
| true
| 6
| 8.48
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
cloneReset
|
Object cloneReset() throws CloneNotSupportedException {
// this method exists to enable 100% test coverage
final StrTokenizer cloned = (StrTokenizer) super.clone();
if (cloned.chars != null) {
cloned.chars = cloned.chars.clone();
}
cloned.reset();
return cloned;
}
|
Creates a new instance of this Tokenizer. The new instance is reset so that
it will be at the start of the token list.
@return a new instance of this Tokenizer which has been reset.
@throws CloneNotSupportedException if there is a problem cloning.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
| 466
|
[] |
Object
| true
| 2
| 8.24
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
removeAllOccurences
|
@Deprecated
public static char[] removeAllOccurences(final char[] array, final char element) {
return (char[]) removeAt(array, indexesOf(array, element));
}
|
Removes the occurrences of the specified element from the specified char array.
<p>
All subsequent elements are shifted to the left (subtracts one from their indices).
If the array doesn't contain such an element, no elements are removed from the array.
{@code null} will be returned if the input array is {@code null}.
</p>
@param array the input array, will not be modified, and may be {@code null}.
@param element the element to remove.
@return A new array containing the existing elements except the occurrences of the specified element.
@since 3.5
@deprecated Use {@link #removeAllOccurrences(char[], char)}.
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 5,303
|
[
"array",
"element"
] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
deactivate_deleted_dags
|
def deactivate_deleted_dags(self, bundle_name: str, present: set[DagFileInfo]) -> None:
"""Deactivate DAGs that come from files that are no longer present in bundle."""
def find_zipped_dags(abs_path: os.PathLike) -> Iterator[str]:
"""
Find dag files in zip file located at abs_path.
We return the abs "paths" formed by joining the relative path inside the zip
with the path to the zip.
"""
try:
with zipfile.ZipFile(abs_path) as z:
for info in z.infolist():
if might_contain_dag(info.filename, True, z):
yield os.path.join(abs_path, info.filename)
except zipfile.BadZipFile:
self.log.exception("There was an error accessing ZIP file %s", abs_path)
rel_filelocs: list[str] = []
for info in present:
abs_path = str(info.absolute_path)
if abs_path.endswith(".py") or not zipfile.is_zipfile(abs_path):
rel_filelocs.append(str(info.rel_path))
else:
if TYPE_CHECKING:
assert info.bundle_path
for abs_sub_path in find_zipped_dags(abs_path=info.absolute_path):
rel_sub_path = Path(abs_sub_path).relative_to(info.bundle_path)
rel_filelocs.append(str(rel_sub_path))
with create_session() as session:
any_deactivated = DagModel.deactivate_deleted_dags(
bundle_name=bundle_name,
rel_filelocs=rel_filelocs,
session=session,
)
# Only run cleanup if we actually deactivated any DAGs
# This avoids unnecessary DELETE queries in the common case where no DAGs were deleted
if any_deactivated:
remove_references_to_deleted_dags(session=session)
|
Deactivate DAGs that come from files that are no longer present in bundle.
|
python
|
airflow-core/src/airflow/dag_processing/manager.py
| 616
|
[
"self",
"bundle_name",
"present"
] |
None
| true
| 10
| 6
|
apache/airflow
| 43,597
|
unknown
| false
|
indexOf
|
@Deprecated
public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
return Strings.CS.indexOf(seq, searchSeq);
}
|
Finds the first index within a CharSequence, handling {@code null}. This method uses {@link String#indexOf(String, int)} if possible.
<p>
A {@code null} CharSequence will return {@code -1}.
</p>
<pre>
StringUtils.indexOf(null, *) = -1
StringUtils.indexOf(*, null) = -1
StringUtils.indexOf("", "") = 0
StringUtils.indexOf("", *) = -1 (except when * = "")
StringUtils.indexOf("aabaabaa", "a") = 0
StringUtils.indexOf("aabaabaa", "b") = 2
StringUtils.indexOf("aabaabaa", "ab") = 1
StringUtils.indexOf("aabaabaa", "") = 0
</pre>
@param seq the CharSequence to check, may be null.
@param searchSeq the CharSequence to find, may be null.
@return the first index of the search CharSequence, -1 if no match or {@code null} string input.
@since 2.0
@since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
@deprecated Use {@link Strings#indexOf(CharSequence, CharSequence) Strings.CS.indexOf(CharSequence, CharSequence)}.
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 2,542
|
[
"seq",
"searchSeq"
] | true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
_build
|
def _build(self, values: list[T], node: int, start: int, end: int) -> None:
"""
Build the segment tree recursively.
Args:
values: Original array of values
node: Current node index in the segment tree
start: Start index of the segment
end: End index of the segment
"""
if start == end:
# Leaf node
if start < len(values):
self.tree[node] = values[start]
return
mid = (start + end) // 2
left_child = 2 * node
right_child = 2 * node + 1
# Recursively build left and right subtrees
self._build(values, left_child, start, mid)
self._build(values, right_child, mid + 1, end)
# Update current node with summary of children
self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child])
|
Build the segment tree recursively.
Args:
values: Original array of values
node: Current node index in the segment tree
start: Start index of the segment
end: End index of the segment
|
python
|
torch/_inductor/codegen/segmented_tree.py
| 63
|
[
"self",
"values",
"node",
"start",
"end"
] |
None
| true
| 3
| 6.88
|
pytorch/pytorch
| 96,034
|
google
| false
|
wrappersToPrimitives
|
public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
return ArrayUtils.setAll(new Class[classes.length], i -> wrapperToPrimitive(classes[i]));
}
|
Converts the specified array of wrapper Class objects to an array of its corresponding primitive Class objects.
<p>
This method invokes {@code wrapperToPrimitive()} for each element of the passed in array.
</p>
@param classes the class array to convert, may be null or empty.
@return an array which contains for each given class, the primitive class or <strong>null</strong> if the original class is not a wrapper class.
{@code null} if null input. Empty array if an empty array passed in.
@see #wrapperToPrimitive(Class)
@since 2.4
|
java
|
src/main/java/org/apache/commons/lang3/ClassUtils.java
| 1,678
|
[] | true
| 3
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getExpressionForPropertyName
|
function getExpressionForPropertyName(member: ClassElement | EnumMember, generateNameForComputedPropertyName: boolean): Expression {
const name = member.name!;
if (isPrivateIdentifier(name)) {
return factory.createIdentifier("");
}
else if (isComputedPropertyName(name)) {
return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
? factory.getGeneratedNameForNode(name)
: name.expression;
}
else if (isIdentifier(name)) {
return factory.createStringLiteral(idText(name));
}
else {
return factory.cloneNode(name);
}
}
|
Gets an expression that represents a property name (for decorated properties or enums).
For a computed property, a name is generated for the node.
@param member The member whose name should be converted into an expression.
|
typescript
|
src/compiler/transformers/legacyDecorators.ts
| 741
|
[
"member",
"generateNameForComputedPropertyName"
] | true
| 9
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
defaultIfNull
|
@Deprecated
public static <T> T defaultIfNull(final T object, final T defaultValue) {
return getIfNull(object, defaultValue);
}
|
Returns a default value if the object passed is {@code null}.
<pre>
ObjectUtils.defaultIfNull(null, null) = null
ObjectUtils.defaultIfNull(null, "") = ""
ObjectUtils.defaultIfNull(null, "zz") = "zz"
ObjectUtils.defaultIfNull("abc", *) = "abc"
ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
</pre>
@param <T> the type of the object.
@param object the {@link Object} to test, may be {@code null}.
@param defaultValue the default value to return, may be {@code null}.
@return {@code object} if it is not {@code null}, defaultValue otherwise.
@see #getIfNull(Object, Object)
@see #getIfNull(Object, Supplier)
@deprecated Use {@link #getIfNull(Object, Object)}.
|
java
|
src/main/java/org/apache/commons/lang3/ObjectUtils.java
| 537
|
[
"object",
"defaultValue"
] |
T
| true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
autocorr
|
def autocorr(self, lag: int = 1) -> float:
"""
Compute the lag-N autocorrelation.
This method computes the Pearson correlation between
the Series and its shifted self.
Parameters
----------
lag : int, default 1
Number of lags to apply before performing autocorrelation.
Returns
-------
float
The Pearson correlation between self and self.shift(lag).
See Also
--------
Series.corr : Compute the correlation between two Series.
Series.shift : Shift index by desired number of periods.
DataFrame.corr : Compute pairwise correlation of columns.
DataFrame.corrwith : Compute pairwise correlation between rows or
columns of two DataFrame objects.
Notes
-----
If the Pearson correlation is not well defined return 'NaN'.
Examples
--------
>>> s = pd.Series([0.25, 0.5, 0.2, -0.05])
>>> s.autocorr() # doctest: +ELLIPSIS
0.10355...
>>> s.autocorr(lag=2) # doctest: +ELLIPSIS
-0.99999...
If the Pearson correlation is not well defined, then 'NaN' is returned.
>>> s = pd.Series([1, 0, 0, 0])
>>> s.autocorr()
nan
"""
return self.corr(cast(Series, self.shift(lag)))
|
Compute the lag-N autocorrelation.
This method computes the Pearson correlation between
the Series and its shifted self.
Parameters
----------
lag : int, default 1
Number of lags to apply before performing autocorrelation.
Returns
-------
float
The Pearson correlation between self and self.shift(lag).
See Also
--------
Series.corr : Compute the correlation between two Series.
Series.shift : Shift index by desired number of periods.
DataFrame.corr : Compute pairwise correlation of columns.
DataFrame.corrwith : Compute pairwise correlation between rows or
columns of two DataFrame objects.
Notes
-----
If the Pearson correlation is not well defined return 'NaN'.
Examples
--------
>>> s = pd.Series([0.25, 0.5, 0.2, -0.05])
>>> s.autocorr() # doctest: +ELLIPSIS
0.10355...
>>> s.autocorr(lag=2) # doctest: +ELLIPSIS
-0.99999...
If the Pearson correlation is not well defined, then 'NaN' is returned.
>>> s = pd.Series([1, 0, 0, 0])
>>> s.autocorr()
nan
|
python
|
pandas/core/series.py
| 2,908
|
[
"self",
"lag"
] |
float
| true
| 1
| 7.12
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
fenceProducers
|
FenceProducersResult fenceProducers(Collection<String> transactionalIds,
FenceProducersOptions options);
|
Fence out all active producers that use any of the provided transactional IDs.
@param transactionalIds The IDs of the producers to fence.
@param options The options to use when fencing the producers.
@return The FenceProducersResult.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 1,776
|
[
"transactionalIds",
"options"
] |
FenceProducersResult
| true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
createKeySet
|
@Override
ImmutableSet<K> createKeySet() {
@SuppressWarnings("unchecked")
ImmutableList<K> keyList =
(ImmutableList<K>) new KeysOrValuesAsList(alternatingKeysAndValues, 0, size);
return new KeySet<K>(this, keyList);
}
|
Returns a hash table for the specified keys and values, and ensures that neither keys nor
values are null. This method may update {@code alternatingKeysAndValues} if there are duplicate
keys. If so, the return value will indicate how many entries are still valid, and will also
include a {@link Builder.DuplicateKey} in case duplicate keys are not allowed now or will not
be allowed on a later {@link Builder#buildOrThrow()} call.
@param keyOffset 1 if this is the reverse direction of a BiMap, 0 otherwise.
@return an {@code Object} that is a {@code byte[]}, {@code short[]}, or {@code int[]}, the
smallest possible to fit {@code tableSize}; or an {@code Object[]} where [0] is one of
these; [1] indicates how many element pairs in {@code alternatingKeysAndValues} are valid;
and [2] is a {@link Builder.DuplicateKey} for the first duplicate key encountered.
|
java
|
android/guava/src/com/google/common/collect/RegularImmutableMap.java
| 475
|
[] | true
| 1
| 6.88
|
google/guava
| 51,352
|
javadoc
| false
|
|
removeIgnoreCase
|
@Deprecated
public static String removeIgnoreCase(final String str, final String remove) {
return Strings.CI.remove(str, remove);
}
|
Case-insensitive removal of all occurrences of a substring from within the source string.
<p>
A {@code null} source string will return {@code null}. An empty ("") source string will return the empty string. A {@code null} remove string will return
the source string. An empty ("") remove string will return the source string.
</p>
<pre>
StringUtils.removeIgnoreCase(null, *) = null
StringUtils.removeIgnoreCase("", *) = ""
StringUtils.removeIgnoreCase(*, null) = *
StringUtils.removeIgnoreCase(*, "") = *
StringUtils.removeIgnoreCase("queued", "ue") = "qd"
StringUtils.removeIgnoreCase("queued", "zz") = "queued"
StringUtils.removeIgnoreCase("quEUed", "UE") = "qd"
StringUtils.removeIgnoreCase("queued", "zZ") = "queued"
</pre>
@param str the source String to search, may be null.
@param remove the String to search for (case-insensitive) and remove, may be null.
@return the substring with the string removed if found, {@code null} if null String input.
@since 3.5
@deprecated Use {@link Strings#remove(String, String) Strings.CI.remove(String, String)}.
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 5,893
|
[
"str",
"remove"
] |
String
| true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
equals
|
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof DefaultIntroductionAdvisor otherAdvisor &&
this.advice.equals(otherAdvisor.advice) &&
this.interfaces.equals(otherAdvisor.interfaces)));
}
|
Add the specified interface to the list of interfaces to introduce.
@param ifc the interface to introduce
|
java
|
spring-aop/src/main/java/org/springframework/aop/support/DefaultIntroductionAdvisor.java
| 148
|
[
"other"
] | true
| 4
| 6.88
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
resolveArtifactId
|
protected @Nullable String resolveArtifactId() {
if (this.artifactId != null) {
return this.artifactId;
}
if (this.output != null) {
int i = this.output.lastIndexOf('.');
return (i != -1) ? this.output.substring(0, i) : this.output;
}
return null;
}
|
Resolve the artifactId to use or {@code null} if it should not be customized.
@return the artifactId
|
java
|
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java
| 407
|
[] |
String
| true
| 4
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
ensure_dtype_objs
|
def ensure_dtype_objs(
dtype: DtypeArg | dict[Hashable, DtypeArg] | None,
) -> DtypeObj | dict[Hashable, DtypeObj] | None:
"""
Ensure we have either None, a dtype object, or a dictionary mapping to
dtype objects.
"""
if isinstance(dtype, defaultdict):
# "None" not callable [misc]
default_dtype = pandas_dtype(dtype.default_factory()) # type: ignore[misc]
dtype_converted: defaultdict = defaultdict(lambda: default_dtype)
for key in dtype.keys():
dtype_converted[key] = pandas_dtype(dtype[key])
return dtype_converted
elif isinstance(dtype, dict):
return {k: pandas_dtype(dtype[k]) for k in dtype}
elif dtype is not None:
return pandas_dtype(dtype)
return dtype
|
Ensure we have either None, a dtype object, or a dictionary mapping to
dtype objects.
|
python
|
pandas/io/parsers/c_parser_wrapper.py
| 377
|
[
"dtype"
] |
DtypeObj | dict[Hashable, DtypeObj] | None
| true
| 5
| 6
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
indexOf
|
public static int indexOf(final long[] array, final long 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,661
|
[
"array",
"valueToFind"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
listStreamsGroupOffsets
|
default ListStreamsGroupOffsetsResult listStreamsGroupOffsets(Map<String, ListStreamsGroupOffsetsSpec> groupSpecs) {
return listStreamsGroupOffsets(groupSpecs, new ListStreamsGroupOffsetsOptions());
}
|
List the streams group offsets available in the cluster for the specified groups with the default options.
<p>
This is a convenience method for
{@link #listStreamsGroupOffsets(Map, ListStreamsGroupOffsetsOptions)} with default options.
@param groupSpecs Map of streams group ids to a spec that specifies the topic partitions of the group to list offsets for.
@return The ListStreamsGroupOffsetsResult.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 974
|
[
"groupSpecs"
] |
ListStreamsGroupOffsetsResult
| true
| 1
| 6.32
|
apache/kafka
| 31,560
|
javadoc
| false
|
buildHeartbeatRequest
|
public abstract NetworkClientDelegate.UnsentRequest buildHeartbeatRequest();
|
Builds a heartbeat request using the heartbeat state to follow the protocol faithfully.
@return The heartbeat request
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManager.java
| 492
|
[] | true
| 1
| 6.64
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
addHours
|
public static Date addHours(final Date date, final int amount) {
return add(date, Calendar.HOUR_OF_DAY, amount);
}
|
Adds a number of hours to a date returning a new object.
The original {@link Date} is unchanged.
@param date the date, not null.
@param amount the amount to add, may be negative.
@return the new {@link Date} with the amount added.
@throws NullPointerException if the date is null.
|
java
|
src/main/java/org/apache/commons/lang3/time/DateUtils.java
| 250
|
[
"date",
"amount"
] |
Date
| true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
asExpression
|
function asExpression<T extends Expression | undefined>(value: string | number | boolean | T): T | StringLiteral | NumericLiteral | BooleanLiteral {
return typeof value === "string" ? createStringLiteral(value) :
typeof value === "number" ? createNumericLiteral(value) :
typeof value === "boolean" ? value ? createTrue() : createFalse() :
value;
}
|
Lifts a NodeArray containing only Statement nodes to a block.
@param nodes The NodeArray.
|
typescript
|
src/compiler/factory/nodeFactory.ts
| 7,146
|
[
"value"
] | true
| 5
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
parseSemicolon
|
function parseSemicolon(): boolean {
return tryParseSemicolon() || parseExpected(SyntaxKind.SemicolonToken);
}
|
Reports a diagnostic error for the current token being an invalid name.
@param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
@param nameDiagnostic Diagnostic to report for all other cases.
@param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
|
typescript
|
src/compiler/parser.ts
| 2,590
|
[] | true
| 2
| 6.64
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
hexRing
|
public static String[] hexRing(String h3Address) {
return h3ToStringList(hexRing(stringToH3(h3Address)));
}
|
Returns the neighbor indexes.
@param h3Address Origin index
@return All neighbor indexes from the origin
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/H3.java
| 354
|
[
"h3Address"
] | true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
syntaxError
|
public JSONException syntaxError(String message) {
return new JSONException(message + this);
}
|
Returns an exception containing the given message plus the current position and the
entire input string.
@param message the message
@return an exception
|
java
|
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONTokener.java
| 455
|
[
"message"
] |
JSONException
| true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
attach_enctype_error_multidict
|
def attach_enctype_error_multidict(request: Request) -> None:
"""Patch ``request.files.__getitem__`` to raise a descriptive error
about ``enctype=multipart/form-data``.
:param request: The request to patch.
:meta private:
"""
oldcls = request.files.__class__
class newcls(oldcls): # type: ignore[valid-type, misc]
def __getitem__(self, key: str) -> t.Any:
try:
return super().__getitem__(key)
except KeyError as e:
if key not in request.form:
raise
raise DebugFilesKeyError(request, key).with_traceback(
e.__traceback__
) from None
newcls.__name__ = oldcls.__name__
newcls.__module__ = oldcls.__module__
request.files.__class__ = newcls
|
Patch ``request.files.__getitem__`` to raise a descriptive error
about ``enctype=multipart/form-data``.
:param request: The request to patch.
:meta private:
|
python
|
src/flask/debughelpers.py
| 81
|
[
"request"
] |
None
| true
| 2
| 6.56
|
pallets/flask
| 70,946
|
sphinx
| false
|
faceIjkToCellBoundary
|
public CellBoundary faceIjkToCellBoundary(final int res) {
// adjust the center point to be in an aperture 33r substrate grid
// these should be composed for speed
this.coord.downAp3();
this.coord.downAp3r();
// if res is Class III we need to add a cw aperture 7 to get to
// icosahedral Class II
final int adjRes = adjustRes(this.coord, res);
// convert each vertex to lat/lng
// adjust the face of each vertex as appropriate and introduce
// edge-crossing vertices as needed
if (H3Index.isResolutionClassIII(res)) {
return faceIjkToCellBoundaryClassIII(adjRes);
} else {
return faceIjkToCellBoundaryClassII(adjRes);
}
}
|
Generates the cell boundary in spherical coordinates for a cell given by this
FaceIJK address at a specified resolution.
@param res The H3 resolution of the cell.
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/FaceIJK.java
| 529
|
[
"res"
] |
CellBoundary
| true
| 2
| 6.72
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
view
|
def view(self, cls=None):
"""
Return a view of the Index with the specified dtype or a new Index instance.
This method returns a view of the calling Index object if no arguments are
provided. If a dtype is specified through the `cls` argument, it attempts
to return a view of the Index with the specified dtype. Note that viewing
the Index as a different dtype reinterprets the underlying data, which can
lead to unexpected results for non-numeric or incompatible dtype conversions.
Parameters
----------
cls : data-type or ndarray sub-class, optional
Data-type descriptor of the returned view, e.g., float32 or int16.
Omitting it results in the view having the same data-type as `self`.
This argument can also be specified as an ndarray sub-class,
e.g., np.int64 or np.float32 which then specifies the type of
the returned object.
Returns
-------
Index or ndarray
A view of the Index. If `cls` is None, the returned object is an Index
view with the same dtype as the calling object. If a numeric `cls` is
specified an ndarray view with the new dtype is returned.
Raises
------
ValueError
If attempting to change to a dtype in a way that is not compatible with
the original dtype's memory layout, for example, viewing an 'int64' Index
as 'str'.
See Also
--------
Index.copy : Returns a copy of the Index.
numpy.ndarray.view : Returns a new view of array with the same data.
Examples
--------
>>> idx = pd.Index([-1, 0, 1])
>>> idx.view()
Index([-1, 0, 1], dtype='int64')
>>> idx.view(np.uint64)
array([18446744073709551615, 0, 1],
dtype=uint64)
Viewing as 'int32' or 'float32' reinterprets the memory, which may lead to
unexpected behavior:
>>> idx.view("float32")
array([ nan, nan, 0.e+00, 0.e+00, 1.e-45, 0.e+00], dtype=float32)
"""
# we need to see if we are subclassing an
# index type here
if cls is not None:
dtype = cls
if isinstance(cls, str):
dtype = pandas_dtype(cls)
if needs_i8_conversion(dtype):
idx_cls = self._dtype_to_subclass(dtype)
arr = self.array.view(dtype)
if isinstance(arr, ExtensionArray):
# here we exclude non-supported dt64/td64 dtypes
return idx_cls._simple_new(
arr, name=self.name, refs=self._references
)
return arr
result = self._data.view(cls)
else:
result = self._view()
if isinstance(result, Index):
result._id = self._id
return result
|
Return a view of the Index with the specified dtype or a new Index instance.
This method returns a view of the calling Index object if no arguments are
provided. If a dtype is specified through the `cls` argument, it attempts
to return a view of the Index with the specified dtype. Note that viewing
the Index as a different dtype reinterprets the underlying data, which can
lead to unexpected results for non-numeric or incompatible dtype conversions.
Parameters
----------
cls : data-type or ndarray sub-class, optional
Data-type descriptor of the returned view, e.g., float32 or int16.
Omitting it results in the view having the same data-type as `self`.
This argument can also be specified as an ndarray sub-class,
e.g., np.int64 or np.float32 which then specifies the type of
the returned object.
Returns
-------
Index or ndarray
A view of the Index. If `cls` is None, the returned object is an Index
view with the same dtype as the calling object. If a numeric `cls` is
specified an ndarray view with the new dtype is returned.
Raises
------
ValueError
If attempting to change to a dtype in a way that is not compatible with
the original dtype's memory layout, for example, viewing an 'int64' Index
as 'str'.
See Also
--------
Index.copy : Returns a copy of the Index.
numpy.ndarray.view : Returns a new view of array with the same data.
Examples
--------
>>> idx = pd.Index([-1, 0, 1])
>>> idx.view()
Index([-1, 0, 1], dtype='int64')
>>> idx.view(np.uint64)
array([18446744073709551615, 0, 1],
dtype=uint64)
Viewing as 'int32' or 'float32' reinterprets the memory, which may lead to
unexpected behavior:
>>> idx.view("float32")
array([ nan, nan, 0.e+00, 0.e+00, 1.e-45, 0.e+00], dtype=float32)
|
python
|
pandas/core/indexes/base.py
| 1,034
|
[
"self",
"cls"
] | false
| 7
| 7.76
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
|
processBitVector
|
public static <E extends Enum<E>> EnumSet<E> processBitVector(final Class<E> enumClass, final long value) {
return processBitVectors(checkBitVectorable(enumClass), value);
}
|
Convert a long value created by {@link EnumUtils#generateBitVector} into the set of
enum values that it represents.
<p>If you store this value, beware any changes to the enum that would affect ordinal values.</p>
@param enumClass the class of the enum we are working with, not {@code null}.
@param value the long value representation of a set of enum values.
@param <E> the type of the enumeration.
@return a set of enum values.
@throws NullPointerException if {@code enumClass} is {@code null}.
@throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values.
@since 3.0.1
|
java
|
src/main/java/org/apache/commons/lang3/EnumUtils.java
| 426
|
[
"enumClass",
"value"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
generate_numba_agg_func
|
def generate_numba_agg_func(
func: Callable[..., Scalar],
nopython: bool,
nogil: bool,
parallel: bool,
) -> Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, Any], np.ndarray]:
"""
Generate a numba jitted agg function specified by values from engine_kwargs.
1. jit the user's function
2. Return a groupby agg function with the jitted function inline
Configurations specified in engine_kwargs apply to both the user's
function _AND_ the groupby evaluation loop.
Parameters
----------
func : function
function to be applied to each group and will be JITed
nopython : bool
nopython to be passed into numba.jit
nogil : bool
nogil to be passed into numba.jit
parallel : bool
parallel to be passed into numba.jit
Returns
-------
Numba function
"""
numba_func = jit_user_function(func)
if TYPE_CHECKING:
import numba
else:
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
def group_agg(
values: np.ndarray,
index: np.ndarray,
begin: np.ndarray,
end: np.ndarray,
num_columns: int,
*args: Any,
) -> np.ndarray:
assert len(begin) == len(end)
num_groups = len(begin)
result = np.empty((num_groups, num_columns))
for i in numba.prange(num_groups):
group_index = index[begin[i] : end[i]]
for j in numba.prange(num_columns):
group = values[begin[i] : end[i], j]
result[i, j] = numba_func(group, group_index, *args)
return result
return group_agg
|
Generate a numba jitted agg function specified by values from engine_kwargs.
1. jit the user's function
2. Return a groupby agg function with the jitted function inline
Configurations specified in engine_kwargs apply to both the user's
function _AND_ the groupby evaluation loop.
Parameters
----------
func : function
function to be applied to each group and will be JITed
nopython : bool
nopython to be passed into numba.jit
nogil : bool
nogil to be passed into numba.jit
parallel : bool
parallel to be passed into numba.jit
Returns
-------
Numba function
|
python
|
pandas/core/groupby/numba_.py
| 67
|
[
"func",
"nopython",
"nogil",
"parallel"
] |
Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, Any], np.ndarray]
| true
| 5
| 6.72
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.