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
isFactoryBean
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { Boolean result = mbd.isFactoryBean; if (result == null) { Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class); result = (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); mbd.isFactoryBean = result; } return result; }
Check whether the given bean is defined as a {@link FactoryBean}. @param beanName the name of the bean @param mbd the corresponding bean definition
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
1,696
[ "beanName", "mbd" ]
true
3
6.72
spring-projects/spring-framework
59,386
javadoc
false
upperCase
public static String upperCase(final String str, final Locale locale) { if (str == null) { return null; } return str.toUpperCase(LocaleUtils.toLocale(locale)); }
Converts a String to upper case as per {@link String#toUpperCase(Locale)}. <p> A {@code null} input String returns {@code null}. </p> <pre> StringUtils.upperCase(null, Locale.ENGLISH) = null StringUtils.upperCase("", Locale.ENGLISH) = "" StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC" </pre> @param str the String to upper case, may be null. @param locale the locale that defines the case transformation rules, must not be null. @return the upper-cased String, {@code null} if null String input. @since 2.5
java
src/main/java/org/apache/commons/lang3/StringUtils.java
9,034
[ "str", "locale" ]
String
true
2
7.76
apache/commons-lang
2,896
javadoc
false
getCSVInstance
public static StrTokenizer getCSVInstance(final char[] input) { final StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; }
Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be trim whitespace from both ends (which can be overridden with the setTrimmer method). @param input the text to parse. @return a new tokenizer instance which parses Comma Separated Value strings.
java
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
149
[ "input" ]
StrTokenizer
true
1
6.72
apache/commons-lang
2,896
javadoc
false
setBcc
@Override public void setBcc(String... bcc) throws MailParseException { try { this.helper.setBcc(bcc); } catch (MessagingException ex) { throw new MailParseException(ex); } }
Return the JavaMail MimeMessage that this MimeMailMessage is based on.
java
spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMailMessage.java
146
[]
void
true
2
6.4
spring-projects/spring-framework
59,386
javadoc
false
between
@Deprecated public static <T> Range<T> between(final T fromInclusive, final T toInclusive, final Comparator<T> comparator) { return new Range<>(fromInclusive, toInclusive, comparator); }
Creates a range with the specified minimum and maximum values (both inclusive). <p>The range uses the specified {@link Comparator} to determine where values lie in the range.</p> <p>The arguments may be passed in the order (min,max) or (max,min). The getMinimum and getMaximum methods will return the correct values.</p> @param <T> the type of the elements in this range. @param fromInclusive the first value that defines the edge of the range, inclusive. @param toInclusive the second value that defines the edge of the range, inclusive. @param comparator the comparator to be used, null for natural ordering. @return the range object, not null. @throws NullPointerException when fromInclusive is null. @throws NullPointerException when toInclusive is null. @throws ClassCastException if using natural ordering and the elements are not {@link Comparable}. @deprecated Use {@link #of(Object, Object, Comparator)}.
java
src/main/java/org/apache/commons/lang3/Range.java
104
[ "fromInclusive", "toInclusive", "comparator" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
add_content_weights_lightweight
def add_content_weights_lightweight( output_dir: Path, glob_pattern: str, exclude_patterns: list[str] | None = None ) -> int: """Add data-pagefind-weight attributes using simple regex replacement. :param output_dir: Output directory :param glob_pattern: Glob pattern :param exclude_patterns: Exclude patterns :return: Number of files processed """ files_processed = 0 exclude_patterns = exclude_patterns or [] # Regex patterns to match opening tags without existing weight attribute # Use maximum valid weights (0.0-10.0 range, quadratic scale) # https://pagefind.app/docs/weighting/ # Weight of 10.0 = ~100x impact, 7.0 = ~49x impact (default h1), 5.0 = ~25x impact patterns = [ (re.compile(r"<title(?![^>]*data-pagefind-weight)"), '<title data-pagefind-weight="10.0"'), (re.compile(r"<h1(?![^>]*data-pagefind-weight)"), '<h1 data-pagefind-weight="9.0"'), ] for html_file in output_dir.glob(glob_pattern): if not html_file.is_file(): continue # Check if file matches any exclude pattern (using simple prefix matching) relative_path = html_file.relative_to(output_dir) relative_str = str(relative_path) if any(relative_str.startswith(pattern.rstrip("/*")) for pattern in exclude_patterns): continue try: content = html_file.read_text(encoding="utf-8") modified_content = content for pattern, replacement in patterns: modified_content = pattern.sub(replacement, modified_content) if modified_content != content: html_file.write_text(modified_content, encoding="utf-8") files_processed += 1 except Exception as e: logger.warning("Failed to add weights to %s: %s", html_file, e) return files_processed
Add data-pagefind-weight attributes using simple regex replacement. :param output_dir: Output directory :param glob_pattern: Glob pattern :param exclude_patterns: Exclude patterns :return: Number of files processed
python
devel-common/src/sphinx_exts/pagefind_search/builder.py
37
[ "output_dir", "glob_pattern", "exclude_patterns" ]
int
true
7
7.76
apache/airflow
43,597
sphinx
false
compareAndSet
public final boolean compareAndSet(int i, double expect, double update) { return longs.compareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); }
Atomically sets the element at position {@code i} to the given updated value if the current value is <a href="#bitEquals">bitwise equal</a> to the expected value. @param i the index @param expect the expected value @param update the new value @return true if successful. False return indicates that the actual value was not equal to the expected value.
java
android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
148
[ "i", "expect", "update" ]
true
1
6.64
google/guava
51,352
javadoc
false
equals
@Override public boolean equals(final Object obj) { return obj instanceof MutableDouble && Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value); }
Compares this object against the specified object. The result is {@code true} if and only if the argument is not {@code null} and is a {@link Double} object that represents a double that has the identical bit pattern to the bit pattern of the double represented by this object. For this purpose, two {@code double} values are considered to be the same if and only if the method {@link Double#doubleToLongBits(double)}returns the same long value when applied to each. <p> Note that in most cases, for two instances of class {@link Double},{@code d1} and {@code d2}, the value of {@code d1.equals(d2)} is {@code true} if and only if: </p> <pre> d1.doubleValue() == d2.doubleValue() </pre> <p> also has the value {@code true}. However, there are two exceptions: </p> <ul> <li>If {@code d1} and {@code d2} both represent {@code Double.NaN}, then the {@code equals} method returns {@code true}, even though {@code Double.NaN == Double.NaN} has the value {@code false}.</li> <li>If {@code d1} represents {@code +0.0} while {@code d2} represents {@code -0.0}, or vice versa, the {@code equal} test has the value {@code false}, even though {@code +0.0 == -0.0} has the value {@code true}. This allows hashtables to operate properly.</li> </ul> @param obj the object to compare with, null returns false. @return {@code true} if the objects are the same; {@code false} otherwise.
java
src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java
199
[ "obj" ]
true
2
8.08
apache/commons-lang
2,896
javadoc
false
throwFileNotFound
private void throwFileNotFound() throws FileNotFoundException { if (Optimizations.isEnabled()) { throw FILE_NOT_FOUND_EXCEPTION; } if (this.notFound != null) { throw this.notFound.get(); } throw new FileNotFoundException("JAR entry " + this.entryName + " not found in " + this.jarFile.getName()); }
The {@link URLClassLoader} connects often to check if a resource exists, we can save some object allocations by using the cached copy if we have one. @param jarFileURL the jar file to check @param entryName the entry name to check @throws FileNotFoundException on a missing entry
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrlConnection.java
324
[]
void
true
3
6.72
spring-projects/spring-boot
79,428
javadoc
false
count
def count(self, pat, flags: int = 0): r""" Count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the :class:`~pandas.Series`. Parameters ---------- pat : str Valid regular expression. flags : int, default 0, meaning no flags Flags for the `re` module. For a complete list, `see here <https://docs.python.org/3/howto/regex.html#compilation-flags>`_. Returns ------- Series or Index Same type as the calling object containing the integer counts. See Also -------- re : Standard library module for regular expressions. str.count : Standard library version, without regular expression support. Notes ----- Some characters need to be escaped when passing in `pat`. eg. ``'$'`` has a special meaning in regex and must be escaped when finding this literal character. Examples -------- >>> s = pd.Series(["A", "B", "Aaba", "Baca", np.nan, "CABA", "cat"]) >>> s.str.count("a") 0 0.0 1 0.0 2 2.0 3 2.0 4 NaN 5 0.0 6 1.0 dtype: float64 Escape ``'$'`` to find the literal dollar sign. >>> s = pd.Series(["$", "B", "Aab$", "$$ca", "C$B$", "cat"]) >>> s.str.count("\\$") 0 1 1 0 2 1 3 2 4 2 5 0 dtype: int64 This is also available on Index >>> pd.Index(["A", "A", "Aaba", "cat"]).str.count("a") Index([0, 0, 2, 1], dtype='int64') """ result = self._data.array._str_count(pat, flags) return self._wrap_result(result, returns_string=False)
r""" Count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the :class:`~pandas.Series`. Parameters ---------- pat : str Valid regular expression. flags : int, default 0, meaning no flags Flags for the `re` module. For a complete list, `see here <https://docs.python.org/3/howto/regex.html#compilation-flags>`_. Returns ------- Series or Index Same type as the calling object containing the integer counts. See Also -------- re : Standard library module for regular expressions. str.count : Standard library version, without regular expression support. Notes ----- Some characters need to be escaped when passing in `pat`. eg. ``'$'`` has a special meaning in regex and must be escaped when finding this literal character. Examples -------- >>> s = pd.Series(["A", "B", "Aaba", "Baca", np.nan, "CABA", "cat"]) >>> s.str.count("a") 0 0.0 1 0.0 2 2.0 3 2.0 4 NaN 5 0.0 6 1.0 dtype: float64 Escape ``'$'`` to find the literal dollar sign. >>> s = pd.Series(["$", "B", "Aab$", "$$ca", "C$B$", "cat"]) >>> s.str.count("\\$") 0 1 1 0 2 1 3 2 4 2 5 0 dtype: int64 This is also available on Index >>> pd.Index(["A", "A", "Aaba", "cat"]).str.count("a") Index([0, 0, 2, 1], dtype='int64')
python
pandas/core/strings/accessor.py
2,621
[ "self", "pat", "flags" ]
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
formatDecimal
private static String formatDecimal(double value, int fractionPieces) { String p = String.valueOf(value); int totalLength = p.length(); int ix = p.indexOf('.') + 1; int ex = p.indexOf('E'); // Location where the fractional values end int fractionEnd = ex == -1 ? Math.min(ix + fractionPieces, totalLength) : ex; // Determine the value of the fraction, so if it were .000 the // actual long value is 0, in which case, it can be elided. long fractionValue; try { fractionValue = Long.parseLong(p.substring(ix, fractionEnd)); } catch (NumberFormatException e) { fractionValue = 0; } if (fractionValue == 0 || fractionPieces <= 0) { // Either the part of the fraction we were asked to report is // zero, or the user requested 0 fraction pieces, so return // only the integral value if (ex != -1) { return p.substring(0, ix - 1) + p.substring(ex); } else { return p.substring(0, ix - 1); } } else { // Build up an array of fraction characters, without going past // the end of the string. This keeps track of trailing '0' chars // that should be truncated from the end to avoid getting a // string like "1.3000d" (returning "1.3d" instead) when the // value is 1.30000009 char[] fractions = new char[fractionPieces]; int fracCount = 0; int truncateCount = 0; for (int i = 0; i < fractionPieces; i++) { int position = ix + i; if (position >= fractionEnd) { // No more pieces, the fraction has ended break; } char fraction = p.charAt(position); if (fraction == '0') { truncateCount++; } else { truncateCount = 0; } fractions[i] = fraction; fracCount++; } // Generate the fraction string from the char array, truncating any trailing zeros String fractionStr = new String(fractions, 0, fracCount - truncateCount); if (ex != -1) { return p.substring(0, ix) + fractionStr + p.substring(ex); } else { return p.substring(0, ix) + fractionStr; } } }
Returns a {@link String} representation of the current {@link TimeValue}. Note that this method might produce fractional time values (ex 1.6m) which cannot be parsed by method like {@link TimeValue#parse(String, String, String, String)}. The number of fractional decimals (up to 10 maximum) are truncated to the number of fraction pieces specified. Also note that the maximum string value that will be generated is {@code 106751.9d} due to the way that values are internally converted to nanoseconds (106751.9 days is Long.MAX_VALUE nanoseconds) @param fractionPieces the number of decimal places to include
java
libs/core/src/main/java/org/elasticsearch/core/TimeValue.java
280
[ "value", "fractionPieces" ]
String
true
10
6.8
elastic/elasticsearch
75,680
javadoc
false
CONST_BYTE
public static byte CONST_BYTE(final int v) { if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); } return (byte) v; }
Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., <pre> public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127); </pre> This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. @param v the byte literal (as an int) value to return. @throws IllegalArgumentException if the value passed to v is larger than a byte, that is, smaller than -128 or larger than 127. @return the byte v, unchanged. @since 3.2
java
src/main/java/org/apache/commons/lang3/ObjectUtils.java
490
[ "v" ]
true
3
8.08
apache/commons-lang
2,896
javadoc
false
addDeduping
private void addDeduping(E element) { requireNonNull(hashTable); // safe because we check for null before calling this method int mask = hashTable.length - 1; int hash = element.hashCode(); for (int i = Hashing.smear(hash); ; i++) { i &= mask; Object previous = hashTable[i]; if (previous == null) { hashTable[i] = element; hashCode += hash; super.add(element); return; } else if (previous.equals(element)) { return; } } }
Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate elements (only the first duplicate element is added). @param elements the elements to add @return this {@code Builder} object @throws NullPointerException if {@code elements} is null or contains a null element
java
android/guava/src/com/google/common/collect/ImmutableSet.java
519
[ "element" ]
void
true
4
7.6
google/guava
51,352
javadoc
false
canReuseProjectReferences
function canReuseProjectReferences(): boolean { return !forEachProjectReference( oldProgram!.getProjectReferences(), oldProgram!.getResolvedProjectReferences(), (oldResolvedRef, parent, index) => { const newRef = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; const newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now return newResolvedRef !== undefined; } }, (oldProjectReferences, parent) => { // If array of references is changed, we cant resue old program const newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path)!.commandLine.projectReferences : projectReferences; return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); }, ); }
map with - SourceFile if present - false if sourceFile missing for source of project reference redirect - undefined otherwise
typescript
src/compiler/program.ts
2,317
[]
true
7
6.24
microsoft/TypeScript
107,154
jsdoc
false
initMessageSource
protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms && hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
Initialize the {@link MessageSource}. <p>Uses parent's {@code MessageSource} if none defined in this context. @see #MESSAGE_SOURCE_BEAN_NAME
java
spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
819
[]
void
true
7
6.4
spring-projects/spring-framework
59,386
javadoc
false
poolSize
public ThreadPoolTaskSchedulerBuilder poolSize(int poolSize) { return new ThreadPoolTaskSchedulerBuilder(poolSize, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, this.customizers); }
Set the maximum allowed number of threads. @param poolSize the pool size to set @return a new builder instance
java
core/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java
79
[ "poolSize" ]
ThreadPoolTaskSchedulerBuilder
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
sendFetchesInternal
private List<RequestFuture<ClientResponse>> sendFetchesInternal(Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests, ResponseHandler<ClientResponse> successHandler, ResponseHandler<Throwable> errorHandler) { final List<RequestFuture<ClientResponse>> requestFutures = new ArrayList<>(); for (Map.Entry<Node, FetchSessionHandler.FetchRequestData> entry : fetchRequests.entrySet()) { final Node fetchTarget = entry.getKey(); final FetchSessionHandler.FetchRequestData data = entry.getValue(); final FetchRequest.Builder request = createFetchRequest(fetchTarget, data); final RequestFuture<ClientResponse> responseFuture = client.send(fetchTarget, request); responseFuture.addListener(new RequestFutureListener<>() { @Override public void onSuccess(ClientResponse resp) { successHandler.handle(fetchTarget, data, resp); } @Override public void onFailure(RuntimeException e) { errorHandler.handle(fetchTarget, data, e); } }); requestFutures.add(responseFuture); } return requestFutures; }
Creates the {@link FetchRequest.Builder fetch request}, {@link NetworkClient#send(ClientRequest, long) enqueues/sends it, and adds the {@link RequestFuture callback} for the response. @param fetchRequests {@link Map} of {@link Node nodes} to their {@link FetchSessionHandler.FetchRequestData request data} @param successHandler {@link ResponseHandler Handler for successful responses} @param errorHandler {@link ResponseHandler Handler for failure responses} @return List of {@link RequestFuture callbacks}
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
184
[ "fetchRequests", "successHandler", "errorHandler" ]
true
1
6.24
apache/kafka
31,560
javadoc
false
template_global
def template_global( self, name: T_template_global | str | None = None ) -> T_template_global | t.Callable[[T_template_global], T_template_global]: """Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. .. code-block:: python @app.template_global def double(n): return 2 * n The :meth:`add_template_global` method may be used to register a function later rather than decorating. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10 """ if callable(name): self.add_template_global(name) return name def decorator(f: T_template_global) -> T_template_global: self.add_template_global(f, name=name) return f return decorator
Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. .. code-block:: python @app.template_global def double(n): return 2 * n The :meth:`add_template_global` method may be used to register a function later rather than decorating. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10
python
src/flask/sansio/app.py
776
[ "self", "name" ]
T_template_global | t.Callable[[T_template_global], T_template_global]
true
2
6.72
pallets/flask
70,946
sphinx
false
configureLogLevel
private void configureLogLevel(String name, LogLevel level, BiConsumer<String, @Nullable LogLevel> configurer) { if (this.loggerGroups != null) { LoggerGroup group = this.loggerGroups.get(name); if (group != null && group.hasMembers()) { group.configureLogLevel(level, configurer); return; } } configurer.accept(name, level); }
Set logging levels based on relevant {@link Environment} properties. @param system the logging system @param environment the environment @since 2.2.0
java
core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java
402
[ "name", "level", "configurer" ]
void
true
4
6.56
spring-projects/spring-boot
79,428
javadoc
false
get_dep_statuses
def get_dep_statuses( self, ti: TaskInstance, session: Session, dep_context: DepContext | None = None, ) -> Iterator[TIDepStatus]: """ Wrap around the private _get_dep_statuses method. Contains some global checks for all dependencies. :param ti: the task instance to get the dependency status for :param session: database session :param dep_context: the context for which this dependency should be evaluated for """ cxt = DepContext() if dep_context is None else dep_context if self.IGNORABLE and cxt.ignore_all_deps: yield self._passing_status(reason="Context specified all dependencies should be ignored.") return if self.IS_TASK_DEP and cxt.ignore_task_deps: yield self._passing_status(reason="Context specified all task dependencies should be ignored.") return yield from self._get_dep_statuses(ti, session, cxt)
Wrap around the private _get_dep_statuses method. Contains some global checks for all dependencies. :param ti: the task instance to get the dependency status for :param session: database session :param dep_context: the context for which this dependency should be evaluated for
python
airflow-core/src/airflow/ti_deps/deps/base_ti_dep.py
91
[ "self", "ti", "session", "dep_context" ]
Iterator[TIDepStatus]
true
6
6.88
apache/airflow
43,597
sphinx
false
exists
async function exists(filename: string): Promise<boolean> { try { if ((await fs.promises.stat(filename)).isFile()) { return true; } } catch (ex) { // In case requesting the file statistics fail. // we assume it does not exist. return false; } return false; }
Check if the given filename is a file. If returns false in case the file does not exist or the file stats cannot be accessed/queried or it is no file at all. @param filename the filename to the checked @returns true in case the file exists, in any other case false.
typescript
extensions/gulp/src/main.ts
26
[ "filename" ]
true
3
8.08
microsoft/vscode
179,840
jsdoc
true
appendDisplayNames
private static Map<String, Integer> appendDisplayNames(final Calendar calendar, final Locale locale, final int field, final StringBuilder regex) { Objects.requireNonNull(calendar, "calendar"); final Map<String, Integer> values = new HashMap<>(); final Locale actualLocale = LocaleUtils.toLocale(locale); final Map<String, Integer> displayNames = calendar.getDisplayNames(field, Calendar.ALL_STYLES, actualLocale); final TreeSet<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); displayNames.forEach((k, v) -> { final String keyLc = k.toLowerCase(actualLocale); if (sorted.add(keyLc)) { values.put(keyLc, v); } }); sorted.forEach(symbol -> simpleQuote(regex, symbol).append('|')); return values; }
Gets the short and long values displayed for a field @param calendar The calendar to obtain the short and long values @param locale The locale of display names @param field The field of interest @param regex The regular expression to build @return The map of string display names to field values
java
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
724
[ "calendar", "locale", "field", "regex" ]
true
2
7.12
apache/commons-lang
2,896
javadoc
false
searchsorted
def searchsorted( arr: ArrayLike, value: NumpyValueArrayLike | ExtensionArray, side: Literal["left", "right"] = "left", sorter: NumpySorter | None = None, ) -> npt.NDArray[np.intp] | np.intp: """ Find indices where elements should be inserted to maintain order. Find the indices into a sorted array `arr` (a) such that, if the corresponding elements in `value` were inserted before the indices, the order of `arr` would be preserved. Assuming that `arr` is sorted: ====== ================================ `side` returned index `i` satisfies ====== ================================ left ``arr[i-1] < value <= self[i]`` right ``arr[i-1] <= value < self[i]`` ====== ================================ Parameters ---------- arr: np.ndarray, ExtensionArray, Series Input array. If `sorter` is None, then it must be sorted in ascending order, otherwise `sorter` must be an array of indices that sort it. value : array-like or scalar Values to insert into `arr`. side : {'left', 'right'}, optional If 'left', the index of the first suitable location found is given. If 'right', return the last such index. If there is no suitable index, return either 0 or N (where N is the length of `self`). sorter : 1-D array-like, optional Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. Returns ------- array of ints or int If value is array-like, array of insertion points. If value is scalar, a single integer. See Also -------- numpy.searchsorted : Similar method from NumPy. """ if sorter is not None: sorter = ensure_platform_int(sorter) if ( isinstance(arr, np.ndarray) and arr.dtype.kind in "iu" and (is_integer(value) or is_integer_dtype(value)) ): # if `arr` and `value` have different dtypes, `arr` would be # recast by numpy, causing a slow search. # Before searching below, we therefore try to give `value` the # same dtype as `arr`, while guarding against integer overflows. iinfo = np.iinfo(arr.dtype.type) value_arr = np.array([value]) if is_integer(value) else np.array(value) if (value_arr >= iinfo.min).all() and (value_arr <= iinfo.max).all(): # value within bounds, so no overflow, so can convert value dtype # to dtype of arr dtype = arr.dtype else: dtype = value_arr.dtype if is_integer(value): # We know that value is int value = cast(int, dtype.type(value)) else: value = pd_array(cast(ArrayLike, value), dtype=dtype) else: # E.g. if `arr` is an array with dtype='datetime64[ns]' # and `value` is a pd.Timestamp, we may need to convert value arr = ensure_wrapped_if_datetimelike(arr) # Argument 1 to "searchsorted" of "ndarray" has incompatible type # "Union[NumpyValueArrayLike, ExtensionArray]"; expected "NumpyValueArrayLike" return arr.searchsorted(value, side=side, sorter=sorter) # type: ignore[arg-type]
Find indices where elements should be inserted to maintain order. Find the indices into a sorted array `arr` (a) such that, if the corresponding elements in `value` were inserted before the indices, the order of `arr` would be preserved. Assuming that `arr` is sorted: ====== ================================ `side` returned index `i` satisfies ====== ================================ left ``arr[i-1] < value <= self[i]`` right ``arr[i-1] <= value < self[i]`` ====== ================================ Parameters ---------- arr: np.ndarray, ExtensionArray, Series Input array. If `sorter` is None, then it must be sorted in ascending order, otherwise `sorter` must be an array of indices that sort it. value : array-like or scalar Values to insert into `arr`. side : {'left', 'right'}, optional If 'left', the index of the first suitable location found is given. If 'right', return the last such index. If there is no suitable index, return either 0 or N (where N is the length of `self`). sorter : 1-D array-like, optional Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. Returns ------- array of ints or int If value is array-like, array of insertion points. If value is scalar, a single integer. See Also -------- numpy.searchsorted : Similar method from NumPy.
python
pandas/core/algorithms.py
1,243
[ "arr", "value", "side", "sorter" ]
npt.NDArray[np.intp] | np.intp
true
13
6.8
pandas-dev/pandas
47,362
numpy
false
withFilter
public StandardStackTracePrinter withFilter(Predicate<Throwable> predicate) { Assert.notNull(predicate, "'predicate' must not be null"); return new StandardStackTracePrinter(this.options, this.maximumLength, this.lineSeparator, this.filter.and(predicate), this.frameFilter, this.formatter, this.frameFormatter, this.frameHasher); }
Return a new {@link StandardStackTracePrinter} from this one that will only include throwables (excluding caused and suppressed) that match the given predicate. @param predicate the predicate used to filter the throwable @return a new {@link StandardStackTracePrinter} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/StandardStackTracePrinter.java
201
[ "predicate" ]
StandardStackTracePrinter
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
infer_automated_data_interval
def infer_automated_data_interval(timetable: Timetable, logical_date: datetime) -> DataInterval: """ Infer a data interval for a run against this DAG. This method is used to bridge runs created prior to AIP-39 implementation, which do not have an explicit data interval. Therefore, this method only considers ``schedule_interval`` values valid prior to Airflow 2.2. DO NOT call this method if there is a known data interval. :meta private: """ timetable_type = type(timetable) if issubclass(timetable_type, (NullTimetable, OnceTimetable, AssetTriggeredTimetable)): return DataInterval.exact(timezone.coerce_datetime(logical_date)) start = timezone.coerce_datetime(logical_date) if issubclass(timetable_type, CronDataIntervalTimetable): end = cast("CronDataIntervalTimetable", timetable)._get_next(start) elif issubclass(timetable_type, DeltaDataIntervalTimetable): end = cast("DeltaDataIntervalTimetable", timetable)._get_next(start) # Contributors: When the exception below is raised, you might want to # add an 'elif' block here to handle custom timetables. Stop! The bug # you're looking for is instead at when the DAG run (represented by # logical_date) was created. See GH-31969 for an example: # * Wrong fix: GH-32074 (modifies this function). # * Correct fix: GH-32118 (modifies the DAG run creation code). else: raise ValueError(f"Not a valid timetable: {timetable!r}") return DataInterval(start, end)
Infer a data interval for a run against this DAG. This method is used to bridge runs created prior to AIP-39 implementation, which do not have an explicit data interval. Therefore, this method only considers ``schedule_interval`` values valid prior to Airflow 2.2. DO NOT call this method if there is a known data interval. :meta private:
python
airflow-core/src/airflow/models/dag.py
99
[ "timetable", "logical_date" ]
DataInterval
true
5
6
apache/airflow
43,597
unknown
false
initializeValueParameterDetail
private static @Nullable CacheParameterDetail initializeValueParameterDetail( Method method, List<CacheParameterDetail> allParameters) { CacheParameterDetail result = null; for (CacheParameterDetail parameter : allParameters) { if (parameter.isValue()) { if (result == null) { result = parameter; } else { throw new IllegalArgumentException("More than one @CacheValue found on " + method); } } } return result; }
Return the {@link CacheInvocationParameter} for the parameter holding the value to cache. <p>The method arguments must match the signature of the related method invocation @param values the parameters value for a particular invocation @return the {@link CacheInvocationParameter} instance for the value parameter
java
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/CachePutOperation.java
95
[ "method", "allParameters" ]
CacheParameterDetail
true
3
7.28
spring-projects/spring-framework
59,386
javadoc
false
as_series
def as_series(alist, trim=True): """ Return argument as a list of 1-d arrays. The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array. Parameters ---------- alist : array_like A 1- or 2-d array_like trim : boolean, optional When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact. Returns ------- [a1, a2,...] : list of 1-D arrays A copy of the input data as a list of 1-d arrays. Raises ------ ValueError Raised when `as_series` cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty. Examples -------- >>> import numpy as np >>> from numpy.polynomial import polyutils as pu >>> a = np.arange(4) >>> pu.as_series(a) [array([0.]), array([1.]), array([2.]), array([3.])] >>> b = np.arange(6).reshape((2,3)) >>> pu.as_series(b) [array([0., 1., 2.]), array([3., 4., 5.])] >>> pu.as_series((1, np.arange(3), np.arange(2, dtype=np.float16))) [array([1.]), array([0., 1., 2.]), array([0., 1.])] >>> pu.as_series([2, [1.1, 0.]]) [array([2.]), array([1.1])] >>> pu.as_series([2, [1.1, 0.]], trim=False) [array([2.]), array([1.1, 0. ])] """ arrays = [np.array(a, ndmin=1, copy=None) for a in alist] for a in arrays: if a.size == 0: raise ValueError("Coefficient array is empty") if a.ndim != 1: raise ValueError("Coefficient array is not 1-d") if trim: arrays = [trimseq(a) for a in arrays] try: dtype = np.common_type(*arrays) except Exception as e: object_dtype = np.dtypes.ObjectDType() has_one_object_type = False ret = [] for a in arrays: if a.dtype != object_dtype: tmp = np.empty(len(a), dtype=object_dtype) tmp[:] = a[:] ret.append(tmp) else: has_one_object_type = True ret.append(a.copy()) if not has_one_object_type: raise ValueError("Coefficient arrays have no common type") from e else: ret = [np.array(a, copy=True, dtype=dtype) for a in arrays] return ret
Return argument as a list of 1-d arrays. The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array. Parameters ---------- alist : array_like A 1- or 2-d array_like trim : boolean, optional When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact. Returns ------- [a1, a2,...] : list of 1-D arrays A copy of the input data as a list of 1-d arrays. Raises ------ ValueError Raised when `as_series` cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty. Examples -------- >>> import numpy as np >>> from numpy.polynomial import polyutils as pu >>> a = np.arange(4) >>> pu.as_series(a) [array([0.]), array([1.]), array([2.]), array([3.])] >>> b = np.arange(6).reshape((2,3)) >>> pu.as_series(b) [array([0., 1., 2.]), array([3., 4., 5.])] >>> pu.as_series((1, np.arange(3), np.arange(2, dtype=np.float16))) [array([1.]), array([0., 1., 2.]), array([0., 1.])] >>> pu.as_series([2, [1.1, 0.]]) [array([2.]), array([1.1])] >>> pu.as_series([2, [1.1, 0.]], trim=False) [array([2.]), array([1.1, 0. ])]
python
numpy/polynomial/polyutils.py
63
[ "alist", "trim" ]
false
10
7.6
numpy/numpy
31,054
numpy
false
load
private Configuration load(ResourceLoader resourceLoader, String location) throws IOException { ConfigurationFactory configurationFactory = ConfigurationFactory.getInstance(); Resource resource = resourceLoader.getResource(location); Configuration configuration = configurationFactory.getConfiguration(getLoggerContext(), null, resource.getURI(), getClassLoader()); // The error handling in Log4j Core 2.25.x is not consistent, some loading and // parsing errors result in a null configuration, others in an exception. if (configuration == null) { throw new ConfigurationException("Could not load Log4j Core configuration from " + location); } return configuration; }
Return the configuration location. The result may be: <ul> <li>{@code null}: if DefaultConfiguration is used (no explicit config loaded)</li> <li>A file path: if provided explicitly by the user</li> <li>A URI: if loaded from the classpath default or a custom location</li> </ul> @param configuration the source configuration @return the config location or {@code null}
java
core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java
306
[ "resourceLoader", "location" ]
Configuration
true
2
7.44
spring-projects/spring-boot
79,428
javadoc
false
close
@Override public void close() throws IOException { try { IOUtils.close(dataLifecycleInitialisationService.get()); } catch (IOException e) { throw new ElasticsearchException("unable to close the data stream lifecycle service", e); } }
Returns the look ahead time and lowers it when it to 2 hours if it is configured to more than 2 hours.
java
modules/data-streams/src/main/java/org/elasticsearch/datastreams/DataStreamsPlugin.java
304
[]
void
true
2
7.04
elastic/elasticsearch
75,680
javadoc
false
handle_failure
def handle_failure( self, error: None | str, test_mode: bool | None = None, session: Session = NEW_SESSION, ) -> None: """ Handle Failure for a task instance. :param error: if specified, log the specific exception if thrown :param test_mode: doesn't record success or failure in the DB if True :param session: SQLAlchemy ORM Session """ if TYPE_CHECKING: assert self.task assert self.task.dag try: fail_fast = self.task.dag.fail_fast except Exception: fail_fast = False if test_mode is None: test_mode = self.test_mode ti = TaskInstance.fetch_handle_failure_context( ti=self, error=error, test_mode=test_mode, session=session, fail_fast=fail_fast, ) _log_state(task_instance=self) if not test_mode: TaskInstance.save_to_db(ti, session)
Handle Failure for a task instance. :param error: if specified, log the specific exception if thrown :param test_mode: doesn't record success or failure in the DB if True :param session: SQLAlchemy ORM Session
python
airflow-core/src/airflow/models/taskinstance.py
1,593
[ "self", "error", "test_mode", "session" ]
None
true
4
6.88
apache/airflow
43,597
sphinx
false
matrix_power
def matrix_power(a, n): """ Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``. .. note:: Stacks of object matrices are not currently supported. Parameters ---------- a : (..., M, M) array_like Matrix to be "powered". n : int The exponent can be any integer or long integer, positive, negative, or zero. Returns ------- a**n : (..., M, M) ndarray or matrix object The return value is the same shape and type as `M`; if the exponent is positive or zero then the type of the elements is the same as those of `M`. If the exponent is negative the elements are floating-point. Raises ------ LinAlgError For matrices that are not square or that (for negative powers) cannot be inverted numerically. Examples -------- >>> import numpy as np >>> from numpy.linalg import matrix_power >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit >>> matrix_power(i, 3) # should = -i array([[ 0, -1], [ 1, 0]]) >>> matrix_power(i, 0) array([[1, 0], [0, 1]]) >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements array([[ 0., 1.], [-1., 0.]]) Somewhat more sophisticated example >>> q = np.zeros((4, 4)) >>> q[0:2, 0:2] = -i >>> q[2:4, 2:4] = i >>> q # one of the three quaternion units not equal to 1 array([[ 0., -1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.], [ 0., 0., -1., 0.]]) >>> matrix_power(q, 2) # = -np.eye(4) array([[-1., 0., 0., 0.], [ 0., -1., 0., 0.], [ 0., 0., -1., 0.], [ 0., 0., 0., -1.]]) """ a = asanyarray(a) _assert_stacked_square(a) try: n = operator.index(n) except TypeError as e: raise TypeError("exponent must be an integer") from e # Fall back on dot for object arrays. Object arrays are not supported by # the current implementation of matmul using einsum if a.dtype != object: fmatmul = matmul elif a.ndim == 2: fmatmul = dot else: raise NotImplementedError( "matrix_power not supported for stacks of object arrays") if n == 0: a = empty_like(a) a[...] = eye(a.shape[-2], dtype=a.dtype) return a elif n < 0: a = inv(a) n = abs(n) # short-cuts. if n == 1: return a elif n == 2: return fmatmul(a, a) elif n == 3: return fmatmul(fmatmul(a, a), a) # Use binary decomposition to reduce the number of matrix multiplications. # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to # increasing powers of 2, and multiply into the result as needed. z = result = None while n > 0: z = a if z is None else fmatmul(z, z) n, bit = divmod(n, 2) if bit: result = z if result is None else fmatmul(result, z) return result
Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``. .. note:: Stacks of object matrices are not currently supported. Parameters ---------- a : (..., M, M) array_like Matrix to be "powered". n : int The exponent can be any integer or long integer, positive, negative, or zero. Returns ------- a**n : (..., M, M) ndarray or matrix object The return value is the same shape and type as `M`; if the exponent is positive or zero then the type of the elements is the same as those of `M`. If the exponent is negative the elements are floating-point. Raises ------ LinAlgError For matrices that are not square or that (for negative powers) cannot be inverted numerically. Examples -------- >>> import numpy as np >>> from numpy.linalg import matrix_power >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit >>> matrix_power(i, 3) # should = -i array([[ 0, -1], [ 1, 0]]) >>> matrix_power(i, 0) array([[1, 0], [0, 1]]) >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements array([[ 0., 1.], [-1., 0.]]) Somewhat more sophisticated example >>> q = np.zeros((4, 4)) >>> q[0:2, 0:2] = -i >>> q[2:4, 2:4] = i >>> q # one of the three quaternion units not equal to 1 array([[ 0., -1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.], [ 0., 0., -1., 0.]]) >>> matrix_power(q, 2) # = -np.eye(4) array([[-1., 0., 0., 0.], [ 0., -1., 0., 0.], [ 0., 0., -1., 0.], [ 0., 0., 0., -1.]])
python
numpy/linalg/_linalg.py
657
[ "a", "n" ]
false
13
7.76
numpy/numpy
31,054
numpy
false
insertWrapDetails
function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); }
Inserts wrapper `details` in a comment at the top of the `source` body. @private @param {string} source The source to modify. @returns {Array} details The details to insert. @returns {string} Returns the modified source.
javascript
lodash.js
6,332
[ "source", "details" ]
false
4
6.24
lodash/lodash
61,490
jsdoc
false
equals
public abstract boolean equals(String str1, String str2);
Compares two CharSequences, returning {@code true} if they represent equal sequences of characters. <p> {@code null}s are handled without exceptions. Two {@code null} references are considered to be equal. </p> <p> Case-sensitive examples </p> <pre> Strings.CS.equals(null, null) = true Strings.CS.equals(null, "abc") = false Strings.CS.equals("abc", null) = false Strings.CS.equals("abc", "abc") = true Strings.CS.equals("abc", "ABC") = false </pre> <p> Case-insensitive examples </p> <pre> Strings.CI.equals(null, null) = true Strings.CI.equals(null, "abc") = false Strings.CI.equals("abc", null) = false Strings.CI.equals("abc", "abc") = true Strings.CI.equals("abc", "ABC") = true </pre> @param str1 the first CharSequence, may be {@code null} @param str2 the second CharSequence, may be {@code null} @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} @see Object#equals(Object) @see String#compareTo(String) @see String#equalsIgnoreCase(String)
java
src/main/java/org/apache/commons/lang3/Strings.java
721
[ "str1", "str2" ]
true
1
6.16
apache/commons-lang
2,896
javadoc
false
modelActionsLayer
function modelActionsLayer(client: Client, dmmfModelName: string): CompositeProxyLayer<string> { // we use the javascript model name for display purposes const jsModelName = dmmfToJSModelName(dmmfModelName) const ownKeys = Object.keys(DMMF.ModelAction).concat('count') return { getKeys() { return ownKeys }, getPropertyValue(key) { const dmmfActionName = key as DMMF.ModelAction // we return a function as the model action that we want to expose // it takes user args and executes the request in a Prisma Promise const action = (paramOverrides: O.Optional<InternalRequestParams>) => (userArgs?: UserArgs) => { const callSite = getCallSite(client._errorFormat) // used for showing better errors return client._createPrismaPromise( (transaction) => { const params: InternalRequestParams = { // data and its dataPath for nested results args: userArgs, dataPath: [], // action name and its related model action: dmmfActionName, model: dmmfModelName, // method name for display only clientMethod: `${jsModelName}.${key}`, jsModelName, // transaction information transaction, // stack trace callsite: callSite, } return client._request({ ...params, ...paramOverrides }) }, { action: dmmfActionName, args: userArgs, model: dmmfModelName, }, ) } // we give the control over action for building the fluent api if ((fluentProps as readonly string[]).includes(dmmfActionName)) { return applyFluent(client, dmmfModelName, action) } // we handle the edge case of aggregates that need extra steps if (isValidAggregateName(key)) { return applyAggregates(client, key, action) } return action({}) // and by default, don't override any params }, } }
Dynamically creates a model interface via a proxy. @param client to trigger the request execution @param dmmfModelName the dmmf name of the model @returns
typescript
packages/client/src/runtime/core/model/applyModel.ts
63
[ "client", "dmmfModelName" ]
true
3
7.68
prisma/prisma
44,834
jsdoc
false
indexOf
public static int indexOf(final short[] array, final short 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,750
[ "array", "valueToFind" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
fit
public T fit(final T element) { // Comparable API says throw NPE on null Objects.requireNonNull(element, "element"); if (isAfter(element)) { return minimum; } if (isBefore(element)) { return maximum; } return element; }
Fits the given element into this range by returning the given element or, if out of bounds, the range minimum if below, or the range maximum if above. <pre>{@code Range<Integer> range = Range.between(16, 64); range.fit(-9) --> 16 range.fit(0) --> 16 range.fit(15) --> 16 range.fit(16) --> 16 range.fit(17) --> 17 ... range.fit(63) --> 63 range.fit(64) --> 64 range.fit(99) --> 64 }</pre> @param element the element to check for, not null. @return the minimum, the element, or the maximum depending on the element's location relative to the range. @throws NullPointerException if {@code element} is {@code null}. @since 3.10
java
src/main/java/org/apache/commons/lang3/Range.java
340
[ "element" ]
T
true
3
8.08
apache/commons-lang
2,896
javadoc
false
getShortClassName
public static String getShortClassName(String className) { if (StringUtils.isEmpty(className)) { return StringUtils.EMPTY; } final StringBuilder arrayPrefix = new StringBuilder(); // Handle array encoding if (className.startsWith("[")) { while (className.charAt(0) == '[') { className = className.substring(1); arrayPrefix.append("[]"); } // Strip Object type encoding if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { className = className.substring(1, className.length() - 1); } if (REVERSE_ABBREVIATION_MAP.containsKey(className)) { className = REVERSE_ABBREVIATION_MAP.get(className); } } final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); final int innerIdx = className.indexOf(INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1); String out = className.substring(lastDotIdx + 1); if (innerIdx != -1) { out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR); } return out + arrayPrefix; }
Gets the class name minus the package name from a String. <p> The string passed in is assumed to be a class name - it is not checked. The string has to be formatted the way as the JDK method {@code Class.getName()} returns it, and not the usual way as we write it, for example in import statements, or as it is formatted by {@code Class.getCanonicalName()}. </p> <p> The difference is significant only in case of classes that are inner classes of some other classes. In this case the separator between the outer and inner class (possibly on multiple hierarchy level) has to be {@code $} (dollar sign) and not {@code .} (dot), as it is returned by {@code Class.getName()} </p> <p> Note that this method is called from the {@link #getShortClassName(Class)} method using the string returned by {@code Class.getName()}. </p> <p> Note that this method differs from {@link #getSimpleName(Class)} in that this will return, for example {@code "Map.Entry"} whilst the {@link Class} variant will simply return {@code "Entry"}. In this example the argument {@code className} is the string {@code java.util.Map$Entry} (note the {@code $} sign). </p> @param className the className to get the short name for. It has to be formatted as returned by {@code Class.getName()} and not {@code Class.getCanonicalName()}. @return the class name of the class without the package name or an empty string. If the class is an inner class then value contains the outer class or classes and the separator is replaced to be {@code .} (dot) character.
java
src/main/java/org/apache/commons/lang3/ClassUtils.java
1,077
[ "className" ]
String
true
9
8.24
apache/commons-lang
2,896
javadoc
false
getProxy
public static Object getProxy(TargetSource targetSource) { if (targetSource.getTargetClass() == null) { throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class"); } ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTargetSource(targetSource); proxyFactory.setProxyTargetClass(true); return proxyFactory.getProxy(); }
Create a proxy for the specified {@code TargetSource} that extends the target class of the {@code TargetSource}. @param targetSource the TargetSource that the proxy should invoke @return the proxy object
java
spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java
159
[ "targetSource" ]
Object
true
2
7.76
spring-projects/spring-framework
59,386
javadoc
false
cov
def cov(m: Array, /, *, xp: ModuleType | None = None) -> Array: """ Estimate a covariance matrix. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i`. This provides a subset of the functionality of ``numpy.cov``. Parameters ---------- m : array A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. xp : array_namespace, optional The standard-compatible namespace for `m`. Default: infer. Returns ------- array The covariance matrix of the variables. Examples -------- >>> import array_api_strict as xp >>> import array_api_extra as xpx Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions: >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T >>> x Array([[0, 1, 2], [2, 1, 0]], dtype=array_api_strict.int64) Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly: >>> xpx.cov(x, xp=xp) Array([[ 1., -1.], [-1., 1.]], dtype=array_api_strict.float64) Note that element :math:`C_{0,1}`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative. Further, note how `x` and `y` are combined: >>> x = xp.asarray([-2.1, -1, 4.3]) >>> y = xp.asarray([3, 1.1, 0.12]) >>> X = xp.stack((x, y), axis=0) >>> xpx.cov(X, xp=xp) Array([[11.71 , -4.286 ], [-4.286 , 2.14413333]], dtype=array_api_strict.float64) >>> xpx.cov(x, xp=xp) Array(11.71, dtype=array_api_strict.float64) >>> xpx.cov(y, xp=xp) Array(2.14413333, dtype=array_api_strict.float64) """ if xp is None: xp = array_namespace(m) m = xp.asarray(m, copy=True) dtype = ( xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64) ) m = atleast_nd(m, ndim=2, xp=xp) m = xp.astype(m, dtype) avg = _helpers.mean(m, axis=1, xp=xp) m_shape = eager_shape(m) fact = m_shape[1] - 1 if fact <= 0: warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2) fact = 0 m -= avg[:, None] m_transpose = m.T if xp.isdtype(m_transpose.dtype, "complex floating"): m_transpose = xp.conj(m_transpose) c = m @ m_transpose c /= fact axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1) return xp.squeeze(c, axis=axes)
Estimate a covariance matrix. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i`. This provides a subset of the functionality of ``numpy.cov``. Parameters ---------- m : array A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. xp : array_namespace, optional The standard-compatible namespace for `m`. Default: infer. Returns ------- array The covariance matrix of the variables. Examples -------- >>> import array_api_strict as xp >>> import array_api_extra as xpx Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions: >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T >>> x Array([[0, 1, 2], [2, 1, 0]], dtype=array_api_strict.int64) Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly: >>> xpx.cov(x, xp=xp) Array([[ 1., -1.], [-1., 1.]], dtype=array_api_strict.float64) Note that element :math:`C_{0,1}`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative. Further, note how `x` and `y` are combined: >>> x = xp.asarray([-2.1, -1, 4.3]) >>> y = xp.asarray([3, 1.1, 0.12]) >>> X = xp.stack((x, y), axis=0) >>> xpx.cov(X, xp=xp) Array([[11.71 , -4.286 ], [-4.286 , 2.14413333]], dtype=array_api_strict.float64) >>> xpx.cov(x, xp=xp) Array(11.71, dtype=array_api_strict.float64) >>> xpx.cov(y, xp=xp) Array(2.14413333, dtype=array_api_strict.float64)
python
sklearn/externals/array_api_extra/_lib/_funcs.py
284
[ "m", "xp" ]
Array
true
5
7.92
scikit-learn/scikit-learn
64,340
numpy
false
withAlias
default PemSslStore withAlias(@Nullable String alias) { List<X509Certificate> certificates = certificates(); Assert.notNull(certificates, "'certificates' must not be null"); return of(type(), alias, password(), certificates, privateKey()); }
Return a new {@link PemSslStore} instance with a new alias. @param alias the new alias @return a new {@link PemSslStore} instance
java
core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/PemSslStore.java
80
[ "alias" ]
PemSslStore
true
1
6.72
spring-projects/spring-boot
79,428
javadoc
false
assertNotReadOnlySystemAttributesMap
private void assertNotReadOnlySystemAttributesMap(Map<?, ?> map) { try { map.size(); } catch (UnsupportedOperationException ex) { throw new IllegalArgumentException("Security restricted maps are not supported", ex); } }
Add an individual entry. @param name the name @param value the value
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java
105
[ "map" ]
void
true
2
7.04
spring-projects/spring-boot
79,428
javadoc
false
computeInPlace
public double computeInPlace(double... dataset) { checkArgument(dataset.length > 0, "Cannot calculate quantiles of an empty dataset"); if (containsNaN(dataset)) { return NaN; } // Calculate the quotient and remainder in the integer division x = k * (N-1) / q, i.e. // index * (dataset.length - 1) / scale. If there is no remainder, we can just find the value // whose index in the sorted dataset equals the quotient; if there is a remainder, we // interpolate between that and the next value. // Since index and (dataset.length - 1) are non-negative ints, their product can be expressed // as a long, without risk of overflow: long numerator = (long) index * (dataset.length - 1); // Since scale is a positive int, index is in [0, scale], and (dataset.length - 1) is a // non-negative int, we can do long-arithmetic on index * (dataset.length - 1) / scale to get // a rounded ratio and a remainder which can be expressed as ints, without risk of overflow: int quotient = (int) LongMath.divide(numerator, scale, RoundingMode.DOWN); int remainder = (int) (numerator - (long) quotient * scale); selectInPlace(quotient, dataset, 0, dataset.length - 1); if (remainder == 0) { return dataset[quotient]; } else { selectInPlace(quotient + 1, dataset, quotient + 1, dataset.length - 1); return interpolate(dataset[quotient], dataset[quotient + 1], remainder, scale); } }
Computes the quantile value of the given dataset, performing the computation in-place. @param dataset the dataset to do the calculation on, which must be non-empty, and which will be arbitrarily reordered by this method call @return the quantile value
java
android/guava/src/com/google/common/math/Quantiles.java
287
[]
true
3
7.92
google/guava
51,352
javadoc
false
compare
private int compare(@Nullable String e1, @Nullable ElementType type1, @Nullable String e2, @Nullable ElementType type2) { if (e1 == null) { return -1; } if (e2 == null) { return 1; } Assert.state(type1 != null, "'type1' must not be null"); Assert.state(type2 != null, "'type2' must not be null"); int result = Boolean.compare(type2.isIndexed(), type1.isIndexed()); if (result != 0) { return result; } if (type1 == ElementType.NUMERICALLY_INDEXED && type2 == ElementType.NUMERICALLY_INDEXED) { long v1 = Long.parseLong(e1); long v2 = Long.parseLong(e2); return Long.compare(v1, v2); } return e1.compareTo(e2); }
Returns {@code true} if this element is an ancestor (immediate or nested parent) of the specified name. @param name the name to check @return {@code true} if this name is an ancestor
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
334
[ "e1", "type1", "e2", "type2" ]
true
6
8.24
spring-projects/spring-boot
79,428
javadoc
false
cosine_distances
def cosine_distances(X, Y=None): """Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Matrix `X`. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ default=None Matrix `Y`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the cosine distance between samples in X and Y. See Also -------- cosine_similarity : Compute cosine similarity between samples in X and Y. scipy.spatial.distance.cosine : Dense matrices only. Examples -------- >>> from sklearn.metrics.pairwise import cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_distances(X, Y) array([[1. , 1. ], [0.422, 0.183]]) """ xp, _ = get_namespace(X, Y) # 1.0 - cosine_similarity(X, Y) without copy S = cosine_similarity(X, Y) S *= -1 S += 1 S = xp.clip(S, 0.0, 2.0) if X is Y or Y is None: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. _fill_diagonal(S, 0.0, xp) return S
Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Matrix `X`. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ default=None Matrix `Y`. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) Returns the cosine distance between samples in X and Y. See Also -------- cosine_similarity : Compute cosine similarity between samples in X and Y. scipy.spatial.distance.cosine : Dense matrices only. Examples -------- >>> from sklearn.metrics.pairwise import cosine_distances >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> cosine_distances(X, Y) array([[1. , 1. ], [0.422, 0.183]])
python
sklearn/metrics/pairwise.py
1,133
[ "X", "Y" ]
false
3
7.68
scikit-learn/scikit-learn
64,340
numpy
false
findThreads
public static Collection<Thread> findThreads(final Predicate<Thread> predicate) { return findThreads(getSystemThreadGroup(), true, predicate); }
Finds all active threads which match the given predicate. @param predicate the predicate. @return An unmodifiable {@link Collection} of active threads matching the given predicate. @throws NullPointerException if the predicate is null. @throws SecurityException if the current thread cannot access the system thread group. @throws SecurityException if the current thread cannot modify thread groups from this thread's thread group up to the system thread group. @since 3.13.0
java
src/main/java/org/apache/commons/lang3/ThreadUtils.java
326
[ "predicate" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
subarray
public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } startIndexInclusive = max0(startIndexInclusive); endIndexExclusive = Math.min(endIndexExclusive, array.length); final int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_SHORT_ARRAY; } return arraycopy(array, startIndexInclusive, 0, newSize, short[]::new); }
Produces a new {@code short} array containing the elements between the start and end indices. <p> The start index is inclusive, the end index exclusive. Null array input produces null output. </p> @param array the input array. @param startIndexInclusive the starting index. Undervalue (&lt;0) is promoted to 0, overvalue (&gt;array.length) results in an empty array. @param endIndexExclusive elements up to endIndex-1 are present in the returned subarray. Undervalue (&lt; startIndex) produces empty array, overvalue (&gt;array.length) is demoted to array length. @return a new array containing the elements between the start and end indices. @since 2.1 @see Arrays#copyOfRange(short[], int, int)
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
7,951
[ "array", "startIndexInclusive", "endIndexExclusive" ]
true
3
7.6
apache/commons-lang
2,896
javadoc
false
dropna
def dropna(self) -> Self: """ Return ExtensionArray without NA values. Returns ------- Self An ExtensionArray of the same type as the original but with all NA values removed. See Also -------- Series.dropna : Remove missing values from a Series. DataFrame.dropna : Remove missing values from a DataFrame. api.extensions.ExtensionArray.isna : Check for missing values in an ExtensionArray. Examples -------- >>> pd.array([1, 2, np.nan]).dropna() <IntegerArray> [1, 2] Length: 2, dtype: Int64 """ # error: Unsupported operand type for ~ ("ExtensionArray") return self[~self.isna()] # type: ignore[operator]
Return ExtensionArray without NA values. Returns ------- Self An ExtensionArray of the same type as the original but with all NA values removed. See Also -------- Series.dropna : Remove missing values from a Series. DataFrame.dropna : Remove missing values from a DataFrame. api.extensions.ExtensionArray.isna : Check for missing values in an ExtensionArray. Examples -------- >>> pd.array([1, 2, np.nan]).dropna() <IntegerArray> [1, 2] Length: 2, dtype: Int64
python
pandas/core/arrays/base.py
1,307
[ "self" ]
Self
true
1
6.8
pandas-dev/pandas
47,362
unknown
false
computeInteractionMatrixAndResiduals
static void computeInteractionMatrixAndResiduals(const Mat& objectPoints, const Mat& R, const Mat& tvec, Mat& L, Mat& s) { Mat objectPointsInCam; int npoints = objectPoints.rows; for (int i = 0; i < npoints; i++) { Mat curPt = objectPoints.row(i); objectPointsInCam = R * curPt.t() + tvec; double Zi = objectPointsInCam.at<double>(2,0); double xi = objectPointsInCam.at<double>(0,0) / Zi; double yi = objectPointsInCam.at<double>(1,0) / Zi; s.at<double>(2*i,0) = xi; s.at<double>(2*i+1,0) = yi; L.at<double>(2*i,0) = -1 / Zi; L.at<double>(2*i,1) = 0; L.at<double>(2*i,2) = xi / Zi; L.at<double>(2*i,3) = xi*yi; L.at<double>(2*i,4) = -(1 + xi*xi); L.at<double>(2*i,5) = yi; L.at<double>(2*i+1,0) = 0; L.at<double>(2*i+1,1) = -1 / Zi; L.at<double>(2*i+1,2) = yi / Zi; L.at<double>(2*i+1,3) = 1 + yi*yi; L.at<double>(2*i+1,4) = -xi*yi; L.at<double>(2*i+1,5) = -xi; } }
@brief Compute the Interaction matrix and the residuals for the current pose. @param objectPoints 3D object points. @param R Current estimated rotation matrix. @param tvec Current estimated translation vector. @param L Interaction matrix for a vector of point features. @param s Residuals.
cpp
modules/calib3d/src/solvepnp.cpp
618
[]
true
2
6.48
opencv/opencv
85,374
doxygen
false
stubString
function stubString() { return ''; }
This method returns an empty string. @static @memberOf _ @since 4.13.0 @category Util @returns {string} Returns the empty string. @example _.times(2, _.stubString); // => ['', '']
javascript
lodash.js
16,207
[]
false
1
7.44
lodash/lodash
61,490
jsdoc
false
stopAsync
@CanIgnoreReturnValue Service stopAsync();
If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running}, this initiates service shutdown and returns immediately. If the service is {@linkplain State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been started nor stopped. If the service has already been stopped, this method returns immediately without taking action. @return this @since 15.0
java
android/guava/src/com/google/common/util/concurrent/Service.java
86
[]
Service
true
1
6.48
google/guava
51,352
javadoc
false
chi2_kernel
def chi2_kernel(X, Y=None, gamma=1.0): """Compute the exponential chi-squared kernel between X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by: .. code-block:: text k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=1 Scaling parameter of the chi2 kernel. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- additive_chi2_kernel : The additive version of this kernel. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> chi2_kernel(X, Y) array([[0.368, 0.135], [0.135, 0.368]]) """ xp, _ = get_namespace(X, Y) K = additive_chi2_kernel(X, Y) K *= gamma if _is_numpy_namespace(xp): return np.exp(K, out=K) return xp.exp(K)
Compute the exponential chi-squared kernel between X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by: .. code-block:: text k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. Parameters ---------- X : array-like of shape (n_samples_X, n_features) A feature array. Y : array-like of shape (n_samples_Y, n_features), default=None An optional second feature array. If `None`, uses `Y=X`. gamma : float, default=1 Scaling parameter of the chi2 kernel. Returns ------- kernel : ndarray of shape (n_samples_X, n_samples_Y) The kernel matrix. See Also -------- additive_chi2_kernel : The additive version of this kernel. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 https://hal.archives-ouvertes.fr/hal-00171412/document Examples -------- >>> from sklearn.metrics.pairwise import chi2_kernel >>> X = [[0, 0, 0], [1, 1, 1]] >>> Y = [[1, 0, 0], [1, 1, 0]] >>> chi2_kernel(X, Y) array([[0.368, 0.135], [0.135, 0.368]])
python
sklearn/metrics/pairwise.py
1,842
[ "X", "Y", "gamma" ]
false
2
7.52
scikit-learn/scikit-learn
64,340
numpy
false
resolveArguments
@Override protected Object[] resolveArguments(Object @Nullable [] args, @Nullable Locale locale) { if (ObjectUtils.isEmpty(args)) { return super.resolveArguments(args, locale); } List<Object> resolvedArgs = new ArrayList<>(args.length); for (Object arg : args) { if (arg instanceof MessageSourceResolvable messageSourceResolvable) { resolvedArgs.add(getMessage(messageSourceResolvable, locale)); } else { resolvedArgs.add(arg); } } return resolvedArgs.toArray(); }
Searches through the given array of objects, finds any MessageSourceResolvable objects and resolves them. <p>Allows for messages to have MessageSourceResolvables as arguments. @param args array of arguments for a message @param locale the locale to resolve through @return an array of arguments with any MessageSourceResolvables resolved
java
spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.java
336
[ "args", "locale" ]
true
3
7.28
spring-projects/spring-framework
59,386
javadoc
false
_perform_double_linked_list_swap
def _perform_double_linked_list_swap( candidate: BaseSchedulerNode, group_head: BaseSchedulerNode, group_tail: BaseSchedulerNode, prev_dict: dict[BaseSchedulerNode, Optional[BaseSchedulerNode]], next_dict: dict[BaseSchedulerNode, Optional[BaseSchedulerNode]], head: BaseSchedulerNode, ) -> BaseSchedulerNode: """ Swap positions of candidate and group in doubly-linked list. Transforms: candidate_prev -> candidate -> group_head...group_tail -> group_tail_next Into: candidate_prev -> group_head...group_tail -> candidate -> group_tail_next Args: candidate: Node to swap with group group_head: First node of group group_tail: Last node of group prev_dict: Dictionary mapping nodes to their previous nodes next_dict: Dictionary mapping nodes to their next nodes head: Current head of the linked list Returns: New head of the linked list (may change if candidate was the head) """ # 0: Update candidate's previous node candidate_prev = prev_dict[candidate] if candidate_prev: next_dict[candidate_prev] = group_head prev_dict[group_head] = candidate_prev # 2: Update group_tail's next node group_tail_next = next_dict[group_tail] if group_tail_next: prev_dict[group_tail_next] = candidate next_dict[candidate] = group_tail_next # 1: Link group_tail to candidate prev_dict[candidate] = group_tail next_dict[group_tail] = candidate # Update head if candidate was the head if head == candidate: return group_head return head
Swap positions of candidate and group in doubly-linked list. Transforms: candidate_prev -> candidate -> group_head...group_tail -> group_tail_next Into: candidate_prev -> group_head...group_tail -> candidate -> group_tail_next Args: candidate: Node to swap with group group_head: First node of group group_tail: Last node of group prev_dict: Dictionary mapping nodes to their previous nodes next_dict: Dictionary mapping nodes to their next nodes head: Current head of the linked list Returns: New head of the linked list (may change if candidate was the head)
python
torch/_inductor/comms.py
494
[ "candidate", "group_head", "group_tail", "prev_dict", "next_dict", "head" ]
BaseSchedulerNode
true
4
7.76
pytorch/pytorch
96,034
google
false
requireTimestamps
public boolean requireTimestamps() { return requireTimestamps; }
Build result representing that no offsets were found as part of the current event. @return Map containing all the partitions the event was trying to get offsets for, and null {@link OffsetAndTimestamp} as value
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ListOffsetsEvent.java
63
[]
true
1
6.48
apache/kafka
31,560
javadoc
false
getSymbolNamesToImport
function getSymbolNamesToImport(sourceFile: SourceFile, checker: TypeChecker, symbolToken: Identifier, compilerOptions: CompilerOptions): string[] { const parent = symbolToken.parent; if ((isJsxOpeningLikeElement(parent) || isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { const jsxNamespace = checker.getJsxNamespace(sourceFile); if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(symbolToken.text, symbolToken, SymbolFlags.Value, /*excludeGlobals*/ false); return needsComponentNameFix ? [symbolToken.text, jsxNamespace] : [jsxNamespace]; } } return [symbolToken.text]; }
@param forceImportKeyword Indicates that the user has already typed `import`, so the result must start with `import`. (In other words, do not allow `const x = require("...")` for JS files.) @internal
typescript
src/services/codefixes/importFixes.ts
1,599
[ "sourceFile", "checker", "symbolToken", "compilerOptions" ]
true
8
6.56
microsoft/TypeScript
107,154
jsdoc
false
scanDirectory
private void scanDirectory( File directory, String packagePrefix, Set<File> currentPath, ImmutableSet.Builder<ResourceInfo> builder) throws IOException { File[] files = directory.listFiles(); if (files == null) { logger.warning("Cannot read directory " + directory); // IO error, just skip the directory return; } for (File f : files) { String name = f.getName(); if (f.isDirectory()) { File deref = f.getCanonicalFile(); if (currentPath.add(deref)) { scanDirectory(deref, packagePrefix + name + "/", currentPath, builder); currentPath.remove(deref); } } else { String resourceName = packagePrefix + name; if (!resourceName.equals(JarFile.MANIFEST_NAME)) { builder.add(ResourceInfo.of(f, resourceName, classloader)); } } } }
Recursively scan the given directory, adding resources for each file encountered. Symlinks which have already been traversed in the current tree path will be skipped to eliminate cycles; otherwise symlinks are traversed. @param directory the root of the directory to scan @param packagePrefix resource path prefix inside {@code classloader} for any files found under {@code directory} @param currentPath canonical files already visited in the current directory tree path, for cycle elimination
java
android/guava/src/com/google/common/reflect/ClassPath.java
521
[ "directory", "packagePrefix", "currentPath", "builder" ]
void
true
5
6.56
google/guava
51,352
javadoc
false
removeAll
@SuppressWarnings("unchecked") // removeAll() always creates an array of the same type as its input public static <T> T[] removeAll(final T[] array, final int... indices) { return (T[]) removeAll((Object) array, indices); }
Removes the elements at the specified positions from the specified array. All remaining elements are shifted to the left. <p> This method returns a new array with the same elements of the input array except those at the specified positions. The component type of the returned array is always the same as that of the input array. </p> <p> If the input array is {@code null}, an IndexOutOfBoundsException will be thrown, because in that case no valid index can be specified. </p> <pre> ArrayUtils.removeAll(["a", "b", "c"], 0, 2) = ["b"] ArrayUtils.removeAll(["a", "b", "c"], 1, 2) = ["a"] </pre> @param <T> the component type of the array. @param array the array to remove the element from, may not be {@code null}. @param indices the positions of the elements to be removed. @return A new array containing the existing elements except those at the specified positions. @throws IndexOutOfBoundsException if any index is out of range (index &lt; 0 || index &gt;= array.length), or if the array is {@code null}. @since 3.0.1
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
5,246
[ "array" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
compareExponentiallyScaledValues
public static int compareExponentiallyScaledValues(long idxA, int scaleA, long idxB, int scaleB) { if (scaleA > scaleB) { return -compareExponentiallyScaledValues(idxB, scaleB, idxA, scaleA); } // scaleA <= scaleB int shifts = scaleB - scaleA; long scaledDownB = idxB >> shifts; int result = Long.compare(idxA, scaledDownB); if (result == 0) { // the scaled down values are equal // this means that b is bigger if it has a "fractional" part, which corresponds to the bits that were removed on the right-shift assert (1L << shifts) > 0; long shiftedAway = idxB & ((1L << shifts) - 1); if (shiftedAway > 0) { return -1; } else { return 0; } } return result; }
Compares the lower boundaries of two buckets, which may have different scales. This is equivalent to a mathematically correct comparison of the lower bucket boundaries. Note that this method allows for scales and indices of the full numeric range of the types. @param idxA the index of the first bucket @param scaleA the scale of the first bucket @param idxB the index of the second bucket @param scaleB the scale of the second bucket @return a negative integer, zero, or a positive integer as the first bucket's lower boundary is less than, equal to, or greater than the second bucket's lower boundary
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialScaleUtils.java
145
[ "idxA", "scaleA", "idxB", "scaleB" ]
true
4
8.08
elastic/elasticsearch
75,680
javadoc
false
toObject
public static Long[] toObject(final long[] array) { if (array == null) { return null; } if (array.length == 0) { return EMPTY_LONG_OBJECT_ARRAY; } return setAll(new Long[array.length], i -> Long.valueOf(array[i])); }
Converts an array of primitive longs to objects. <p>This method returns {@code null} for a {@code null} input array.</p> @param array a {@code long} array. @return a {@link Long} array, {@code null} if null array input.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
8,780
[ "array" ]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
add
private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) throws IOException { try { RawConfigurationMetadata metadata = this.reader.read(in, charset); return create(metadata); } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Failed to read configuration metadata", ex); } }
Build a {@link ConfigurationMetadataRepository} with the current state of this builder. @return this builder
java
configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java
94
[ "in", "charset" ]
SimpleConfigurationMetadataRepository
true
3
6.08
spring-projects/spring-boot
79,428
javadoc
false
getCausalChain
public static List<Throwable> getCausalChain(Throwable throwable) { checkNotNull(throwable); List<Throwable> causes = new ArrayList<>(4); causes.add(throwable); // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches // the slower pointer, then there's a loop. Throwable slowPointer = throwable; boolean advanceSlowPointer = false; Throwable cause; while ((cause = throwable.getCause()) != null) { throwable = cause; causes.add(throwable); if (throwable == slowPointer) { throw new IllegalArgumentException("Loop in causal chain detected.", throwable); } if (advanceSlowPointer) { slowPointer = slowPointer.getCause(); } advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration } return Collections.unmodifiableList(causes); }
Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and will not reflect any subsequent changes to the cause chain. <p>Here's an example of how it can be used to find specific types of exceptions in the cause chain: <pre> Iterables.filter(Throwables.getCausalChain(e), IOException.class)); </pre> @param throwable the non-null {@code Throwable} to extract causes from @return an unmodifiable list containing the cause chain starting with {@code throwable} @throws IllegalArgumentException if there is a loop in the causal chain
java
android/guava/src/com/google/common/base/Throwables.java
284
[ "throwable" ]
true
4
8.24
google/guava
51,352
javadoc
false
_load_backend
def _load_backend(backend: str) -> types.ModuleType: """ Load a pandas plotting backend. Parameters ---------- backend : str The identifier for the backend. Either an entrypoint item registered with importlib.metadata, "matplotlib", or a module name. Returns ------- types.ModuleType The imported backend. """ from importlib.metadata import entry_points if backend == "matplotlib": # Because matplotlib is an optional dependency and first-party backend, # we need to attempt an import here to raise an ImportError if needed. try: module = importlib.import_module("pandas.plotting._matplotlib") except ImportError: raise ImportError( "matplotlib is required for plotting when the " 'default backend "matplotlib" is selected.' ) from None return module found_backend = False eps = entry_points() key = "pandas_plotting_backends" # entry_points lost dict API ~ PY 3.10 # https://github.com/python/importlib_metadata/issues/298 if hasattr(eps, "select"): entry = eps.select(group=key) else: # Argument 2 to "get" of "dict" has incompatible type "Tuple[]"; # expected "EntryPoints" [arg-type] entry = eps.get(key, ()) # type: ignore[arg-type] for entry_point in entry: found_backend = entry_point.name == backend if found_backend: module = entry_point.load() break if not found_backend: # Fall back to unregistered, module name approach. try: module = importlib.import_module(backend) found_backend = True except ImportError: # We re-raise later on. pass if found_backend: if hasattr(module, "plot"): # Validate that the interface is implemented when the option is set, # rather than at plot time. return module raise ValueError( f"Could not find plotting backend '{backend}'. Ensure that you've " f"installed the package providing the '{backend}' entrypoint, or that " "the package has a top-level `.plot` method." )
Load a pandas plotting backend. Parameters ---------- backend : str The identifier for the backend. Either an entrypoint item registered with importlib.metadata, "matplotlib", or a module name. Returns ------- types.ModuleType The imported backend.
python
pandas/plotting/_core.py
2,160
[ "backend" ]
types.ModuleType
true
9
6.32
pandas-dev/pandas
47,362
numpy
false
scanDigits
function scanDigits(): boolean { const start = pos; let isOctal = true; while (isDigit(charCodeChecked(pos))) { if (!isOctalDigit(charCodeUnchecked(pos))) { isOctal = false; } pos++; } tokenValue = text.substring(start, pos); return isOctal; }
Returns the char code for the character at the given position within `text`. If `pos` is outside the bounds set for `text`, `CharacterCodes.EOF` is returned instead.
typescript
src/compiler/scanner.ts
1,348
[]
true
3
6.88
microsoft/TypeScript
107,154
jsdoc
false
baseToString
function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; }
The base implementation of `_.toString` which doesn't convert nullish values to empty strings. @private @param {*} value The value to process. @returns {string} Returns the string.
javascript
lodash.js
4,286
[ "value" ]
false
7
6.24
lodash/lodash
61,490
jsdoc
false
posAngleRads
static double posAngleRads(double rads) { if (rads < 0.0) { return rads + Constants.M_2PI; } else if (rads >= Constants.M_2PI) { return rads - Constants.M_2PI; } else { return rads; } }
Normalizes radians to a value between 0.0 and two PI. @param rads The input radians value. @return The normalized radians value.
java
libs/h3/src/main/java/org/elasticsearch/h3/Vec2d.java
307
[ "rads" ]
true
3
8.24
elastic/elasticsearch
75,680
javadoc
false
_ensure_listlike_indexer
def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None: """ Ensure that a list-like of column labels are all present by adding them if they do not already exist. Parameters ---------- key : list-like of column labels Target labels. axis : key axis if known """ column_axis = 1 # column only exists in 2-dimensional DataFrame if self.ndim != 2: return if isinstance(key, tuple) and len(key) > 1: # key may be a tuple if we are .loc # if length of key is > 1 set key to column part # unless axis is already specified, then go with that if axis is None: axis = column_axis key = key[axis] if ( axis == column_axis and not isinstance(self.obj.columns, MultiIndex) and is_list_like_indexer(key) and not com.is_bool_indexer(key) and all(is_hashable(k) for k in key) ): # GH#38148 keys = self.obj.columns.union(key, sort=False) diff = Index(key).difference(self.obj.columns, sort=False) if len(diff): # e.g. if we are doing df.loc[:, ["A", "B"]] = 7 and "B" # is a new column, add the new columns with dtype=np.void # so that later when we go through setitem_single_column # we will use isetitem. Without this, the reindex_axis # below would create float64 columns in this example, which # would successfully hold 7, so we would end up with the wrong # dtype. indexer = np.arange(len(keys), dtype=np.intp) indexer[len(self.obj.columns) :] = -1 new_mgr = self.obj._mgr.reindex_indexer( keys, indexer=indexer, axis=0, only_slice=True, use_na_proxy=True ) self.obj._mgr = new_mgr return self.obj._mgr = self.obj._mgr.reindex_axis(keys, axis=0, only_slice=True)
Ensure that a list-like of column labels are all present by adding them if they do not already exist. Parameters ---------- key : list-like of column labels Target labels. axis : key axis if known
python
pandas/core/indexing.py
863
[ "self", "key", "axis", "value" ]
None
true
11
6.88
pandas-dev/pandas
47,362
numpy
false
segmentFor
Segment<K, V> segmentFor(int hash) { // TODO(fry): Lazily create segments? return segments[(hash >>> segmentShift) & segmentMask]; }
Returns the segment that should be used for a key with the given hash. @param hash the hash code for the key @return the segment
java
android/guava/src/com/google/common/cache/LocalCache.java
1,755
[ "hash" ]
true
1
6.8
google/guava
51,352
javadoc
false
hexRing
public static long[] hexRing(long h3) { final long[] ring = new long[hexRingSize(h3)]; for (int i = 0; i < ring.length; i++) { ring[i] = hexRingPosToH3(h3, i); assert ring[i] >= 0; } return ring; }
Returns the neighbor indexes. @param h3 Origin index @return All neighbor indexes from the origin
java
libs/h3/src/main/java/org/elasticsearch/h3/H3.java
364
[ "h3" ]
true
2
8.08
elastic/elasticsearch
75,680
javadoc
false
add
public <V> Member<V> add(String name, Extractor<T, V> extractor) { Assert.notNull(name, "'name' must not be null"); Assert.notNull(extractor, "'extractor' must not be null"); return addMember(name, extractor); }
Add a new member with an extracted value. @param <V> the value type @param name the member name @param extractor {@link Extractor} to extract the value @return the added {@link Member} which may be configured further
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
237
[ "name", "extractor" ]
true
1
7.04
spring-projects/spring-boot
79,428
javadoc
false
whenHasPath
default ValueProcessor<T> whenHasPath(String path) { return whenHasPath(MemberPath.of(path)::equals); }
Return a new processor from this one that only applied to members with the given path. @param path the patch to match @return a new {@link ValueProcessor} that only applies when the path matches
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
1,000
[ "path" ]
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
isQualifierMatch
public static boolean isQualifierMatch( Predicate<String> qualifier, String beanName, @Nullable BeanFactory beanFactory) { // Try quick bean name or alias match first... if (qualifier.test(beanName)) { return true; } if (beanFactory != null) { for (String alias : beanFactory.getAliases(beanName)) { if (qualifier.test(alias)) { return true; } } try { Class<?> beanType = beanFactory.getType(beanName); if (beanFactory instanceof ConfigurableBeanFactory cbf) { BeanDefinition bd = cbf.getMergedBeanDefinition(beanName); // Explicit qualifier metadata on bean definition? (typically in XML definition) if (bd instanceof AbstractBeanDefinition abd) { AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName()); if (candidate != null) { Object value = candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY); if (value != null && qualifier.test(value.toString())) { return true; } } } // Corresponding qualifier on factory method? (typically in configuration class) if (bd instanceof RootBeanDefinition rbd) { Method factoryMethod = rbd.getResolvedFactoryMethod(); if (factoryMethod != null) { Qualifier targetAnnotation = AnnotationUtils.getAnnotation(factoryMethod, Qualifier.class); if (targetAnnotation != null) { return qualifier.test(targetAnnotation.value()); } } } } // Corresponding qualifier on bean implementation class? (for custom user types) if (beanType != null) { Qualifier targetAnnotation = AnnotationUtils.getAnnotation(beanType, Qualifier.class); if (targetAnnotation != null) { return qualifier.test(targetAnnotation.value()); } } } catch (NoSuchBeanDefinitionException ignored) { // can't compare qualifiers for a manually registered singleton object } } return false; }
Check whether the named bean declares a qualifier of the given name. @param qualifier the qualifier to match @param beanName the name of the candidate bean @param beanFactory the factory from which to retrieve the named bean @return {@code true} if either the bean definition (in the XML case) or the bean's factory method (in the {@code @Bean} case) defines a matching qualifier value (through {@code <qualifier>} or {@code @Qualifier}) @since 5.0
java
spring-beans/src/main/java/org/springframework/beans/factory/annotation/BeanFactoryAnnotationUtils.java
165
[ "qualifier", "beanName", "beanFactory" ]
true
15
7.68
spring-projects/spring-framework
59,386
javadoc
false
standardFirstKey
protected K standardFirstKey() { Entry<K, V> entry = firstEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } }
A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override {@code firstEntry}, you may wish to override {@code firstKey} to forward to this implementation.
java
android/guava/src/com/google/common/collect/ForwardingNavigableMap.java
196
[]
K
true
2
6.56
google/guava
51,352
javadoc
false
value_labels
def value_labels(self) -> dict[str, dict[int, str]]: """ Return a nested dict associating each variable name to its value and label. This method retrieves the value labels from a Stata file. Value labels are mappings between the coded values and their corresponding descriptive labels in a Stata dataset. Returns ------- dict A python dictionary. See Also -------- read_stata : Read Stata file into DataFrame. DataFrame.to_stata : Export DataFrame object to Stata dta format. Examples -------- >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["col_1", "col_2"]) >>> time_stamp = pd.Timestamp(2000, 2, 29, 14, 21) >>> path = "/My_path/filename.dta" >>> value_labels = {"col_1": {3: "x"}} >>> df.to_stata( ... path, ... time_stamp=time_stamp, # doctest: +SKIP ... value_labels=value_labels, ... version=None, ... ) # doctest: +SKIP >>> with pd.io.stata.StataReader(path) as reader: # doctest: +SKIP ... print(reader.value_labels()) # doctest: +SKIP {'col_1': {3: 'x'}} >>> pd.read_stata(path) # doctest: +SKIP index col_1 col_2 0 0 1 2 1 1 x 4 """ if not self._value_labels_read: self._read_value_labels() return self._value_label_dict
Return a nested dict associating each variable name to its value and label. This method retrieves the value labels from a Stata file. Value labels are mappings between the coded values and their corresponding descriptive labels in a Stata dataset. Returns ------- dict A python dictionary. See Also -------- read_stata : Read Stata file into DataFrame. DataFrame.to_stata : Export DataFrame object to Stata dta format. Examples -------- >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["col_1", "col_2"]) >>> time_stamp = pd.Timestamp(2000, 2, 29, 14, 21) >>> path = "/My_path/filename.dta" >>> value_labels = {"col_1": {3: "x"}} >>> df.to_stata( ... path, ... time_stamp=time_stamp, # doctest: +SKIP ... value_labels=value_labels, ... version=None, ... ) # doctest: +SKIP >>> with pd.io.stata.StataReader(path) as reader: # doctest: +SKIP ... print(reader.value_labels()) # doctest: +SKIP {'col_1': {3: 'x'}} >>> pd.read_stata(path) # doctest: +SKIP index col_1 col_2 0 0 1 2 1 1 x 4
python
pandas/io/stata.py
2,045
[ "self" ]
dict[str, dict[int, str]]
true
2
8.32
pandas-dev/pandas
47,362
unknown
false
invert
public static String[][] invert(final String[][] array) { final String[][] newArray = new String[array.length][2]; for (int i = 0; i < array.length; i++) { newArray[i][0] = array[i][1]; newArray[i][1] = array[i][0]; } return newArray; }
Used to invert an escape array into an unescape array. @param array String[][] to be inverted. @return String[][] inverted array.
java
src/main/java/org/apache/commons/lang3/text/translate/EntityArrays.java
421
[ "array" ]
true
2
8.24
apache/commons-lang
2,896
javadoc
false
allows_duplicate_labels
def allows_duplicate_labels(self) -> bool: """ Whether this object allows duplicate labels. Setting ``allows_duplicate_labels=False`` ensures that the index (and columns of a DataFrame) are unique. Most methods that accept and return a Series or DataFrame will propagate the value of ``allows_duplicate_labels``. See :ref:`duplicates` for more. See Also -------- DataFrame.attrs : Set global metadata on this object. DataFrame.set_flags : Set global flags on this object. Examples -------- >>> df = pd.DataFrame({"A": [1, 2]}, index=["a", "a"]) >>> df.flags.allows_duplicate_labels True >>> df.flags.allows_duplicate_labels = False Traceback (most recent call last): ... pandas.errors.DuplicateLabelError: Index has duplicates. positions label a [0, 1] """ return self._allows_duplicate_labels
Whether this object allows duplicate labels. Setting ``allows_duplicate_labels=False`` ensures that the index (and columns of a DataFrame) are unique. Most methods that accept and return a Series or DataFrame will propagate the value of ``allows_duplicate_labels``. See :ref:`duplicates` for more. See Also -------- DataFrame.attrs : Set global metadata on this object. DataFrame.set_flags : Set global flags on this object. Examples -------- >>> df = pd.DataFrame({"A": [1, 2]}, index=["a", "a"]) >>> df.flags.allows_duplicate_labels True >>> df.flags.allows_duplicate_labels = False Traceback (most recent call last): ... pandas.errors.DuplicateLabelError: Index has duplicates. positions label a [0, 1]
python
pandas/core/flags.py
68
[ "self" ]
bool
true
1
6.8
pandas-dev/pandas
47,362
unknown
false
onSendAttempt
public void onSendAttempt(final long currentTimeMs) { this.requestInFlight = true; // Here we update the timer everytime we try to send a request. this.lastSentMs = currentTimeMs; }
@return True if no response has been received after the last send, indicating that there is a request in-flight.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestState.java
102
[ "currentTimeMs" ]
void
true
1
6
apache/kafka
31,560
javadoc
false
construct_docker_push_command
def construct_docker_push_command( image_params: CommonBuildParams, ) -> list[str]: """ Constructs docker push command based on the parameters passed. :param image_params: parameters of the image :return: Command to run as list of string """ return ["docker", "push", image_params.airflow_image_name]
Constructs docker push command based on the parameters passed. :param image_params: parameters of the image :return: Command to run as list of string
python
dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
457
[ "image_params" ]
list[str]
true
1
6.88
apache/airflow
43,597
sphinx
false
all
public KafkaFuture<Void> all() { return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture<?>[0])); }
Get a future which completes when the transaction specified by {@link AbortTransactionSpec} in the respective call to {@link Admin#abortTransaction(AbortTransactionSpec, AbortTransactionOptions)} returns successfully or fails due to an error or timeout. @return the future
java
clients/src/main/java/org/apache/kafka/clients/admin/AbortTransactionResult.java
41
[]
true
1
6
apache/kafka
31,560
javadoc
false
GetCompressedFileSizeW
int GetCompressedFileSizeW(String lpFileName, IntConsumer lpFileSizeHigh);
Retrieves the actual number of bytes of disk storage used to store a specified file. https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getcompressedfilesizew @param lpFileName the path string @param lpFileSizeHigh pointer to high-order DWORD for compressed file size (or null if not needed) @return the low-order DWORD for compressed file size
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/lib/Kernel32Library.java
96
[ "lpFileName", "lpFileSizeHigh" ]
true
1
6.16
elastic/elasticsearch
75,680
javadoc
false
from
static SslManagerBundle from(TrustManager... trustManagers) { Assert.notNull(trustManagers, "'trustManagers' must not be null"); KeyManagerFactory defaultKeyManagerFactory = createDefaultKeyManagerFactory(); TrustManagerFactory defaultTrustManagerFactory = createDefaultTrustManagerFactory(); return of(defaultKeyManagerFactory, FixedTrustManagerFactory.of(defaultTrustManagerFactory, trustManagers)); }
Factory method to create a new {@link SslManagerBundle} using the given {@link TrustManager TrustManagers} and the default {@link KeyManagerFactory}. @param trustManagers the trust managers to use @return a new {@link SslManagerBundle} instance @since 3.5.0
java
core/spring-boot/src/main/java/org/springframework/boot/ssl/SslManagerBundle.java
149
[]
SslManagerBundle
true
1
6.24
spring-projects/spring-boot
79,428
javadoc
false
doProcessConfigurationClass
protected final @Nullable SourceClass doProcessConfigurationClass( ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter) throws IOException { if (configClass.getMetadata().isAnnotated(Component.class.getName())) { // Recursively process any member (nested) classes first processMemberClasses(configClass, sourceClass, filter); } // Process any @PropertySource annotations for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), org.springframework.context.annotation.PropertySource.class, PropertySources.class, true)) { if (this.propertySourceRegistry != null) { this.propertySourceRegistry.processPropertySource(propertySource); } else { logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment"); } } // Search for locally declared @ComponentScan annotations first. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScan.class, ComponentScans.class, MergedAnnotation::isDirectlyPresent); // Fall back to searching for @ComponentScan meta-annotations (which indirectly // includes locally declared composed annotations). if (componentScans.isEmpty()) { componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScan.class, ComponentScans.class, MergedAnnotation::isMetaPresent); } if (!componentScans.isEmpty()) { List<Condition> registerBeanConditions = collectRegisterBeanConditions(configClass); if (!registerBeanConditions.isEmpty()) { throw new ApplicationContextException( "Component scan for configuration class [%s] could not be used with conditions in REGISTER_BEAN phase: %s" .formatted(configClass.getMetadata().getClassName(), registerBeanConditions)); } for (AnnotationAttributes componentScan : componentScans) { // The config class is annotated with @ComponentScan -> perform the scan immediately Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // Check the set of scanned definitions for any further config classes and parse recursively if needed for (BeanDefinitionHolder holder : scannedBeanDefinitions) { BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) { parse(bdCand.getBeanClassName(), holder.getBeanName()); } } } } // Process any @Import annotations processImports(configClass, sourceClass, getImports(sourceClass), filter, true); // Process any @ImportResource annotations AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class); if (importResource != null) { String[] resources = importResource.getStringArray("locations"); Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader"); for (String resource : resources) { String resolvedResource = this.environment.resolveRequiredPlaceholders(resource); configClass.addImportedResource(resolvedResource, readerClass); } } // Process individual @Bean methods Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { if (methodMetadata.isAnnotated("kotlin.jvm.JvmStatic") && !methodMetadata.isStatic()) { continue; } configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); } // Process default methods on interfaces processInterfaces(configClass, sourceClass); // Process superclass, if any if (sourceClass.getMetadata().hasSuperClass()) { String superclass = sourceClass.getMetadata().getSuperClassName(); if (superclass != null && !superclass.startsWith("java")) { boolean superclassKnown = this.knownSuperclasses.containsKey(superclass); this.knownSuperclasses.add(superclass, configClass); if (!superclassKnown) { // Superclass found, return its annotation metadata and recurse return sourceClass.getSuperClass(); } } } // No superclass -> processing is complete return null; }
Apply processing and build a complete {@link ConfigurationClass} by reading the annotations, members and methods from the source class. This method can be called multiple times as relevant sources are discovered. @param configClass the configuration class being build @param sourceClass a source class @return the superclass, or {@code null} if none found or previously processed
java
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
303
[ "configClass", "sourceClass", "filter" ]
SourceClass
true
15
7.84
spring-projects/spring-framework
59,386
javadoc
false
isUrlExcludedFactory
function isUrlExcludedFactory (excludePatterns = []) { if (excludePatterns.length === 0) { return () => false } return function isUrlExcluded (url) { let urlLowerCased for (const pattern of excludePatterns) { if (typeof pattern === 'string') { if (!urlLowerCased) { // Convert URL to lowercase only once urlLowerCased = url.toLowerCase() } // Simple string match (case-insensitive) if (urlLowerCased.includes(pattern.toLowerCase())) { return true } } else if (pattern instanceof RegExp) { // Regex pattern match if (pattern.test(url)) { return true } } } return false } }
Factory function to create a URL exclusion checker @param {Array<string| RegExp>} [excludePatterns=[]] - Array of patterns to exclude @returns {IsUrlExcluded} - A function that checks if a URL matches any of the exclude patterns
javascript
deps/undici/src/lib/mock/snapshot-utils.js
68
[]
false
8
6.48
nodejs/node
114,839
jsdoc
false
applyAsInt
int applyAsInt(double value) throws E;
Applies this function to the given argument. @param value the function argument @return the function result @throws E Thrown when the function fails.
java
src/main/java/org/apache/commons/lang3/function/FailableDoubleToIntFunction.java
53
[ "value" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
downloaderFor
private ProviderDownload downloaderFor(DatabaseConfiguration database) { if (database.provider() instanceof DatabaseConfiguration.Maxmind maxmind) { return new MaxmindDownload(database.name(), maxmind); } else if (database.provider() instanceof DatabaseConfiguration.Ipinfo ipinfo) { return new IpinfoDownload(database.name(), ipinfo); } else { throw new IllegalArgumentException( Strings.format("Unexpected provider [%s] for configuration [%s]", database.provider().getClass(), database.id()) ); } }
This method fetches the database file for the given database from the passed-in source, then indexes that database file into the .geoip_databases Elasticsearch index, deleting any old versions of the database from the index if they exist. @param name The name of the database to be downloaded and indexed into an Elasticsearch index @param checksum The checksum to compare to the computed checksum of the downloaded file @param source The supplier of an InputStream that will actually download the file
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/EnterpriseGeoIpDownloader.java
422
[ "database" ]
ProviderDownload
true
3
6.56
elastic/elasticsearch
75,680
javadoc
false
_shallow_copy
def _shallow_copy(self, values, name: Hashable = no_default): """ Create a new RangeIndex with the same class as the caller, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ---------- values : the values to create the new RangeIndex, optional name : Label, defaults to self.name """ name = self._name if name is no_default else name if values.dtype.kind == "f": return Index(values, name=name, dtype=np.float64) if values.dtype.kind == "i" and values.ndim == 1: # GH 46675 & 43885: If values is equally spaced, return a # more memory-compact RangeIndex instead of Index with 64-bit dtype if len(values) == 1: start = values[0] new_range = range(start, start + self.step, self.step) return type(self)._simple_new(new_range, name=name) maybe_range = ibase.maybe_sequence_to_range(values) if isinstance(maybe_range, range): return type(self)._simple_new(maybe_range, name=name) return self._constructor._simple_new(values, name=name)
Create a new RangeIndex with the same class as the caller, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ---------- values : the values to create the new RangeIndex, optional name : Label, defaults to self.name
python
pandas/core/indexes/range.py
591
[ "self", "values", "name" ]
true
7
6.72
pandas-dev/pandas
47,362
numpy
false
uniqueIndex
private static <K, V> ImmutableMap<K, V> uniqueIndex( Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) { checkNotNull(keyFunction); while (values.hasNext()) { V value = values.next(); builder.put(keyFunction.apply(value), value); } try { return builder.buildOrThrow(); } catch (IllegalArgumentException duplicateKeys) { throw new IllegalArgumentException( duplicateKeys.getMessage() + ". To index multiple values under a key, use Multimaps.index."); } }
Returns a map with the given {@code values}, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applying {@code keyFunction} to that value. These entries appear in the same order as the input values. Example usage: {@snippet : Color red = new Color("red", 255, 0, 0); ... Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator(); Map<String, Color> colorForName = uniqueIndex(allColors, toStringFunction()); assertThat(colorForName).containsEntry("red", red); } <p>If your index may associate multiple values with each key, use {@link Multimaps#index(Iterator, Function) Multimaps.index}. @param values the values to use when constructing the {@code Map} @param keyFunction the function used to produce the key for each value @return a map mapping the result of evaluating the function {@code keyFunction} on each value in the input collection to that value @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one value in the input collection @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code keyFunction} produces {@code null} for any value @since 10.0
java
android/guava/src/com/google/common/collect/Maps.java
1,337
[ "values", "keyFunction", "builder" ]
true
3
7.76
google/guava
51,352
javadoc
false
get_action_id
def get_action_id(resource_type: AvpEntities, method: ResourceMethod | str, entity_id: str | None): """ Return action id. Convention for action ID is <resource_type>.<method>. Example: Variable.GET. :param resource_type: Resource type. :param method: Resource method. :param entity_id: The entity ID. """ if method == "GET" and not entity_id: method = "LIST" return f"{resource_type.value}.{method}"
Return action id. Convention for action ID is <resource_type>.<method>. Example: Variable.GET. :param resource_type: Resource type. :param method: Resource method. :param entity_id: The entity ID.
python
providers/amazon/src/airflow/providers/amazon/aws/auth_manager/avp/entities.py
60
[ "resource_type", "method", "entity_id" ]
true
3
6.72
apache/airflow
43,597
sphinx
false
readResolve
Object readResolve() { if (this.equals(ALL)) { return all(); } else { return this; } }
Returns a string representation of this range, such as {@code "[3..5)"} (other examples are listed in the class documentation).
java
android/guava/src/com/google/common/collect/Range.java
692
[]
Object
true
2
7.04
google/guava
51,352
javadoc
false
generateClassElementDecorationExpression
function generateClassElementDecorationExpression(node: ClassExpression | ClassDeclaration, member: ClassElement) { const allDecorators = getAllDecoratorsOfClassElement(member, node, /*useLegacyDecorators*/ true); const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); if (!decoratorExpressions) { return undefined; } // Emit the call to __decorate. Given the following: // // class C { // @dec method(@dec2 x) {} // @dec get accessor() {} // @dec prop; // } // // The emit for a method is: // // __decorate([ // dec, // __param(0, dec2), // __metadata("design:type", Function), // __metadata("design:paramtypes", [Object]), // __metadata("design:returntype", void 0) // ], C.prototype, "method", null); // // The emit for an accessor is: // // __decorate([ // dec // ], C.prototype, "accessor", null); // // The emit for a property is: // // __decorate([ // dec // ], C.prototype, "prop"); // const prefix = getClassMemberPrefix(node, member); const memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !hasSyntacticModifier(member, ModifierFlags.Ambient)); const descriptor = isPropertyDeclaration(member) && !hasAccessorModifier(member) // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. // We have this extra argument here so that we can inject an explicit property descriptor at a later date. : factory.createNull(); const helper = emitHelpers().createDecorateHelper( decoratorExpressions, prefix, memberName, descriptor, ); setEmitFlags(helper, EmitFlags.NoComments); setSourceMapRange(helper, moveRangePastModifiers(member)); return helper; }
Generates an expression used to evaluate class element decorators at runtime. @param node The class node that contains the member. @param member The class member.
typescript
src/compiler/transformers/legacyDecorators.ts
604
[ "node", "member" ]
false
4
6
microsoft/TypeScript
107,154
jsdoc
false
deleteShareGroupOffsets
DeleteShareGroupOffsetsResult deleteShareGroupOffsets(String groupId, Set<String> topics, DeleteShareGroupOffsetsOptions options);
Delete offsets for a set of topics in a share group. @param groupId The group for which to delete offsets. @param topics The topics for which to delete offsets. @param options The options to use when deleting offsets in a share group. @return The DeleteShareGroupOffsetsResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
2,001
[ "groupId", "topics", "options" ]
DeleteShareGroupOffsetsResult
true
1
6.48
apache/kafka
31,560
javadoc
false
__call__
def __call__(self, x, pos: int | None = 0) -> str: """ Return the time of day as a formatted string. Parameters ---------- x : float The time of day specified as seconds since 00:00 (midnight), with up to microsecond precision. pos Unused Returns ------- str A string in HH:MM:SS.mmmuuu format. Microseconds, milliseconds and seconds are only displayed if non-zero. """ fmt = "%H:%M:%S.%f" s = int(x) msus = round((x - s) * 10**6) ms = msus // 1000 us = msus % 1000 m, s = divmod(s, 60) h, m = divmod(m, 60) _, h = divmod(h, 24) if us != 0: return pydt.time(h, m, s, msus).strftime(fmt) elif ms != 0: return pydt.time(h, m, s, msus).strftime(fmt)[:-3] elif s != 0: return pydt.time(h, m, s).strftime("%H:%M:%S") return pydt.time(h, m).strftime("%H:%M")
Return the time of day as a formatted string. Parameters ---------- x : float The time of day specified as seconds since 00:00 (midnight), with up to microsecond precision. pos Unused Returns ------- str A string in HH:MM:SS.mmmuuu format. Microseconds, milliseconds and seconds are only displayed if non-zero.
python
pandas/plotting/_matplotlib/converter.py
187
[ "self", "x", "pos" ]
str
true
4
6.72
pandas-dev/pandas
47,362
numpy
false
toFloat
public static float toFloat(final String str, final float defaultValue) { try { return Float.parseFloat(str); } catch (final RuntimeException e) { return defaultValue; } }
Converts a {@link String} to a {@code float}, returning a default value if the conversion fails. <p> If the string {@code str} is {@code null}, the default value is returned. </p> <pre> NumberUtils.toFloat(null, 1.1f) = 1.1f NumberUtils.toFloat("", 1.1f) = 1.1f NumberUtils.toFloat("1.5", 0.0f) = 1.5f </pre> @param str the string to convert, may be {@code null}. @param defaultValue the default value. @return the float represented by the string, or defaultValue if conversion fails. @since 2.1
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,515
[ "str", "defaultValue" ]
true
2
8.08
apache/commons-lang
2,896
javadoc
false
repeat
def repeat(self, repeats): """ Duplicate each string in the Series or Index. Duplicates each string in the Series or Index, either by applying the same repeat count to all elements or by using different repeat values for each element. Parameters ---------- repeats : int or sequence of int Same value for all (int) or different value per (sequence). Returns ------- Series or pandas.Index Series or Index of repeated string objects specified by input parameter repeats. See Also -------- Series.str.lower : Convert all characters in each string to lowercase. Series.str.upper : Convert all characters in each string to uppercase. Series.str.title : Convert each string to title case (capitalizing the first letter of each word). Series.str.strip : Remove leading and trailing whitespace from each string. Series.str.replace : Replace occurrences of a substring with another substring in each string. Series.str.ljust : Left-justify each string in the Series/Index by padding with a specified character. Series.str.rjust : Right-justify each string in the Series/Index by padding with a specified character. Examples -------- >>> s = pd.Series(["a", "b", "c"]) >>> s 0 a 1 b 2 c dtype: str Single int repeats string in Series >>> s.str.repeat(repeats=2) 0 aa 1 bb 2 cc dtype: str Sequence of int repeats corresponding string in Series >>> s.str.repeat(repeats=[1, 2, 3]) 0 a 1 bb 2 ccc dtype: str """ result = self._data.array._str_repeat(repeats) return self._wrap_result(result)
Duplicate each string in the Series or Index. Duplicates each string in the Series or Index, either by applying the same repeat count to all elements or by using different repeat values for each element. Parameters ---------- repeats : int or sequence of int Same value for all (int) or different value per (sequence). Returns ------- Series or pandas.Index Series or Index of repeated string objects specified by input parameter repeats. See Also -------- Series.str.lower : Convert all characters in each string to lowercase. Series.str.upper : Convert all characters in each string to uppercase. Series.str.title : Convert each string to title case (capitalizing the first letter of each word). Series.str.strip : Remove leading and trailing whitespace from each string. Series.str.replace : Replace occurrences of a substring with another substring in each string. Series.str.ljust : Left-justify each string in the Series/Index by padding with a specified character. Series.str.rjust : Right-justify each string in the Series/Index by padding with a specified character. Examples -------- >>> s = pd.Series(["a", "b", "c"]) >>> s 0 a 1 b 2 c dtype: str Single int repeats string in Series >>> s.str.repeat(repeats=2) 0 aa 1 bb 2 cc dtype: str Sequence of int repeats corresponding string in Series >>> s.str.repeat(repeats=[1, 2, 3]) 0 a 1 bb 2 ccc dtype: str
python
pandas/core/strings/accessor.py
1,676
[ "self", "repeats" ]
false
1
6.24
pandas-dev/pandas
47,362
numpy
false
getAnnotatedMethods
private static ImmutableList<Method> getAnnotatedMethods(Class<?> clazz) { try { return subscriberMethodsCache.getUnchecked(clazz); } catch (UncheckedExecutionException e) { if (e.getCause() instanceof IllegalArgumentException) { /* * IllegalArgumentException is the one unchecked exception that we know is likely to happen * (thanks to the checkArgument calls in getAnnotatedMethodsNotCached). If it happens, we'd * prefer to propagate an IllegalArgumentException to the caller. However, we don't want to * simply rethrow an exception (e.getCause()) that may in rare cases have come from another * thread. To accomplish both goals, we wrap that IllegalArgumentException in a new * instance. */ throw new IllegalArgumentException(e.getCause().getMessage(), e.getCause()); } /* * If some other exception happened, we just propagate the wrapper * UncheckedExecutionException, which has the stack trace from this thread and which has its * cause set to the underlying exception (which may be from another thread). If we someday * learn that some other exception besides IllegalArgumentException is common, then we could * add another special case to throw an instance of it, too. */ throw e; } }
Returns all subscribers for the given listener grouped by the type of event they subscribe to.
java
android/guava/src/com/google/common/eventbus/SubscriberRegistry.java
167
[ "clazz" ]
true
3
6
google/guava
51,352
javadoc
false
prepare_code_snippet
def prepare_code_snippet(file_path: Path, line_no: int, context_lines_count: int = 5) -> str: """ Prepare code snippet with line numbers and a specific line marked. :param file_path: File name :param line_no: Line number :param context_lines_count: The number of lines that will be cut before and after. :return: str """ code_lines = file_path.read_text().splitlines() # Prepend line number code_lines = [ f">{lno:3} | {line}" if line_no == lno else f"{lno:4} | {line}" for lno, line in enumerate(code_lines, 1) ] # # Cut out the snippet start_line_no = max(0, line_no - context_lines_count - 1) end_line_no = line_no + context_lines_count code_lines = code_lines[start_line_no:end_line_no] # Join lines code = "\n".join(code_lines) return code
Prepare code snippet with line numbers and a specific line marked. :param file_path: File name :param line_no: Line number :param context_lines_count: The number of lines that will be cut before and after. :return: str
python
airflow-core/src/airflow/utils/code_utils.py
53
[ "file_path", "line_no", "context_lines_count" ]
str
true
2
8.4
apache/airflow
43,597
sphinx
false
toByte
public Byte toByte() { return Byte.valueOf(byteValue()); }
Gets this mutable as an instance of Byte. @return a Byte instance containing the value from this mutable.
java
src/main/java/org/apache/commons/lang3/mutable/MutableByte.java
373
[]
Byte
true
1
6.96
apache/commons-lang
2,896
javadoc
false
to_html
def to_html( self, buf: FilePath | WriteBuffer[str] | None = None, encoding: str | None = None, classes: str | list | tuple | None = None, notebook: bool = False, border: int | bool | None = None, table_id: str | None = None, render_links: bool = False, ) -> str | None: """ Render a DataFrame to a html table. Parameters ---------- buf : str, path object, file-like object, or None, default None String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If None, the result is returned as a string. encoding : str, default “utf-8” Set character encoding. classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False Whether the generated HTML is for IPython Notebook. border : int or bool When an integer value is provided, it sets the border attribute in the opening tag, specifying the thickness of the border. If ``False`` or ``0`` is passed, the border attribute will not be present in the ``<table>`` tag. The default value for this parameter is governed by ``pd.options.display.html.border``. table_id : str, optional A css id is included in the opening `<table>` tag if specified. render_links : bool, default False Convert URLs to HTML links. """ from pandas.io.formats.html import ( HTMLFormatter, NotebookFormatter, ) Klass = NotebookFormatter if notebook else HTMLFormatter html_formatter = Klass( self.fmt, classes=classes, border=border, table_id=table_id, render_links=render_links, ) string = html_formatter.to_string() return save_to_buffer(string, buf=buf, encoding=encoding)
Render a DataFrame to a html table. Parameters ---------- buf : str, path object, file-like object, or None, default None String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If None, the result is returned as a string. encoding : str, default “utf-8” Set character encoding. classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False Whether the generated HTML is for IPython Notebook. border : int or bool When an integer value is provided, it sets the border attribute in the opening tag, specifying the thickness of the border. If ``False`` or ``0`` is passed, the border attribute will not be present in the ``<table>`` tag. The default value for this parameter is governed by ``pd.options.display.html.border``. table_id : str, optional A css id is included in the opening `<table>` tag if specified. render_links : bool, default False Convert URLs to HTML links.
python
pandas/io/formats/format.py
895
[ "self", "buf", "encoding", "classes", "notebook", "border", "table_id", "render_links" ]
str | None
true
2
6.64
pandas-dev/pandas
47,362
numpy
false
_parse_possible_contraction
def _parse_possible_contraction( positions, input_sets, output_set, idx_dict, memory_limit, path_cost, naive_cost ): """Compute the cost (removed size + flops) and resultant indices for performing the contraction specified by ``positions``. Parameters ---------- positions : tuple of int The locations of the proposed tensors to contract. input_sets : list of sets The indices found on each tensors. output_set : set The output indices of the expression. idx_dict : dict Mapping of each index to its size. memory_limit : int The total allowed size for an intermediary tensor. path_cost : int The contraction cost so far. naive_cost : int The cost of the unoptimized expression. Returns ------- cost : (int, int) A tuple containing the size of any indices removed, and the flop cost. positions : tuple of int The locations of the proposed tensors to contract. new_input_sets : list of sets The resulting new list of indices if this proposed contraction is performed. """ # Find the contraction contract = _find_contraction(positions, input_sets, output_set) idx_result, new_input_sets, idx_removed, idx_contract = contract # Sieve the results based on memory_limit new_size = _compute_size_by_dict(idx_result, idx_dict) if new_size > memory_limit: return None # Build sort tuple old_sizes = ( _compute_size_by_dict(input_sets[p], idx_dict) for p in positions ) removed_size = sum(old_sizes) - new_size # NB: removed_size used to be just the size of any removed indices i.e.: # helpers.compute_size_by_dict(idx_removed, idx_dict) cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict) sort = (-removed_size, cost) # Sieve based on total cost as well if (path_cost + cost) > naive_cost: return None # Add contraction to possible choices return [sort, positions, new_input_sets]
Compute the cost (removed size + flops) and resultant indices for performing the contraction specified by ``positions``. Parameters ---------- positions : tuple of int The locations of the proposed tensors to contract. input_sets : list of sets The indices found on each tensors. output_set : set The output indices of the expression. idx_dict : dict Mapping of each index to its size. memory_limit : int The total allowed size for an intermediary tensor. path_cost : int The contraction cost so far. naive_cost : int The cost of the unoptimized expression. Returns ------- cost : (int, int) A tuple containing the size of any indices removed, and the flop cost. positions : tuple of int The locations of the proposed tensors to contract. new_input_sets : list of sets The resulting new list of indices if this proposed contraction is performed.
python
numpy/_core/einsumfunc.py
224
[ "positions", "input_sets", "output_set", "idx_dict", "memory_limit", "path_cost", "naive_cost" ]
false
3
6
numpy/numpy
31,054
numpy
false
instantiate
public List<T> instantiate(@Nullable ClassLoader classLoader, Collection<String> names) { Assert.notNull(names, "'names' must not be null"); return instantiate(names.stream().map((name) -> TypeSupplier.forName(classLoader, name))); }
Instantiate the given set of class name, injecting constructor arguments as necessary. @param classLoader the source classloader @param names the class names to instantiate @return a list of instantiated instances @since 2.4.8
java
core/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java
125
[ "classLoader", "names" ]
true
1
6.16
spring-projects/spring-boot
79,428
javadoc
false
parameterizedTypeToString
private static String parameterizedTypeToString(final ParameterizedType parameterizedType) { final StringBuilder builder = new StringBuilder(); final Type useOwner = parameterizedType.getOwnerType(); final Class<?> raw = (Class<?>) parameterizedType.getRawType(); if (useOwner == null) { builder.append(raw.getName()); } else { if (useOwner instanceof Class<?>) { builder.append(((Class<?>) useOwner).getName()); } else { builder.append(useOwner); } builder.append('.').append(raw.getSimpleName()); } final int[] recursiveTypeIndexes = findRecursiveTypes(parameterizedType); if (recursiveTypeIndexes.length > 0) { appendRecursiveTypes(builder, recursiveTypeIndexes, parameterizedType.getActualTypeArguments()); } else { GT_JOINER.join(builder, (Object[]) parameterizedType.getActualTypeArguments()); } return builder.toString(); }
Formats a {@link ParameterizedType} as a {@link String}. @param parameterizedType {@link ParameterizedType} to format. @return String.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
1,413
[ "parameterizedType" ]
String
true
4
7.44
apache/commons-lang
2,896
javadoc
false