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
checkName
String checkName(String name) throws JSONException { if (name == null) { throw new JSONException("Names must be non-null"); } return name; }
Appends {@code value} to the array already mapped to {@code name}. If this object has no mapping for {@code name}, this inserts a new mapping. If the mapping exists but its value is not an array, the existing and new values are inserted in order into a new array which is itself mapped to {@code name}. In aggregate, this allows values to be added to a mapping one at a time. @param name the name of the property @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, Double, {@link #NULL} or null. May not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}. @return this object. @throws JSONException if an error occurs
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
326
[ "name" ]
String
true
2
8.08
spring-projects/spring-boot
79,428
javadoc
false
getShortPathName
public String getShortPathName(String path) { String longPath = "\\\\?\\" + path; // first we get the length of the buffer needed final int length = kernel.GetShortPathNameW(longPath, null, 0); if (length == 0) { logger.warn("failed to get short path name: {}", kernel.GetLastError()); return path; } final char[] shortPath = new char[length]; // knowing the length of the buffer, now we get the short name if (kernel.GetShortPathNameW(longPath, shortPath, length) > 0) { assert shortPath[length - 1] == '\0'; return new String(shortPath, 0, length - 1); } else { logger.warn("failed to get short path name: {}", kernel.GetLastError()); return path; } }
Retrieves the short path form of the specified path. @param path the path @return the short path name, or the original path name if unsupported or unavailable
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/WindowsFunctions.java
34
[ "path" ]
String
true
3
8.4
elastic/elasticsearch
75,680
javadoc
false
kurt
def kurt( self, axis: Axis | None = 0, skipna: bool = True, numeric_only: bool = False, **kwargs, ): """ Return unbiased kurtosis over requested axis. Kurtosis obtained using Fisher's definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters ---------- axis : {index (0)} Axis for the function to be applied on. For `Series` this parameter is unused and defaults to 0. For DataFrames, specifying ``axis=None`` will apply the aggregation across both axes. .. versionadded:: 2.0.0 skipna : bool, default True Exclude NA/null values when computing the result. numeric_only : bool, default False Include only float, int, boolean columns. **kwargs Additional keyword arguments to be passed to the function. Returns ------- scalar Unbiased kurtosis. See Also -------- Series.skew : Return unbiased skew over requested axis. Series.var : Return unbiased variance over requested axis. Series.std : Return unbiased standard deviation over requested axis. Examples -------- >>> s = pd.Series([1, 2, 2, 3], index=["cat", "dog", "dog", "mouse"]) >>> s cat 1 dog 2 dog 2 mouse 3 dtype: int64 >>> s.kurt() 1.5 """ return NDFrame.kurt( self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs )
Return unbiased kurtosis over requested axis. Kurtosis obtained using Fisher's definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters ---------- axis : {index (0)} Axis for the function to be applied on. For `Series` this parameter is unused and defaults to 0. For DataFrames, specifying ``axis=None`` will apply the aggregation across both axes. .. versionadded:: 2.0.0 skipna : bool, default True Exclude NA/null values when computing the result. numeric_only : bool, default False Include only float, int, boolean columns. **kwargs Additional keyword arguments to be passed to the function. Returns ------- scalar Unbiased kurtosis. See Also -------- Series.skew : Return unbiased skew over requested axis. Series.var : Return unbiased variance over requested axis. Series.std : Return unbiased standard deviation over requested axis. Examples -------- >>> s = pd.Series([1, 2, 2, 3], index=["cat", "dog", "dog", "mouse"]) >>> s cat 1 dog 2 dog 2 mouse 3 dtype: int64 >>> s.kurt() 1.5
python
pandas/core/series.py
8,004
[ "self", "axis", "skipna", "numeric_only" ]
true
1
7.12
pandas-dev/pandas
47,362
numpy
false
take
def take( self, indices, axis: Axis = 0, allow_fill: bool = True, fill_value=None, **kwargs, ) -> Self: """ Return a new Index of the values selected by the indices. For internal compatibility with numpy arrays. Parameters ---------- indices : array-like Indices to be taken. axis : {0 or 'index'}, optional The axis over which to select values, always 0 or 'index'. allow_fill : bool, default True How to handle negative values in `indices`. * False: negative values in `indices` indicate positional indices from the right (the default). This is similar to :func:`numpy.take`. * True: negative values in `indices` indicate missing values. These values are set to `fill_value`. Any other negative values raise a ``ValueError``. fill_value : scalar, default None If allow_fill=True and fill_value is not None, indices specified by -1 are regarded as NA. If Index doesn't hold NA, raise ValueError. **kwargs Required for compatibility with numpy. Returns ------- Index An index formed of elements at the given indices. Will be the same type as self, except for RangeIndex. See Also -------- numpy.ndarray.take: Return an array formed from the elements of a at the given indices. Examples -------- >>> idx = pd.Index(["a", "b", "c"]) >>> idx.take([2, 2, 1, 2]) Index(['c', 'c', 'b', 'c'], dtype='str') """ if kwargs: nv.validate_take((), kwargs) if is_scalar(indices): raise TypeError("Expected indices to be array-like") indices = ensure_platform_int(indices) allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices) if indices.ndim == 1 and lib.is_range_indexer(indices, len(self)): return self.copy() # Note: we discard fill_value and use self._na_value, only relevant # in the case where allow_fill is True and fill_value is not None values = self._values if isinstance(values, np.ndarray): taken = algos.take( values, indices, allow_fill=allow_fill, fill_value=self._na_value ) else: # algos.take passes 'axis' keyword which not all EAs accept taken = values.take( indices, allow_fill=allow_fill, fill_value=self._na_value ) return self._constructor._simple_new(taken, name=self.name)
Return a new Index of the values selected by the indices. For internal compatibility with numpy arrays. Parameters ---------- indices : array-like Indices to be taken. axis : {0 or 'index'}, optional The axis over which to select values, always 0 or 'index'. allow_fill : bool, default True How to handle negative values in `indices`. * False: negative values in `indices` indicate positional indices from the right (the default). This is similar to :func:`numpy.take`. * True: negative values in `indices` indicate missing values. These values are set to `fill_value`. Any other negative values raise a ``ValueError``. fill_value : scalar, default None If allow_fill=True and fill_value is not None, indices specified by -1 are regarded as NA. If Index doesn't hold NA, raise ValueError. **kwargs Required for compatibility with numpy. Returns ------- Index An index formed of elements at the given indices. Will be the same type as self, except for RangeIndex. See Also -------- numpy.ndarray.take: Return an array formed from the elements of a at the given indices. Examples -------- >>> idx = pd.Index(["a", "b", "c"]) >>> idx.take([2, 2, 1, 2]) Index(['c', 'c', 'b', 'c'], dtype='str')
python
pandas/core/indexes/base.py
1,229
[ "self", "indices", "axis", "allow_fill", "fill_value" ]
Self
true
7
8.4
pandas-dev/pandas
47,362
numpy
false
forOwn
function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); }
Iterates over own enumerable string keyed properties of an object and invokes `iteratee` for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning `false`. @static @memberOf _ @since 0.3.0 @category Object @param {Object} object The object to iterate over. @param {Function} [iteratee=_.identity] The function invoked per iteration. @returns {Object} Returns `object`. @see _.forOwnRight @example function Foo() { this.a = 1; this.b = 2; } Foo.prototype.c = 3; _.forOwn(new Foo, function(value, key) { console.log(key); }); // => Logs 'a' then 'b' (iteration order is not guaranteed).
javascript
lodash.js
13,120
[ "object", "iteratee" ]
false
2
6.96
lodash/lodash
61,490
jsdoc
false
grid_to_graph
def grid_to_graph( n_x, n_y, n_z=1, *, mask=None, return_as=sparse.coo_matrix, dtype=int ): """Graph of the pixel-to-pixel connections. Edges exist if 2 voxels are connected. Read more in the :ref:`User Guide <connectivity_graph_image>`. Parameters ---------- n_x : int Dimension in x axis. n_y : int Dimension in y axis. n_z : int, default=1 Dimension in z axis. mask : ndarray of shape (n_x, n_y, n_z), dtype=bool, default=None An optional mask of the image, to consider only part of the pixels. return_as : np.ndarray or a sparse matrix class, \ default=sparse.coo_matrix The class to use to build the returned adjacency matrix. dtype : dtype, default=int The data of the returned sparse matrix. By default it is int. Returns ------- graph : np.ndarray or a sparse matrix class The computed adjacency matrix. Examples -------- >>> import numpy as np >>> from sklearn.feature_extraction.image import grid_to_graph >>> shape_img = (4, 4, 1) >>> mask = np.zeros(shape=shape_img, dtype=bool) >>> mask[[1, 2], [1, 2], :] = True >>> graph = grid_to_graph(*shape_img, mask=mask) >>> print(graph) <COOrdinate sparse matrix of dtype 'int64' with 2 stored elements and shape (2, 2)> Coords Values (0, 0) 1 (1, 1) 1 """ return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as, dtype=dtype)
Graph of the pixel-to-pixel connections. Edges exist if 2 voxels are connected. Read more in the :ref:`User Guide <connectivity_graph_image>`. Parameters ---------- n_x : int Dimension in x axis. n_y : int Dimension in y axis. n_z : int, default=1 Dimension in z axis. mask : ndarray of shape (n_x, n_y, n_z), dtype=bool, default=None An optional mask of the image, to consider only part of the pixels. return_as : np.ndarray or a sparse matrix class, \ default=sparse.coo_matrix The class to use to build the returned adjacency matrix. dtype : dtype, default=int The data of the returned sparse matrix. By default it is int. Returns ------- graph : np.ndarray or a sparse matrix class The computed adjacency matrix. Examples -------- >>> import numpy as np >>> from sklearn.feature_extraction.image import grid_to_graph >>> shape_img = (4, 4, 1) >>> mask = np.zeros(shape=shape_img, dtype=bool) >>> mask[[1, 2], [1, 2], :] = True >>> graph = grid_to_graph(*shape_img, mask=mask) >>> print(graph) <COOrdinate sparse matrix of dtype 'int64' with 2 stored elements and shape (2, 2)> Coords Values (0, 0) 1 (1, 1) 1
python
sklearn/feature_extraction/image.py
206
[ "n_x", "n_y", "n_z", "mask", "return_as", "dtype" ]
false
1
6.32
scikit-learn/scikit-learn
64,340
numpy
false
determineCacheOperations
protected @Nullable Collection<CacheOperation> determineCacheOperations(CacheOperationProvider provider) { Collection<CacheOperation> ops = null; for (CacheAnnotationParser parser : this.annotationParsers) { Collection<CacheOperation> annOps = provider.getCacheOperations(parser); if (annOps != null) { if (ops == null) { ops = annOps; } else { Collection<CacheOperation> combined = new ArrayList<>(ops.size() + annOps.size()); combined.addAll(ops); combined.addAll(annOps); ops = combined; } } } return ops; }
Determine the cache operation(s) for the given {@link CacheOperationProvider}. <p>This implementation delegates to configured {@link CacheAnnotationParser CacheAnnotationParsers} for parsing known annotations into Spring's metadata attribute class. <p>Can be overridden to support custom annotations that carry caching metadata. @param provider the cache operation provider to use @return the configured caching operations, or {@code null} if none found
java
spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java
142
[ "provider" ]
true
3
7.44
spring-projects/spring-framework
59,386
javadoc
false
addProcessor
private static void addProcessor(final String key, final Processor processor) { if (ARCH_TO_PROCESSOR.containsKey(key)) { throw new IllegalStateException("Key " + key + " already exists in processor map"); } ARCH_TO_PROCESSOR.put(key, processor); }
Adds the given {@link Processor} with the given key {@link String} to the map. @param key The key as {@link String}. @param processor The {@link Processor} to add. @throws IllegalStateException If the key already exists.
java
src/main/java/org/apache/commons/lang3/ArchUtils.java
49
[ "key", "processor" ]
void
true
2
6.88
apache/commons-lang
2,896
javadoc
false
_refine_color
def _refine_color(color: str): """ Convert color in #RGB (12 bits) format to #RRGGBB (32 bits), if it possible. Otherwise, it returns the original value. Graphviz does not support colors in #RGB format. :param color: Text representation of color :return: Refined representation of color """ if len(color) == 4 and color[0] == "#": color_r = color[1] color_g = color[2] color_b = color[3] return "#" + color_r + color_r + color_g + color_g + color_b + color_b return color
Convert color in #RGB (12 bits) format to #RRGGBB (32 bits), if it possible. Otherwise, it returns the original value. Graphviz does not support colors in #RGB format. :param color: Text representation of color :return: Refined representation of color
python
airflow-core/src/airflow/utils/dot_renderer.py
55
[ "color" ]
true
3
8.24
apache/airflow
43,597
sphinx
false
match_einsum_strings
def match_einsum_strings(s: str) -> bool: """ This function takes a string s as input, where s is in the format "3 letter string, 4 letter string -> 3 letter string". It checks if the strings match the rule and returns True if they do, False otherwise. The rule is: - The three strings have the same first two characters. - The first two strings have the same third character. - The second and third strings have the same last character. """ # Split the input string into parts parts = s.replace("->", ",").split(",") # Strip leading/trailing whitespaces from each part parts = [part.strip() for part in parts] # Check if we have exactly three parts if len(parts) != 3: return False # Extract the strings s1, s2, s3 = parts # Check if the strings have the correct lengths if len(s1) != 3 or len(s2) != 4 or len(s3) != 3: return False # Check the rule return s1[:2] == s2[:2] == s3[:2] and s1[2] == s2[2] and s2[3] == s3[2]
This function takes a string s as input, where s is in the format "3 letter string, 4 letter string -> 3 letter string". It checks if the strings match the rule and returns True if they do, False otherwise. The rule is: - The three strings have the same first two characters. - The first two strings have the same third character. - The second and third strings have the same last character.
python
torch/_inductor/fx_passes/split_cat.py
2,983
[ "s" ]
bool
true
7
6
pytorch/pytorch
96,034
unknown
false
getContentEntry
private ZipContent.Entry getContentEntry(String namePrefix, String name) { synchronized (this) { ensureOpen(); return this.resources.zipContent().getEntry(namePrefix, name); } }
Return if an entry with the given name exists. @param name the name to check @return if the entry exists
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/NestedJarFile.java
293
[ "namePrefix", "name" ]
true
1
6.88
spring-projects/spring-boot
79,428
javadoc
false
close
@Override public void close() { SchedulerEngine engine = scheduler.get(); if (engine != null) { engine.stop(); } logger.trace("Clearing the error store as we are closing"); errorStore.clearStore(); }
Initializer method to avoid the publication of a self reference in the constructor.
java
modules/data-streams/src/main/java/org/elasticsearch/datastreams/lifecycle/DataStreamLifecycleService.java
292
[]
void
true
2
6.72
elastic/elasticsearch
75,680
javadoc
false
getStopTime
@Deprecated public long getStopTime() { // stopTimeNanos stores System.nanoTime() for elapsed time return getStopInstant().toEpochMilli(); }
Gets the time this StopWatch was stopped in milliseconds, between the current time and midnight, January 1, 1970 UTC. @return the time this StopWatch was stopped in milliseconds, between the current time and midnight, January 1, 1970 UTC. @throws IllegalStateException if this StopWatch has not been started. @since 3.12.0 @deprecated Use {@link #getStopInstant()}.
java
src/main/java/org/apache/commons/lang3/time/StopWatch.java
519
[]
true
1
6.88
apache/commons-lang
2,896
javadoc
false
format_percentiles
def format_percentiles( percentiles: np.ndarray | Sequence[float], ) -> list[str]: """ Outputs rounded and formatted percentiles. Parameters ---------- percentiles : list-like, containing floats from interval [0,1] Returns ------- formatted : list of strings Notes ----- Rounding precision is chosen so that: (1) if any two elements of ``percentiles`` differ, they remain different after rounding (2) no entry is *rounded* to 0% or 100%. Any non-integer is always rounded to at least 1 decimal place. Examples -------- Keeps all entries different after rounding: >>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) ['1.999%', '2.001%', '50%', '66.667%', '99.99%'] No element is rounded to 0% or 100% (unless already equal to it). Duplicates are allowed: >>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] """ if len(percentiles) == 0: return [] percentiles = np.asarray(percentiles) # It checks for np.nan as well if ( not is_numeric_dtype(percentiles) or not np.all(percentiles >= 0) or not np.all(percentiles <= 1) ): raise ValueError("percentiles should all be in the interval [0,1]") percentiles = 100 * percentiles prec = get_precision(percentiles) percentiles_round_type = percentiles.round(prec).astype(int) int_idx = np.isclose(percentiles_round_type, percentiles) if np.all(int_idx): out = percentiles_round_type.astype(str) return [i + "%" for i in out] unique_pcts = np.unique(percentiles) prec = get_precision(unique_pcts) out = np.empty_like(percentiles, dtype=object) out[int_idx] = percentiles[int_idx].round().astype(int).astype(str) out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) return [i + "%" for i in out]
Outputs rounded and formatted percentiles. Parameters ---------- percentiles : list-like, containing floats from interval [0,1] Returns ------- formatted : list of strings Notes ----- Rounding precision is chosen so that: (1) if any two elements of ``percentiles`` differ, they remain different after rounding (2) no entry is *rounded* to 0% or 100%. Any non-integer is always rounded to at least 1 decimal place. Examples -------- Keeps all entries different after rounding: >>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) ['1.999%', '2.001%', '50%', '66.667%', '99.99%'] No element is rounded to 0% or 100% (unless already equal to it). Duplicates are allowed: >>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%']
python
pandas/io/formats/format.py
1,554
[ "percentiles" ]
list[str]
true
6
8.48
pandas-dev/pandas
47,362
numpy
false
getRootSource
private static PropertySource<?> getRootSource(PropertySource<?> source) { while (source.getSource() instanceof PropertySource<?> propertySource) { source = propertySource; } return source; }
Create a new {@link SpringConfigurationPropertySource} for the specified {@link PropertySource}. @param source the source Spring {@link PropertySource} @return a {@link SpringConfigurationPropertySource} or {@link SpringIterableConfigurationPropertySource} instance
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java
202
[ "source" ]
true
2
7.12
spring-projects/spring-boot
79,428
javadoc
false
op_list
def op_list(**configs): """Generate a list of ops organized in a specific format. It takes two parameters which are "attr_names" and "attr". attrs stores the name and function of operators. Args: configs: key-value pairs including the name and function of operators. attrs and attr_names must be present in configs. Return: a sequence of dictionaries which stores the name and function of ops in a specifal format Example: attrs = [ ["abs", torch.abs], ["abs_", torch.abs_], ] attr_names = ["op_name", "op"]. With those two examples, we will generate (({"op_name": "abs"}, {"op" : torch.abs}), ({"op_name": "abs_"}, {"op" : torch.abs_})) """ generated_configs = [] if "attrs" not in configs: raise ValueError("Missing attrs in configs") for inputs in configs["attrs"]: tmp_result = { configs["attr_names"][i]: input_value for i, input_value in enumerate(inputs) } generated_configs.append(tmp_result) return generated_configs
Generate a list of ops organized in a specific format. It takes two parameters which are "attr_names" and "attr". attrs stores the name and function of operators. Args: configs: key-value pairs including the name and function of operators. attrs and attr_names must be present in configs. Return: a sequence of dictionaries which stores the name and function of ops in a specifal format Example: attrs = [ ["abs", torch.abs], ["abs_", torch.abs_], ] attr_names = ["op_name", "op"]. With those two examples, we will generate (({"op_name": "abs"}, {"op" : torch.abs}), ({"op_name": "abs_"}, {"op" : torch.abs_}))
python
benchmarks/operator_benchmark/benchmark_utils.py
289
[]
false
3
8.72
pytorch/pytorch
96,034
google
false
mapTypeVariablesToArguments
private static <T> void mapTypeVariablesToArguments(final Class<T> cls, final ParameterizedType parameterizedType, final Map<TypeVariable<?>, Type> typeVarAssigns) { // capture the type variables from the owner type that have assignments final Type ownerType = parameterizedType.getOwnerType(); if (ownerType instanceof ParameterizedType) { // recursion to make sure the owner's owner type gets processed mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns); } // parameterizedType is a generic interface/class (or it's in the owner // hierarchy of said interface/class) implemented/extended by the class // cls. Find out which type variables of cls are type arguments of // parameterizedType: final Type[] typeArgs = parameterizedType.getActualTypeArguments(); // of the cls's type variables that are arguments of parameterizedType, // find out which ones can be determined from the super type's arguments final TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters(); // use List view of type parameters of cls so the contains() method can be used: final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls.getTypeParameters()); for (int i = 0; i < typeArgs.length; i++) { final TypeVariable<?> typeVar = typeVars[i]; final Type typeArg = typeArgs[i]; // argument of parameterizedType is a type variable of cls if (typeVarList.contains(typeArg) // type variable of parameterizedType has an assignment in // the super type. && typeVarAssigns.containsKey(typeVar)) { // map the assignment to the cls's type variable typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar)); } } }
Maps type variables. @param <T> the generic type of the class in question. @param cls the class in question. @param parameterizedType the parameterized type. @param typeVarAssigns the map to be filled.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
1,290
[ "cls", "parameterizedType", "typeVarAssigns" ]
void
true
5
7.04
apache/commons-lang
2,896
javadoc
false
_graph_connected_component
def _graph_connected_component(graph, node_id): """Find the largest graph connected components that contains one given node. Parameters ---------- graph : array-like of shape (n_samples, n_samples) Adjacency matrix of the graph, non-zero weight means an edge between the nodes. node_id : int The index of the query node of the graph. Returns ------- connected_components_matrix : array-like of shape (n_samples,) An array of bool value indicating the indexes of the nodes belonging to the largest connected components of the given query node. """ n_node = graph.shape[0] if sparse.issparse(graph): # speed up row-wise access to boolean connection mask graph = graph.tocsr() connected_nodes = np.zeros(n_node, dtype=bool) nodes_to_explore = np.zeros(n_node, dtype=bool) nodes_to_explore[node_id] = True for _ in range(n_node): last_num_component = connected_nodes.sum() np.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes) if last_num_component >= connected_nodes.sum(): break indices = np.where(nodes_to_explore)[0] nodes_to_explore.fill(False) for i in indices: if sparse.issparse(graph): # scipy not yet implemented 1D sparse slices; can be changed back to # `neighbors = graph[i].toarray().ravel()` once implemented neighbors = graph[[i], :].toarray().ravel() else: neighbors = graph[i] np.logical_or(nodes_to_explore, neighbors, out=nodes_to_explore) return connected_nodes
Find the largest graph connected components that contains one given node. Parameters ---------- graph : array-like of shape (n_samples, n_samples) Adjacency matrix of the graph, non-zero weight means an edge between the nodes. node_id : int The index of the query node of the graph. Returns ------- connected_components_matrix : array-like of shape (n_samples,) An array of bool value indicating the indexes of the nodes belonging to the largest connected components of the given query node.
python
sklearn/manifold/_spectral_embedding.py
27
[ "graph", "node_id" ]
false
7
6.08
scikit-learn/scikit-learn
64,340
numpy
false
__init__
def __init__(self, x=None, y=None, z=None, srid=None): """ The Point object may be initialized with either a tuple, or individual parameters. For example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed as individual parameters """ if x is None: coords = [] elif isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. coords = x elif isinstance(x, (float, int)) and isinstance(y, (float, int)): # Here X, Y, and (optionally) Z were passed in individually, as # parameters. if isinstance(z, (float, int)): coords = [x, y, z] else: coords = [x, y] else: raise TypeError("Invalid parameters given for Point initialization.") point = self._create_point(len(coords), coords) # Initializing using the address returned from the GEOS # createPoint factory. super().__init__(point, srid=srid)
The Point object may be initialized with either a tuple, or individual parameters. For example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed as individual parameters
python
django/contrib/gis/geos/point.py
14
[ "self", "x", "y", "z", "srid" ]
false
8
6.64
django/django
86,204
unknown
false
checkNotZip64Extended
private void checkNotZip64Extended(long value) throws IOException { if (value == 0xFFFFFFFF) { throw new IOException("Zip64 extended information extra fields are not supported"); } }
Open a {@link DataBlock} providing access to raw contents of the entry (not including the local file header). <p> To release resources, the {@link #close()} method of the data block should be called explicitly or by try-with-resources. @return the contents of the entry @throws IOException on I/O error
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java
812
[ "value" ]
void
true
2
6.56
spring-projects/spring-boot
79,428
javadoc
false
getResource
@Override public @Nullable URL getResource(String name) { Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized"); Resource resource = this.resourceLoader.getResource(name); if (resource.exists()) { try { return resource.getURL(); } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not load " + resource); } return null; } } else { return getClassLoader().getResource(name); } }
Create a new ResourceLoaderClassLoadHelper for the given ResourceLoader. @param resourceLoader the ResourceLoader to delegate to
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/ResourceLoaderClassLoadHelper.java
89
[ "name" ]
URL
true
4
6.08
spring-projects/spring-framework
59,386
javadoc
false
dot7uBulk
private static void dot7uBulk(MemorySegment a, MemorySegment b, int length, int count, MemorySegment result) { try { JdkVectorLibrary.dot7uBulk$mh.invokeExact(a, b, length, count, result); } catch (Throwable t) { throw new AssertionError(t); } }
Computes the square distance of given float32 vectors. @param a address of the first vector @param b address of the second vector @param elementCount the vector dimensions, number of float32 elements in the segment
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/jdk/JdkVectorLibrary.java
299
[ "a", "b", "length", "count", "result" ]
void
true
2
6.56
elastic/elasticsearch
75,680
javadoc
false
lazyWeakCustom
static <L> Striped<L> lazyWeakCustom(int stripes, Supplier<L> supplier) { return stripes < LARGE_LAZY_CUTOFF ? new SmallLazyStriped<L>(stripes, supplier) : new LargeLazyStriped<L>(stripes, supplier); }
Creates a {@code Striped<L>} with lazily initialized, weakly referenced locks. Every lock is obtained from the passed supplier. @param stripes the minimum number of stripes (locks) required @param supplier a {@code Supplier<L>} object to obtain locks from @return a new {@code Striped<L>}
java
android/guava/src/com/google/common/util/concurrent/Striped.java
231
[ "stripes", "supplier" ]
true
2
8.08
google/guava
51,352
javadoc
false
_managle_lambda_list
def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]: """ Possibly mangle a list of aggfuncs. Parameters ---------- aggfuncs : Sequence Returns ------- mangled: list-like A new AggSpec sequence, where lambdas have been converted to have unique names. Notes ----- If just one aggfunc is passed, the name will not be mangled. """ if len(aggfuncs) <= 1: # don't mangle for .agg([lambda x: .]) return aggfuncs i = 0 mangled_aggfuncs = [] for aggfunc in aggfuncs: if com.get_callable_name(aggfunc) == "<lambda>": aggfunc = partial(aggfunc) # error: "partial[Any]" has no attribute "__name__"; maybe "__new__"? aggfunc.__name__ = f"<lambda_{i}>" # type: ignore[attr-defined] i += 1 mangled_aggfuncs.append(aggfunc) return mangled_aggfuncs
Possibly mangle a list of aggfuncs. Parameters ---------- aggfuncs : Sequence Returns ------- mangled: list-like A new AggSpec sequence, where lambdas have been converted to have unique names. Notes ----- If just one aggfunc is passed, the name will not be mangled.
python
pandas/core/apply.py
2,015
[ "aggfuncs" ]
Sequence[Any]
true
4
6.88
pandas-dev/pandas
47,362
numpy
false
nanprod
def nanprod( values: np.ndarray, *, axis: AxisInt | None = None, skipna: bool = True, min_count: int = 0, mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Parameters ---------- values : ndarray[dtype] axis : int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known Returns ------- Dtype The product of all elements on a given axis. ( NaNs are treated as 1) Examples -------- >>> from pandas.core import nanops >>> s = pd.Series([1, 2, 3, np.nan]) >>> nanops.nanprod(s.values) np.float64(6.0) """ mask = _maybe_get_mask(values, skipna, mask) if skipna and mask is not None: values = values.copy() values[mask] = 1 result = values.prod(axis) # error: Incompatible return value type (got "Union[ndarray, float]", expected # "float") return _maybe_null_out( # type: ignore[return-value] result, axis, mask, values.shape, min_count=min_count )
Parameters ---------- values : ndarray[dtype] axis : int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known Returns ------- Dtype The product of all elements on a given axis. ( NaNs are treated as 1) Examples -------- >>> from pandas.core import nanops >>> s = pd.Series([1, 2, 3, np.nan]) >>> nanops.nanprod(s.values) np.float64(6.0)
python
pandas/core/nanops.py
1,422
[ "values", "axis", "skipna", "min_count", "mask" ]
float
true
3
8.16
pandas-dev/pandas
47,362
numpy
false
_get_i8_values_and_mask
def _get_i8_values_and_mask( self, other ) -> tuple[int | npt.NDArray[np.int64], None | npt.NDArray[np.bool_]]: """ Get the int64 values and b_mask to pass to add_overflowsafe. """ if isinstance(other, Period): i8values = other.ordinal mask = None elif isinstance(other, (Timestamp, Timedelta)): i8values = other._value mask = None else: # PeriodArray, DatetimeArray, TimedeltaArray mask = other._isnan i8values = other.asi8 return i8values, mask
Get the int64 values and b_mask to pass to add_overflowsafe.
python
pandas/core/arrays/datetimelike.py
1,050
[ "self", "other" ]
tuple[int | npt.NDArray[np.int64], None | npt.NDArray[np.bool_]]
true
4
6
pandas-dev/pandas
47,362
unknown
false
has_job
def has_job(self, job_name: str) -> bool: """ Check if the job already exists. .. seealso:: - :external+boto3:py:meth:`Glue.Client.get_job` :param job_name: unique job name per AWS account :return: Returns True if the job already exists and False if not. """ self.log.info("Checking if job already exists: %s", job_name) try: self.conn.get_job(JobName=job_name) return True except self.conn.exceptions.EntityNotFoundException: return False
Check if the job already exists. .. seealso:: - :external+boto3:py:meth:`Glue.Client.get_job` :param job_name: unique job name per AWS account :return: Returns True if the job already exists and False if not.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/glue.py
445
[ "self", "job_name" ]
bool
true
1
6.72
apache/airflow
43,597
sphinx
false
squeeze
def squeeze(self, axis=None): """ Return a possibly reshaped matrix. Refer to `numpy.squeeze` for more documentation. Parameters ---------- axis : None or int or tuple of ints, optional Selects a subset of the axes of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. Returns ------- squeezed : matrix The matrix, but as a (1, N) matrix if it had shape (N, 1). See Also -------- numpy.squeeze : related function Notes ----- If `m` has a single column then that column is returned as the single row of a matrix. Otherwise `m` is returned. The returned matrix is always either `m` itself or a view into `m`. Supplying an axis keyword argument will not affect the returned matrix but it may cause an error to be raised. Examples -------- >>> c = np.matrix([[1], [2]]) >>> c matrix([[1], [2]]) >>> c.squeeze() matrix([[1, 2]]) >>> r = c.T >>> r matrix([[1, 2]]) >>> r.squeeze() matrix([[1, 2]]) >>> m = np.matrix([[1, 2], [3, 4]]) >>> m.squeeze() matrix([[1, 2], [3, 4]]) """ return N.ndarray.squeeze(self, axis=axis)
Return a possibly reshaped matrix. Refer to `numpy.squeeze` for more documentation. Parameters ---------- axis : None or int or tuple of ints, optional Selects a subset of the axes of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. Returns ------- squeezed : matrix The matrix, but as a (1, N) matrix if it had shape (N, 1). See Also -------- numpy.squeeze : related function Notes ----- If `m` has a single column then that column is returned as the single row of a matrix. Otherwise `m` is returned. The returned matrix is always either `m` itself or a view into `m`. Supplying an axis keyword argument will not affect the returned matrix but it may cause an error to be raised. Examples -------- >>> c = np.matrix([[1], [2]]) >>> c matrix([[1], [2]]) >>> c.squeeze() matrix([[1, 2]]) >>> r = c.T >>> r matrix([[1, 2]]) >>> r.squeeze() matrix([[1, 2]]) >>> m = np.matrix([[1, 2], [3, 4]]) >>> m.squeeze() matrix([[1, 2], [3, 4]])
python
numpy/matrixlib/defmatrix.py
330
[ "self", "axis" ]
false
1
6.48
numpy/numpy
31,054
numpy
false
backend_fails
def backend_fails( gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_fn: CompilerFn, orig_failure: Sequence[Any], ) -> bool: """ Minifier uses this function to identify if the minified graph module fails with the same error. One caveat is that minifier can potentially go into a wrong direction when the resulting graph module fails for a different reason. To avoid this, we save the string for the original exception and check similarity between new and old exception. They can be somewhat different in some cases, when the exception string depends on the failing node information. So, we have a loose similarity metric to guide the minifier path. """ from difflib import SequenceMatcher try: # Run the original gm to check eager validity run_fwd_maybe_bwd(gm, clone_inputs_retaining_gradness(example_inputs)) compiled_gm = compiler_fn(gm, example_inputs) # type: ignore[arg-type] run_fwd_maybe_bwd(compiled_gm, clone_inputs_retaining_gradness(example_inputs)) # type: ignore[arg-type] except Exception as e: new_failure = str(e) if SequenceMatcher(None, orig_failure, new_failure).ratio() > 0.5: return True return False
Minifier uses this function to identify if the minified graph module fails with the same error. One caveat is that minifier can potentially go into a wrong direction when the resulting graph module fails for a different reason. To avoid this, we save the string for the original exception and check similarity between new and old exception. They can be somewhat different in some cases, when the exception string depends on the failing node information. So, we have a loose similarity metric to guide the minifier path.
python
torch/_dynamo/repro/after_dynamo.py
391
[ "gm", "example_inputs", "compiler_fn", "orig_failure" ]
bool
true
2
6
pytorch/pytorch
96,034
unknown
false
hydrationStatus
function hydrationStatus(element: Node): HydrationStatus { if (!(element instanceof Element)) { return null; } if (!!element.getAttribute('ngh')) { return {status: 'dehydrated'}; } const hydrationInfo = (element as HydrationNode).__ngDebugHydrationInfo__; switch (hydrationInfo?.status) { case 'hydrated': return {status: 'hydrated'}; case 'skipped': return {status: 'skipped'}; case 'mismatched': return { status: 'mismatched', expectedNodeDetails: hydrationInfo.expectedNodeDetails, actualNodeDetails: hydrationInfo.actualNodeDetails, }; default: return null; } }
Group Nodes under a defer block if they are part of it. @param node @param deferredNodesToSkip Will mutate the set with the nodes that are grouped into the created deferblock. @param deferBlocks @param appendTo @param getComponent @param getDirectives @param getDirectiveMetadata
typescript
devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.ts
173
[ "element" ]
true
3
6.4
angular/angular
99,544
jsdoc
false
iter_encode
def iter_encode(self, obj): '''The iterative version of `arff.ArffEncoder.encode`. This encodes iteratively a given object and return, one-by-one, the lines of the ARFF file. :param obj: the object containing the ARFF information. :return: (yields) the ARFF file as strings. ''' # DESCRIPTION if obj.get('description', None): for row in obj['description'].split('\n'): yield self._encode_comment(row) # RELATION if not obj.get('relation'): raise BadObject('Relation name not found or with invalid value.') yield self._encode_relation(obj['relation']) yield '' # ATTRIBUTES if not obj.get('attributes'): raise BadObject('Attributes not found.') attribute_names = set() for attr in obj['attributes']: # Verify for bad object format if not isinstance(attr, (tuple, list)) or \ len(attr) != 2 or \ not isinstance(attr[0], str): raise BadObject('Invalid attribute declaration "%s"'%str(attr)) if isinstance(attr[1], str): # Verify for invalid types if attr[1] not in _SIMPLE_TYPES: raise BadObject('Invalid attribute type "%s"'%str(attr)) # Verify for bad object format elif not isinstance(attr[1], (tuple, list)): raise BadObject('Invalid attribute type "%s"'%str(attr)) # Verify attribute name is not used twice if attr[0] in attribute_names: raise BadObject('Trying to use attribute name "%s" for the ' 'second time.' % str(attr[0])) else: attribute_names.add(attr[0]) yield self._encode_attribute(attr[0], attr[1]) yield '' attributes = obj['attributes'] # DATA yield _TK_DATA if 'data' in obj: data = _get_data_object_for_encoding(obj.get('data')) yield from data.encode_data(obj.get('data'), attributes) yield ''
The iterative version of `arff.ArffEncoder.encode`. This encodes iteratively a given object and return, one-by-one, the lines of the ARFF file. :param obj: the object containing the ARFF information. :return: (yields) the ARFF file as strings.
python
sklearn/externals/_arff.py
981
[ "self", "obj" ]
false
15
7.28
scikit-learn/scikit-learn
64,340
sphinx
false
handshakeUnwrap
SSLEngineResult handshakeUnwrap(boolean doRead, boolean ignoreHandshakeStatus) throws IOException { log.trace("SSLHandshake handshakeUnwrap {}", channelId); SSLEngineResult result; int read = 0; if (doRead) read = readFromSocketChannel(); boolean cont; do { //prepare the buffer with the incoming data int position = netReadBuffer.position(); netReadBuffer.flip(); result = sslEngine.unwrap(netReadBuffer, appReadBuffer); netReadBuffer.compact(); handshakeStatus = result.getHandshakeStatus(); if (result.getStatus() == SSLEngineResult.Status.OK && result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { handshakeStatus = runDelegatedTasks(); } cont = (result.getStatus() == SSLEngineResult.Status.OK && handshakeStatus == HandshakeStatus.NEED_UNWRAP) || (ignoreHandshakeStatus && netReadBuffer.position() != position); log.trace("SSLHandshake handshakeUnwrap: handshakeStatus {} status {}", handshakeStatus, result.getStatus()); } while (cont); // Throw EOF exception for failed read after processing already received data // so that handshake failures are reported correctly if (read == -1) throw new EOFException("EOF during handshake, handshake status is " + handshakeStatus); return result; }
Perform handshake unwrap. Visible for testing. @param doRead boolean If true, read more from the socket channel @param ignoreHandshakeStatus If true, continue to unwrap if data available regardless of handshake status @return SSLEngineResult @throws IOException
java
clients/src/main/java/org/apache/kafka/common/network/SslTransportLayer.java
517
[ "doRead", "ignoreHandshakeStatus" ]
SSLEngineResult
true
8
7.44
apache/kafka
31,560
javadoc
false
reverse
function reverse(array) { return array == null ? array : nativeReverse.call(array); }
Reverses `array` so that the first element becomes the last, the second element becomes the second to last, and so on. **Note:** This method mutates `array` and is based on [`Array#reverse`](https://mdn.io/Array/reverse). @static @memberOf _ @since 4.0.0 @category Array @param {Array} array The array to modify. @returns {Array} Returns `array`. @example var array = [1, 2, 3]; _.reverse(array); // => [3, 2, 1] console.log(array); // => [3, 2, 1]
javascript
lodash.js
7,994
[ "array" ]
false
2
7.44
lodash/lodash
61,490
jsdoc
false
exists
function exists(path, callback) { validateFunction(callback, 'cb'); function suppressedCallback(err) { callback(!err); } try { fs.access(path, F_OK, suppressedCallback); } catch { return callback(false); } }
Tests whether or not the given path exists. @param {string | Buffer | URL} path @param {(exists?: boolean) => any} callback @returns {void}
javascript
lib/fs.js
246
[ "path", "callback" ]
false
2
6.24
nodejs/node
114,839
jsdoc
false
__getitem__
def __getitem__(self, key: int | slice) -> Series: """ Index or slice lists in the Series. Parameters ---------- key : int | slice Index or slice of indices to access from each list. Returns ------- pandas.Series The list at requested index. See Also -------- ListAccessor.flatten : Flatten list values. Examples -------- >>> import pyarrow as pa >>> s = pd.Series( ... [ ... [1, 2, 3], ... [3], ... ], ... dtype=pd.ArrowDtype(pa.list_(pa.int64())), ... ) >>> s.list[0] 0 1 1 3 dtype: int64[pyarrow] """ from pandas import Series if isinstance(key, int): # TODO: Support negative key but pyarrow does not allow # element index to be an array. # if key < 0: # key = pc.add(key, pc.list_value_length(self._pa_array)) element = pc.list_element(self._pa_array, key) return Series( element, dtype=ArrowDtype(element.type), index=self._data.index, name=self._data.name, ) elif isinstance(key, slice): # TODO: Support negative start/stop/step, ideally this would be added # upstream in pyarrow. start, stop, step = key.start, key.stop, key.step if start is None: # TODO: When adding negative step support # this should be setto last element of array # when step is negative. start = 0 if step is None: step = 1 sliced = pc.list_slice(self._pa_array, start, stop, step) return Series( sliced, dtype=ArrowDtype(sliced.type), index=self._data.index, name=self._data.name, ) else: raise ValueError(f"key must be an int or slice, got {type(key).__name__}")
Index or slice lists in the Series. Parameters ---------- key : int | slice Index or slice of indices to access from each list. Returns ------- pandas.Series The list at requested index. See Also -------- ListAccessor.flatten : Flatten list values. Examples -------- >>> import pyarrow as pa >>> s = pd.Series( ... [ ... [1, 2, 3], ... [3], ... ], ... dtype=pd.ArrowDtype(pa.list_(pa.int64())), ... ) >>> s.list[0] 0 1 1 3 dtype: int64[pyarrow]
python
pandas/core/arrays/arrow/accessors.py
123
[ "self", "key" ]
Series
true
6
8.56
pandas-dev/pandas
47,362
numpy
false
equals
@Override public boolean equals(final Object obj) { if (!(obj instanceof FastDateParser)) { return false; } final FastDateParser other = (FastDateParser) obj; return pattern.equals(other.pattern) && timeZone.equals(other.timeZone) && locale.equals(other.locale); }
Compares another object for equality with this object. @param obj the object to compare to @return {@code true}if equal to this instance
java
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
874
[ "obj" ]
true
4
8.24
apache/commons-lang
2,896
javadoc
false
retainAll
@CanIgnoreReturnValue public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); }
Removes, from an iterable, every element that does not belong to the provided collection. <p>This method calls {@link Collection#retainAll} if {@code iterable} is a collection, and {@link Iterators#retainAll} otherwise. @param removeFrom the iterable to (potentially) remove elements from @param elementsToRetain the elements to retain @return {@code true} if any element was removed from {@code iterable}
java
android/guava/src/com/google/common/collect/Iterables.java
164
[ "removeFrom", "elementsToRetain" ]
true
2
7.28
google/guava
51,352
javadoc
false
getRegistrationPaths
private Set<Path> getRegistrationPaths(Set<Path> paths) throws IOException { Set<Path> result = new HashSet<>(); for (Path path : paths) { collectRegistrationPaths(path, result); } return Collections.unmodifiableSet(result); }
Retrieves all {@link Path Paths} that should be registered for the specified {@link Path}. If the path is a symlink, changes to the symlink should be monitored, not just the file it points to. For example, for the given {@code keystore.jks} path in the following directory structure:<pre> +- stores | +─ keystore.jks +- <em>data</em> -&gt; stores +─ <em>keystore.jks</em> -&gt; data/keystore.jks </pre> the resulting paths would include: <p> <ul> <li>{@code keystore.jks}</li> <li>{@code data/keystore.jks}</li> <li>{@code data}</li> <li>{@code stores/keystore.jks}</li> </ul> @param paths the source paths @return all possible {@link Path} instances to be registered @throws IOException if an I/O error occurs
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ssl/FileWatcher.java
119
[ "paths" ]
true
1
6.56
spring-projects/spring-boot
79,428
javadoc
false
compressedIterator
private CloseableIterator<Record> compressedIterator(BufferSupplier bufferSupplier, boolean skipKeyValue) { final InputStream inputStream = recordInputStream(bufferSupplier); if (skipKeyValue) { return new StreamRecordIterator(inputStream) { @Override protected Record doReadRecord(long baseOffset, long baseTimestamp, int baseSequence, Long logAppendTime) throws IOException { return DefaultRecord.readPartiallyFrom(inputStream, baseOffset, baseTimestamp, baseSequence, logAppendTime); } }; } else { return new StreamRecordIterator(inputStream) { @Override protected Record doReadRecord(long baseOffset, long baseTimestamp, int baseSequence, Long logAppendTime) throws IOException { return DefaultRecord.readFrom(inputStream, baseOffset, baseTimestamp, baseSequence, logAppendTime); } }; } }
Gets the base timestamp of the batch which is used to calculate the record timestamps from the deltas. @return The base timestamp
java
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
278
[ "bufferSupplier", "skipKeyValue" ]
true
2
6.88
apache/kafka
31,560
javadoc
false
exception
public RuntimeException exception() { if (!failed()) throw new IllegalStateException("Attempt to retrieve exception from future which hasn't failed"); return (RuntimeException) result.get(); }
Get the exception from a failed result (only available if the request failed) @return the exception set in {@link #raise(RuntimeException)} @throws IllegalStateException if the future is not complete or completed successfully
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestFuture.java
109
[]
RuntimeException
true
2
6.8
apache/kafka
31,560
javadoc
false
get_results
def get_results( cls, choices: list[ChoiceCaller], inputs_key: str ) -> dict[ChoiceCaller, float]: """ Get autotuning results, blocking until complete. Args: timeout: Maximum time to wait in seconds. None means wait forever. Returns: Dict mapping ChoiceCaller to benchmark timing """ timings = {} for choice in choices: choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key) timings[choice] = AsyncAutotuner.choice_hash_to_future[choice_hash].result() return timings
Get autotuning results, blocking until complete. Args: timeout: Maximum time to wait in seconds. None means wait forever. Returns: Dict mapping ChoiceCaller to benchmark timing
python
torch/_inductor/autotune_process.py
1,291
[ "cls", "choices", "inputs_key" ]
dict[ChoiceCaller, float]
true
2
7.6
pytorch/pytorch
96,034
google
false
southPolarH3
public static long southPolarH3(int res) { checkResolution(res); return SOUTH[res]; }
Find the h3 index containing the South Pole at the given resolution. @param res the provided resolution. @return the h3 index containing the South Pole.
java
libs/h3/src/main/java/org/elasticsearch/h3/H3.java
561
[ "res" ]
true
1
6.96
elastic/elasticsearch
75,680
javadoc
false
close
private static void close(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext closable) { closable.close(); } }
Perform the given action with the given {@link SpringApplicationHook} attached if the action triggers an {@link SpringApplication#run(String...) application run}. @param <T> the result type @param hook the hook to apply @param action the action to run @return the result of the action @since 3.0.0 @see #withHook(SpringApplicationHook, Runnable)
java
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
1,472
[ "context" ]
void
true
2
7.6
spring-projects/spring-boot
79,428
javadoc
false
getActualIndentationForNode
function getActualIndentationForNode(current: Node, parent: Node, currentLineAndChar: LineAndCharacter, parentAndChildShareLine: boolean, sourceFile: SourceFile, options: EditorSettings): number { // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent.kind === SyntaxKind.SourceFile || !parentAndChildShareLine); if (!useActualIndentation) { return Value.Unknown; } return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); }
@param assumeNewLineBeforeCloseBrace `false` when called on text from a real source file. `true` when we need to assume `position` is on a newline. This is useful for codefixes. Consider ``` function f() { |} ``` with `position` at `|`. When inserting some text after an open brace, we would like to get indentation as if a newline was already there. By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior.
typescript
src/services/formatting/smartIndenter.ts
345
[ "current", "parent", "currentLineAndChar", "parentAndChildShareLine", "sourceFile", "options" ]
true
5
8.48
microsoft/TypeScript
107,154
jsdoc
false
newHashMapWithExpectedSize
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) { return new HashMap<>(capacity(expectedSize)); }
Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method isn't inadvertently <i>oversizing</i> the returned map. @param expectedSize the number of entries you expect to add to the returned map @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries without resizing @throws IllegalArgumentException if {@code expectedSize} is negative
java
android/guava/src/com/google/common/collect/Maps.java
248
[ "expectedSize" ]
true
1
6.56
google/guava
51,352
javadoc
false
requestUpdate
public synchronized int requestUpdate(final boolean resetEquivalentResponseBackoff) { this.needFullUpdate = true; if (resetEquivalentResponseBackoff) { this.equivalentResponseCount = 0; } return this.updateVersion; }
Request an update of the current cluster metadata info, permitting backoff based on the number of equivalent metadata responses, which indicates that responses did not make progress and may be stale. @param resetEquivalentResponseBackoff Whether to reset backing off based on consecutive equivalent responses. This should be set to <i>false</i> in situations where the update is being requested to retry an operation, such as when the leader has changed. It should be set to <i>true</i> in situations where new metadata is being requested, such as adding a topic to a subscription. In situations where it's not clear, it's best to use <i>true</i>. @return The current updateVersion before the update
java
clients/src/main/java/org/apache/kafka/clients/Metadata.java
200
[ "resetEquivalentResponseBackoff" ]
true
2
7.92
apache/kafka
31,560
javadoc
false
resolve
public @Nullable AutowiredArguments resolve(RegisteredBean registeredBean) { Assert.notNull(registeredBean, "'registeredBean' must not be null"); return resolveArguments(registeredBean, getMethod(registeredBean)); }
Resolve the method arguments for the specified registered bean. @param registeredBean the registered bean @return the resolved method arguments
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolver.java
134
[ "registeredBean" ]
AutowiredArguments
true
1
6
spring-projects/spring-framework
59,386
javadoc
false
initialize
protected void initialize(ConfigurableEnvironment environment, ClassLoader classLoader) { getLoggingSystemProperties(environment).apply(); this.logFile = LogFile.get(environment); if (this.logFile != null) { this.logFile.applyToSystemProperties(); } this.loggerGroups = new LoggerGroups(DEFAULT_GROUP_LOGGERS); initializeEarlyLoggingLevel(environment); Assert.state(this.loggingSystem != null, "loggingSystem is not set"); initializeSystem(environment, this.loggingSystem, this.logFile); initializeFinalLoggingLevels(environment, this.loggingSystem); registerShutdownHookIfNecessary(environment, this.loggingSystem); }
Initialize the logging system according to preferences expressed through the {@link Environment} and the classpath. @param environment the environment @param classLoader the classloader
java
core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java
293
[ "environment", "classLoader" ]
void
true
2
6.08
spring-projects/spring-boot
79,428
javadoc
false
xor
public static boolean xor(final boolean... array) { ObjectUtils.requireNonEmpty(array, "array"); // false if the neutral element of the xor operator boolean result = false; for (final boolean element : array) { result ^= element; } return result; }
Performs an xor on a set of booleans. <p> This behaves like an XOR gate; it returns true if the number of true values is odd, and false if the number of true values is zero or even. </p> <pre> BooleanUtils.xor(true, true) = false BooleanUtils.xor(false, false) = false BooleanUtils.xor(true, false) = true BooleanUtils.xor(true, false, false) = true BooleanUtils.xor(true, true, true) = true BooleanUtils.xor(true, true, true, true) = false </pre> @param array an array of {@code boolean}s @return true if the number of true values in the array is odd; otherwise returns false. @throws NullPointerException if {@code array} is {@code null} @throws IllegalArgumentException if {@code array} is empty.
java
src/main/java/org/apache/commons/lang3/BooleanUtils.java
1,175
[]
true
1
7.04
apache/commons-lang
2,896
javadoc
false
field
public XContentBuilder field(String name, BigInteger value) throws IOException { if (value == null) { return nullField(name); } ensureNameNotNull(name); generator.writeNumberField(name, value); return this; }
@return the value of the "human readable" flag. When the value is equal to true, some types of values are written in a format easier to read for a human.
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
661
[ "name", "value" ]
XContentBuilder
true
2
7.04
elastic/elasticsearch
75,680
javadoc
false
registerListeners
protected void registerListeners() { // Register statically specified listeners first. for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (!CollectionUtils.isEmpty(earlyEventsToProcess)) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
Add beans that implement ApplicationListener as listeners. Doesn't affect other listeners, which can be added without being beans.
java
spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
913
[]
void
true
2
6.24
spring-projects/spring-framework
59,386
javadoc
false
maybePropagateCoordinatorFatalErrorEvent
private void maybePropagateCoordinatorFatalErrorEvent() { coordinatorRequestManager.getAndClearFatalError() .ifPresent(fatalError -> backgroundEventHandler.add(new ErrorEvent(fatalError))); }
A heartbeat should be sent without waiting for the heartbeat interval to expire if: - the member is leaving the group or - the member is joining the group or acknowledging the assignment and for both cases there is no heartbeat request in flight. @return true if a heartbeat should be sent before the interval expires, false otherwise
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
474
[]
void
true
1
6.48
apache/kafka
31,560
javadoc
false
squeeze
public static String squeeze(final String str, final String... set) { if (isEmpty(str, set)) { return str; } final CharSet chars = CharSet.getInstance(set); final StringBuilder buffer = new StringBuilder(str.length()); final char[] chrs = str.toCharArray(); final int sz = chrs.length; char lastChar = chrs[0]; char ch; Character inChars = null; Character notInChars = null; buffer.append(lastChar); for (int i = 1; i < sz; i++) { ch = chrs[i]; if (ch == lastChar) { if (inChars != null && ch == inChars) { continue; } if (notInChars == null || ch != notInChars) { if (chars.contains(ch)) { inChars = ch; continue; } notInChars = ch; } } buffer.append(ch); lastChar = ch; } return buffer.toString(); }
Squeezes any repetitions of a character that is mentioned in the supplied set. <pre> CharSetUtils.squeeze(null, *) = null CharSetUtils.squeeze("", *) = "" CharSetUtils.squeeze(*, null) = * CharSetUtils.squeeze(*, "") = * CharSetUtils.squeeze("hello", "k-p") = "helo" CharSetUtils.squeeze("hello", "a-e") = "hello" </pre> @see CharSet#getInstance(String...) for set-syntax. @param str the string to squeeze, may be null @param set the character set to use for manipulation, may be null @return the modified String, {@code null} if null string input
java
src/main/java/org/apache/commons/lang3/CharSetUtils.java
205
[ "str" ]
String
true
9
7.6
apache/commons-lang
2,896
javadoc
false
cov
def cov( self, other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, numeric_only: bool = False, ): """ Calculate the rolling sample covariance. Parameters ---------- other : Series or DataFrame, optional If not supplied then will default to self and produce pairwise output. pairwise : bool, default None If False then only matching columns between self and other will be used and the output will be a DataFrame. If True then all pairwise combinations will be calculated and the output will be a MultiIndexed DataFrame in the case of DataFrame inputs. In the case of missing elements, only complete pairwise observations will be used. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of elements. numeric_only : bool, default False Include only float, int, boolean columns. Returns ------- Series or DataFrame Return type is the same as the original object with ``np.float64`` dtype. See Also -------- Series.rolling : Calling rolling with Series data. DataFrame.rolling : Calling rolling with DataFrames. Series.cov : Aggregating cov for Series. DataFrame.cov : Aggregating cov for DataFrame. Examples -------- >>> ser1 = pd.Series([1, 2, 3, 4]) >>> ser2 = pd.Series([1, 4, 5, 8]) >>> ser1.rolling(2).cov(ser2) 0 NaN 1 1.5 2 0.5 3 1.5 dtype: float64 """ return super().cov( other=other, pairwise=pairwise, ddof=ddof, numeric_only=numeric_only, )
Calculate the rolling sample covariance. Parameters ---------- other : Series or DataFrame, optional If not supplied then will default to self and produce pairwise output. pairwise : bool, default None If False then only matching columns between self and other will be used and the output will be a DataFrame. If True then all pairwise combinations will be calculated and the output will be a MultiIndexed DataFrame in the case of DataFrame inputs. In the case of missing elements, only complete pairwise observations will be used. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of elements. numeric_only : bool, default False Include only float, int, boolean columns. Returns ------- Series or DataFrame Return type is the same as the original object with ``np.float64`` dtype. See Also -------- Series.rolling : Calling rolling with Series data. DataFrame.rolling : Calling rolling with DataFrames. Series.cov : Aggregating cov for Series. DataFrame.cov : Aggregating cov for DataFrame. Examples -------- >>> ser1 = pd.Series([1, 2, 3, 4]) >>> ser2 = pd.Series([1, 4, 5, 8]) >>> ser1.rolling(2).cov(ser2) 0 NaN 1 1.5 2 0.5 3 1.5 dtype: float64
python
pandas/core/window/rolling.py
3,262
[ "self", "other", "pairwise", "ddof", "numeric_only" ]
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
batchIterator
AbstractIterator<? extends RecordBatch> batchIterator();
Get an iterator over the record batches. This is similar to {@link #batches()} but returns an {@link AbstractIterator} instead of {@link Iterator}, so that clients can use methods like {@link AbstractIterator#peek() peek}. @return An iterator over the record batches of the log
java
clients/src/main/java/org/apache/kafka/common/record/Records.java
71
[]
true
1
6.16
apache/kafka
31,560
javadoc
false
throwIfPendingState
private void throwIfPendingState(String operation) { if (pendingTransition != null) { if (pendingTransition.result.isAcked()) { pendingTransition = null; } else { throw new IllegalStateException("Cannot attempt operation `" + operation + "` " + "because the previous call to `" + pendingTransition.operation + "` " + "timed out and must be retried"); } } }
Check if the transaction is in the prepared state. @return true if the current state is PREPARED_TRANSACTION
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
1,251
[ "operation" ]
void
true
3
7.04
apache/kafka
31,560
javadoc
false
size
public int size() { return acknowledgements.size(); }
Returns the size of the set of acknowledgements. @return The size of the set of acknowledgements.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Acknowledgements.java
114
[]
true
1
6.96
apache/kafka
31,560
javadoc
false
isForeachProcessorWithGeoipProcessor
@SuppressWarnings("unchecked") private static boolean isForeachProcessorWithGeoipProcessor( Map<String, Object> processor, boolean downloadDatabaseOnPipelineCreation, Map<String, PipelineConfiguration> pipelineConfigById, Map<String, Boolean> pipelineHasGeoProcessorById ) { final Map<String, Object> processorConfig = (Map<String, Object>) processor.get("foreach"); return processorConfig != null && hasAtLeastOneGeoipProcessor( (Map<String, Object>) processorConfig.get("processor"), downloadDatabaseOnPipelineCreation, pipelineConfigById, pipelineHasGeoProcessorById ); }
Check if a processor is a foreach processor containing at least a geoip processor. @param processor Processor config. @param downloadDatabaseOnPipelineCreation Should the download_database_on_pipeline_creation of the geoip processor be true or false. @param pipelineConfigById A Map of pipeline id to PipelineConfiguration @param pipelineHasGeoProcessorById A Map of pipeline id to Boolean, indicating whether the pipeline references a geoip processor (true), does not reference a geoip processor (false), or we are currently trying to figure that out (null). @return true if a geoip processor is found in the processor list.
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java
459
[ "processor", "downloadDatabaseOnPipelineCreation", "pipelineConfigById", "pipelineHasGeoProcessorById" ]
true
2
7.6
elastic/elasticsearch
75,680
javadoc
false
createIdentifier
function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage, privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier { if (isIdentifier) { identifierCount++; const pos = scanner.hasPrecedingJSDocLeadingAsterisks() ? scanner.getTokenStart() : getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker const originalKeywordKind = token(); const text = internIdentifier(scanner.getTokenValue()); const hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === SyntaxKind.PrivateIdentifier) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } if (token() === SyntaxKind.Unknown && scanner.tryScan(() => scanner.reScanInvalidIdentifier() === SyntaxKind.Identifier)) { // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. return createIdentifier(/*isIdentifier*/ true); } identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. const reportAtCurrentPosition = token() === SyntaxKind.EndOfFileToken; const isReservedWord = scanner.isReservedWord(); const msgArg = scanner.getTokenText(); const defaultMessage = isReservedWord ? Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : Diagnostics.Identifier_expected; return createMissingNode<Identifier>(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); }
Reports a diagnostic error for the current token being an invalid name. @param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName). @param nameDiagnostic Diagnostic to report for all other cases. @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
typescript
src/compiler/parser.ts
2,648
[ "isIdentifier", "diagnosticMessage?", "privateIdentifierDiagnosticMessage?" ]
true
9
6.88
microsoft/TypeScript
107,154
jsdoc
false
modelsLayer
function modelsLayer(client: Client): CompositeProxyLayer { const dmmfModelKeys = Object.keys(client._runtimeDataModel.models) const jsModelKeys = dmmfModelKeys.map(dmmfToJSModelName) const allKeys = [...new Set(dmmfModelKeys.concat(jsModelKeys))] return cacheProperties({ getKeys() { return allKeys }, getPropertyValue(prop) { const dmmfModelName = jsToDMMFModelName(prop) // creates a new model proxy on the fly and caches it if (client._runtimeDataModel.models[dmmfModelName] !== undefined) { return applyModel(client, dmmfModelName) } // above silently failed if model name is lower cased if (client._runtimeDataModel.models[prop] !== undefined) { return applyModel(client, prop) } return undefined }, getPropertyDescriptor(key) { if (!jsModelKeys.includes(key)) { return { enumerable: false } } return undefined }, }) }
Dynamically creates a model proxy interface for a give name. For each prop accessed on this proxy, it will lookup the dmmf to find if that model exists. If it is the case, it will create a proxy for that model via {@link applyModel}. @param client to create the proxy around @returns a proxy to access models
typescript
packages/client/src/runtime/core/model/applyModelsAndClientExtensions.ts
54
[ "client" ]
true
4
8.24
prisma/prisma
44,834
jsdoc
false
close
@Override public void close() { if (principalBuilder instanceof Closeable) Utils.closeQuietly((Closeable) principalBuilder, "principal builder"); }
Constructs Principal using configured principalBuilder. @return the built principal
java
clients/src/main/java/org/apache/kafka/common/network/SslChannelBuilder.java
168
[]
void
true
2
7.28
apache/kafka
31,560
javadoc
false
get_job_state
def get_job_state(self, job_name: str, run_id: str) -> str: """ Get state of the Glue job; the job state can be running, finished, failed, stopped or timeout. .. seealso:: - :external+boto3:py:meth:`Glue.Client.get_job_run` :param job_name: unique job name per AWS account :param run_id: The job-run ID of the predecessor job run :return: State of the Glue job """ for attempt in Retrying(**self.retry_config): with attempt: try: job_run = self.conn.get_job_run(JobName=job_name, RunId=run_id, PredecessorsIncluded=True) return job_run["JobRun"]["JobRunState"] except ClientError as e: self.log.error("Failed to get job state for job %s run %s: %s", job_name, run_id, e) raise except Exception as e: self.log.error( "Unexpected error getting job state for job %s run %s: %s", job_name, run_id, e ) raise # This should never be reached due to reraise=True, but mypy needs it raise RuntimeError("Unexpected end of retry loop")
Get state of the Glue job; the job state can be running, finished, failed, stopped or timeout. .. seealso:: - :external+boto3:py:meth:`Glue.Client.get_job_run` :param job_name: unique job name per AWS account :param run_id: The job-run ID of the predecessor job run :return: State of the Glue job
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/glue.py
253
[ "self", "job_name", "run_id" ]
str
true
2
8.24
apache/airflow
43,597
sphinx
false
nullToEmpty
public static Double[] nullToEmpty(final Double[] array) { return nullTo(array, EMPTY_DOUBLE_OBJECT_ARRAY); }
Defensive programming technique to change a {@code null} reference to an empty one. <p> This method returns an empty array for a {@code null} input array. </p> <p> As a memory optimizing technique an empty array passed in will be overridden with the empty {@code public static} references in this class. </p> @param array the array to check for {@code null} or empty. @return the same array, {@code public static} empty array if {@code null} or empty input. @since 2.5
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
4,432
[ "array" ]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
load
public static ImportCandidates load(Class<?> annotation, @Nullable ClassLoader classLoader) { Assert.notNull(annotation, "'annotation' must not be null"); ClassLoader classLoaderToUse = decideClassloader(classLoader); String location = String.format(LOCATION, annotation.getName()); Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location); List<String> importCandidates = new ArrayList<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); importCandidates.addAll(readCandidateConfigurations(url)); } return new ImportCandidates(importCandidates); }
Loads the names of import candidates from the classpath. The names of the import candidates are stored in files named {@code META-INF/spring/full-qualified-annotation-name.imports} on the classpath. Every line contains the full qualified name of the candidate class. Comments are supported using the # character. @param annotation annotation to load @param classLoader class loader to use for loading @return list of names of annotated classes
java
core/spring-boot/src/main/java/org/springframework/boot/context/annotation/ImportCandidates.java
81
[ "annotation", "classLoader" ]
ImportCandidates
true
2
7.6
spring-projects/spring-boot
79,428
javadoc
false
thru
function thru(value, interceptor) { return interceptor(value); }
This method is like `_.tap` except that it returns the result of `interceptor`. The purpose of this method is to "pass thru" values replacing intermediate results in a method chain sequence. @static @memberOf _ @since 3.0.0 @category Seq @param {*} value The value to provide to `interceptor`. @param {Function} interceptor The function to invoke. @returns {*} Returns the result of `interceptor`. @example _(' abc ') .chain() .trim() .thru(function(value) { return [value]; }) .value(); // => ['abc']
javascript
lodash.js
8,897
[ "value", "interceptor" ]
false
1
6.24
lodash/lodash
61,490
jsdoc
false
load_sample_images
def load_sample_images(): """Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Read more in the :ref:`User Guide <sample_images>`. Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. images : list of ndarray of shape (427, 640, 3) The two sample image. filenames : list The filenames for the images. DESCR : str The full description of the dataset. Examples -------- To load the data and visualize the images: >>> from sklearn.datasets import load_sample_images >>> dataset = load_sample_images() #doctest: +SKIP >>> len(dataset.images) #doctest: +SKIP 2 >>> first_img_data = dataset.images[0] #doctest: +SKIP >>> first_img_data.shape #doctest: +SKIP (427, 640, 3) >>> first_img_data.dtype #doctest: +SKIP dtype('uint8') """ try: from PIL import Image except ImportError: raise ImportError( "The Python Imaging Library (PIL) is required to load data " "from jpeg files. Please refer to " "https://pillow.readthedocs.io/en/stable/installation.html " "for installing PIL." ) descr = load_descr("README.txt", descr_module=IMAGES_MODULE) filenames, images = [], [] jpg_paths = sorted( resource for resource in resources.files(IMAGES_MODULE).iterdir() if resource.is_file() and resource.match("*.jpg") ) for path in jpg_paths: filenames.append(str(path)) with path.open("rb") as image_file: pil_image = Image.open(image_file) image = np.asarray(pil_image) images.append(image) return Bunch(images=images, filenames=filenames, DESCR=descr)
Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Read more in the :ref:`User Guide <sample_images>`. Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. images : list of ndarray of shape (427, 640, 3) The two sample image. filenames : list The filenames for the images. DESCR : str The full description of the dataset. Examples -------- To load the data and visualize the images: >>> from sklearn.datasets import load_sample_images >>> dataset = load_sample_images() #doctest: +SKIP >>> len(dataset.images) #doctest: +SKIP 2 >>> first_img_data = dataset.images[0] #doctest: +SKIP >>> first_img_data.shape #doctest: +SKIP (427, 640, 3) >>> first_img_data.dtype #doctest: +SKIP dtype('uint8')
python
sklearn/datasets/_base.py
1,294
[]
false
3
7.2
scikit-learn/scikit-learn
64,340
unknown
false
isTrue
public static void isTrue(final boolean expression, final Supplier<String> messageSupplier) { if (!expression) { throw new IllegalArgumentException(messageSupplier.get()); } }
Validate that the argument condition is {@code true}; otherwise throwing an exception with the specified message. This method is useful when validating according to an arbitrary boolean expression, such as validating a primitive number or using your own custom validation expression. <pre>{@code Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max); }</pre> @param expression the boolean expression to check. @param messageSupplier the exception message supplier. @throws IllegalArgumentException if expression is {@code false}. @see #isTrue(boolean) @see #isTrue(boolean, String, long) @see #isTrue(boolean, String, double) @since 3.18.0
java
src/main/java/org/apache/commons/lang3/Validate.java
594
[ "expression", "messageSupplier" ]
void
true
2
6.24
apache/commons-lang
2,896
javadoc
false
_isna_array
def _isna_array(values: ArrayLike) -> npt.NDArray[np.bool_] | NDFrame: """ Return an array indicating which values of the input array are NaN / NA. Parameters ---------- obj: ndarray or ExtensionArray The input array whose elements are to be checked. Returns ------- array-like Array of boolean values denoting the NA status of each element. """ dtype = values.dtype result: npt.NDArray[np.bool_] | NDFrame if not isinstance(values, np.ndarray): # i.e. ExtensionArray # error: Incompatible types in assignment (expression has type # "Union[ndarray[Any, Any], ExtensionArraySupportsAnyAll]", variable has # type "ndarray[Any, dtype[bool_]]") result = values.isna() # type: ignore[assignment] elif isinstance(values, np.rec.recarray): # GH 48526 result = _isna_recarray_dtype(values) elif is_string_or_object_np_dtype(values.dtype): result = _isna_string_dtype(values) elif dtype.kind in "mM": # this is the NaT pattern result = values.view("i8") == iNaT else: result = np.isnan(values) return result
Return an array indicating which values of the input array are NaN / NA. Parameters ---------- obj: ndarray or ExtensionArray The input array whose elements are to be checked. Returns ------- array-like Array of boolean values denoting the NA status of each element.
python
pandas/core/dtypes/missing.py
223
[ "values" ]
npt.NDArray[np.bool_] | NDFrame
true
6
6.88
pandas-dev/pandas
47,362
numpy
false
stateStrategy
private static AbstractStateStrategy stateStrategy(final State state) { return STRATEGY_MAP.get(state); }
Returns the {@link AbstractStateStrategy} object responsible for the given state. @param state the state @return the corresponding {@link AbstractStateStrategy} @throws CircuitBreakingException if the strategy cannot be resolved
java
src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java
306
[ "state" ]
AbstractStateStrategy
true
1
6
apache/commons-lang
2,896
javadoc
false
resolveValueIfNecessary
public @Nullable Object resolveValueIfNecessary(Object argName, @Nullable Object value) { // We must check each value to see whether it requires a runtime reference // to another bean to be resolved. if (value instanceof RuntimeBeanReference ref) { return resolveReference(argName, ref); } else if (value instanceof RuntimeBeanNameReference ref) { String refName = ref.getBeanName(); refName = String.valueOf(doEvaluate(refName)); if (!this.beanFactory.containsBean(refName)) { throw new BeanDefinitionStoreException( "Invalid bean name '" + refName + "' in bean reference for " + argName); } return refName; } else if (value instanceof BeanDefinitionHolder bdHolder) { // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. return resolveInnerBean(bdHolder.getBeanName(), bdHolder.getBeanDefinition(), (name, mbd) -> resolveInnerBeanValue(argName, name, mbd)); } else if (value instanceof BeanDefinition bd) { return resolveInnerBean(null, bd, (name, mbd) -> resolveInnerBeanValue(argName, name, mbd)); } else if (value instanceof DependencyDescriptor dependencyDescriptor) { Set<String> autowiredBeanNames = new LinkedHashSet<>(2); Object result = this.beanFactory.resolveDependency( dependencyDescriptor, this.beanName, autowiredBeanNames, this.typeConverter); for (String autowiredBeanName : autowiredBeanNames) { if (this.beanFactory.containsBean(autowiredBeanName)) { this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName); } } return result; } else if (value instanceof ManagedArray managedArray) { // May need to resolve contained runtime references. Class<?> elementType = managedArray.resolvedElementType; if (elementType == null) { String elementTypeName = managedArray.getElementTypeName(); if (StringUtils.hasText(elementTypeName)) { try { elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader()); managedArray.resolvedElementType = elementType; } catch (Throwable ex) { // Improve the message by showing the context. throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error resolving array type for " + argName, ex); } } else { elementType = Object.class; } } return resolveManagedArray(argName, (List<?>) value, elementType); } else if (value instanceof ManagedList<?> managedList) { // May need to resolve contained runtime references. return resolveManagedList(argName, managedList); } else if (value instanceof ManagedSet<?> managedSet) { // May need to resolve contained runtime references. return resolveManagedSet(argName, managedSet); } else if (value instanceof ManagedMap<?, ?> managedMap) { // May need to resolve contained runtime references. return resolveManagedMap(argName, managedMap); } else if (value instanceof ManagedProperties original) { // Properties original = managedProperties; Properties copy = new Properties(); original.forEach((propKey, propValue) -> { if (propKey instanceof TypedStringValue typedStringValue) { propKey = evaluate(typedStringValue); } if (propValue instanceof TypedStringValue typedStringValue) { propValue = evaluate(typedStringValue); } if (propKey == null || propValue == null) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error converting Properties key/value pair for " + argName + ": resolved to null"); } copy.put(propKey, propValue); }); return copy; } else if (value instanceof TypedStringValue typedStringValue) { // Convert value to target type here. Object valueObject = evaluate(typedStringValue); try { Class<?> resolvedTargetType = resolveTargetType(typedStringValue); if (resolvedTargetType != null) { return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType); } else { return valueObject; } } catch (Throwable ex) { // Improve the message by showing the context. throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error converting typed String value for " + argName, ex); } } else if (value instanceof NullBean) { return null; } else { return evaluate(value); } }
Given a PropertyValue, return a value, resolving any references to other beans in the factory if necessary. The value could be: <li>A BeanDefinition, which leads to the creation of a corresponding new bean instance. Singleton flags and names of such "inner beans" are always ignored: Inner beans are anonymous prototypes. <li>A RuntimeBeanReference, which must be resolved. <li>A ManagedList. This is a special collection that may contain RuntimeBeanReferences or Collections that will need to be resolved. <li>A ManagedSet. May also contain RuntimeBeanReferences or Collections that will need to be resolved. <li>A ManagedMap. In this case the value may be a RuntimeBeanReference or Collection that will need to be resolved. <li>An ordinary object or {@code null}, in which case it's left alone. @param argName the name of the argument that the value is defined for @param value the value object to resolve @return the resolved object
java
spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java
131
[ "argName", "value" ]
Object
true
24
6.64
spring-projects/spring-framework
59,386
javadoc
false
obtainBean
private Object obtainBean(String beanName) { Object bean = this.beans.get(beanName); if (bean == null) { throw new NoSuchBeanDefinitionException(beanName, "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]"); } return bean; }
Add a new singleton bean. <p>Will overwrite any existing instance for the given name. @param name the name of the bean @param bean the bean instance
java
spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java
161
[ "beanName" ]
Object
true
2
6.88
spring-projects/spring-framework
59,386
javadoc
false
parse_args
def parse_args() -> argparse.Namespace: """ Parse command line arguments. Returns: argparse.Namespace: Parsed arguments. """ parser = argparse.ArgumentParser(description="Upload test stats to s3") parser.add_argument( "--workflow-run-id", type=int, required=True, help="id of the workflow to get artifacts from", ) parser.add_argument( "--workflow-run-attempt", type=int, required=True, help="which retry of the workflow this is", ) parser.add_argument( "--workflow-name", type=str, required=True, help="id of the workflow to get artifacts from", ) parser.add_argument( "--job-id", type=int, required=True, help="id of the workflow to get artifacts from", ) parser.add_argument( "--job-name", type=str, required=True, help="id of the workflow to get artifacts from", ) parser.add_argument( "--repo", type=str, required=False, help="which GitHub repo this workflow run belongs to", ) parser.add_argument("--debug", action="store_true", help="Enable debug mode") parser.add_argument("--dry-run", action="store_true", help="Enable dry-run mode") parser.add_argument( "--artifact-prefix", type=str, required=False, help="artifact prefix to download raw utilizarion data from s3", ) parser.add_argument( "--local-path", type=str, required=False, help="path of the raw utilizarion data from local location", ) return parser.parse_args()
Parse command line arguments. Returns: argparse.Namespace: Parsed arguments.
python
tools/stats/upload_utilization_stats/upload_utilization_stats.py
428
[]
argparse.Namespace
true
1
6.16
pytorch/pytorch
96,034
unknown
false
handleCompletedSends
private void handleCompletedSends(List<ClientResponse> responses, long now) { // if no response is expected then when the send is completed, return it for (NetworkSend send : this.selector.completedSends()) { InFlightRequest request = this.inFlightRequests.lastSent(send.destinationId()); if (!request.expectResponse) { this.inFlightRequests.completeLastSent(send.destinationId()); responses.add(request.completed(null, now)); } } }
Handle any completed request send. In particular if no response is expected consider the request complete. @param responses The list of responses to update @param now The current time
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
958
[ "responses", "now" ]
void
true
2
7.04
apache/kafka
31,560
javadoc
false
get_available_distributions
def get_available_distributions( include_non_provider_doc_packages: bool = False, include_all_providers: bool = False, include_suspended: bool = False, include_removed: bool = False, include_not_ready: bool = False, include_regular: bool = True, ) -> list[str]: """ Return provider ids for all packages that are available currently (not suspended). :param include_suspended: whether the suspended packages should be included :param include_removed: whether the removed packages should be included :param include_not_ready: whether the not-ready packages should be included :param include_regular: whether the regular packages should be included :param include_non_provider_doc_packages: whether the non-provider doc packages should be included (packages like apache-airflow, helm-chart, docker-stack) :param include_all_providers: whether "all-providers" should be included ni the list. """ # Need lazy import to prevent circular dependencies from airflow_breeze.utils.provider_dependencies import get_provider_dependencies provider_dependencies = get_provider_dependencies() valid_states = set() if include_not_ready: valid_states.add("not-ready") if include_regular: valid_states.update({"ready", "pre-release"}) if include_suspended: valid_states.add("suspended") if include_removed: valid_states.add("removed") available_packages: list[str] = [ provider_id for provider_id, provider_dependencies in provider_dependencies.items() if provider_dependencies["state"] in valid_states ] if include_non_provider_doc_packages: available_packages.extend(REGULAR_DOC_PACKAGES) if include_all_providers: available_packages.append("all-providers") return sorted(set(available_packages))
Return provider ids for all packages that are available currently (not suspended). :param include_suspended: whether the suspended packages should be included :param include_removed: whether the removed packages should be included :param include_not_ready: whether the not-ready packages should be included :param include_regular: whether the regular packages should be included :param include_non_provider_doc_packages: whether the non-provider doc packages should be included (packages like apache-airflow, helm-chart, docker-stack) :param include_all_providers: whether "all-providers" should be included ni the list.
python
dev/breeze/src/airflow_breeze/utils/packages.py
298
[ "include_non_provider_doc_packages", "include_all_providers", "include_suspended", "include_removed", "include_not_ready", "include_regular" ]
list[str]
true
7
6.24
apache/airflow
43,597
sphinx
false
verify_non_translated
def verify_non_translated() -> None: """ Verify there are no files in the non translatable pages. """ print("Verifying non translated pages") lang_paths = get_lang_paths() error_paths = [] for lang in lang_paths: if lang.name == "en": continue for non_translatable in non_translated_sections: non_translatable_path = lang / "docs" / non_translatable if non_translatable_path.exists(): error_paths.append(non_translatable_path) if error_paths: print("Non-translated pages found, remove them:") for error_path in error_paths: print(error_path) raise typer.Abort() print("No non-translated pages found ✅")
Verify there are no files in the non translatable pages.
python
scripts/docs.py
398
[]
None
true
7
7.04
tiangolo/fastapi
93,264
unknown
false
describeAcls
default DescribeAclsResult describeAcls(AclBindingFilter filter) { return describeAcls(filter, new DescribeAclsOptions()); }
This is a convenience method for {@link #describeAcls(AclBindingFilter, DescribeAclsOptions)} with default options. See the overload for more details. <p> This operation is supported by brokers with version 0.11.0.0 or higher. @param filter The filter to use. @return The DescribeAclsResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
366
[ "filter" ]
DescribeAclsResult
true
1
6.32
apache/kafka
31,560
javadoc
false
determineBeanNameFromAnnotation
protected @Nullable String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) { AnnotationMetadata metadata = annotatedDef.getMetadata(); String beanName = getExplicitBeanName(metadata); if (beanName != null) { return beanName; } // List of annotations directly present on the class we're searching on. // MergedAnnotation implementations do not implement equals()/hashCode(), // so we use a List and a 'visited' Set below. List<MergedAnnotation<Annotation>> mergedAnnotations = metadata.getAnnotations().stream() .filter(MergedAnnotation::isDirectlyPresent) .toList(); Set<AnnotationAttributes> visited = new HashSet<>(); for (MergedAnnotation<Annotation> mergedAnnotation : mergedAnnotations) { AnnotationAttributes attributes = mergedAnnotation.asAnnotationAttributes(ADAPTATIONS); if (visited.add(attributes)) { String annotationType = mergedAnnotation.getType().getName(); Set<String> metaAnnotationTypes = this.metaAnnotationTypesCache.computeIfAbsent(annotationType, key -> getMetaAnnotationTypes(mergedAnnotation)); if (isStereotypeWithNameValue(annotationType, metaAnnotationTypes, attributes)) { Object value = attributes.get(MergedAnnotation.VALUE); if (value instanceof String currentName && !currentName.isBlank() && !hasExplicitlyAliasedValueAttribute(mergedAnnotation.getType())) { if (conventionBasedStereotypeCheckCache.add(annotationType) && metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME) && logger.isWarnEnabled()) { logger.warn(""" Support for convention-based @Component names is deprecated and will \ be removed in a future version of the framework. Please annotate the \ 'value' attribute in @%s with @AliasFor(annotation=Component.class) \ to declare an explicit alias for @Component's 'value' attribute.""" .formatted(annotationType)); } if (beanName != null && !currentName.equals(beanName)) { throw new IllegalStateException("Stereotype annotations suggest inconsistent " + "component names: '" + beanName + "' versus '" + currentName + "'"); } beanName = currentName; } } } } return beanName; }
Derive a bean name from one of the annotations on the class. @param annotatedDef the annotation-aware bean definition @return the bean name, or {@code null} if none is found
java
spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java
125
[ "annotatedDef" ]
String
true
12
8.08
spring-projects/spring-framework
59,386
javadoc
false
stableInsertionSort
private static void stableInsertionSort(TDigestIntArray order, TDigestDoubleArray values, int start, int n, int limit) { for (int i = start + 1; i < n; i++) { int t = order.get(i); double v = values.get(order.get(i)); int vi = order.get(i); int m = Math.max(i - limit, start); // values in [start, i) are ordered // scan backwards to find where to stick t for (int j = i; j >= m; j--) { if (j == 0 || values.get(order.get(j - 1)) < v || (values.get(order.get(j - 1)) == v && (order.get(j - 1) <= vi))) { if (j < i) { order.set(j + 1, order, j, i - j); order.set(j, t); } break; } } } }
Limited range insertion sort with primary key stabilized by the use of the original position to break ties. We assume that no element has to move more than limit steps because quick sort has done its thing. @param order The permutation index @param values The values we are sorting @param start Where to start the sort @param n How many elements to sort @param limit The largest amount of disorder
java
libs/tdigest/src/main/java/org/elasticsearch/tdigest/Sort.java
163
[ "order", "values", "start", "n", "limit" ]
void
true
8
6.72
elastic/elasticsearch
75,680
javadoc
false
replaceAll
public StrBuilder replaceAll(final String searchStr, final String replaceStr) { final int searchLen = StringUtils.length(searchStr); if (searchLen > 0) { final int replaceLen = StringUtils.length(replaceStr); int index = indexOf(searchStr, 0); while (index >= 0) { replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); index = indexOf(searchStr, index + replaceLen); } } return this; }
Replaces the search string with the replace string throughout the builder. @param searchStr the search string, null causes no action to occur @param replaceStr the replace string, null is equivalent to an empty string @return {@code this} instance.
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
2,590
[ "searchStr", "replaceStr" ]
StrBuilder
true
3
7.92
apache/commons-lang
2,896
javadoc
false
of
public static OriginTrackedResource of(Resource resource, @Nullable Origin origin) { if (resource instanceof WritableResource writableResource) { return new OriginTrackedWritableResource(writableResource, origin); } return new OriginTrackedResource(resource, origin); }
Return a new {@link OriginProvider origin tracked} version the given {@link Resource}. @param resource the tracked resource @param origin the origin of the resource @return an {@link OriginTrackedResource} instance
java
core/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedResource.java
183
[ "resource", "origin" ]
OriginTrackedResource
true
2
7.44
spring-projects/spring-boot
79,428
javadoc
false
_create_task_instances
def _create_task_instances( self, dag_id: str, tasks: Iterator[dict[str, Any]] | Iterator[TI], created_counts: dict[str, int], hook_is_noop: bool, *, session: Session, ) -> None: """ Create the necessary task instances from the given tasks. :param dag_id: DAG ID associated with the dagrun :param tasks: the tasks to create the task instances from :param created_counts: a dictionary of number of tasks -> total ti created by the task creator :param hook_is_noop: whether the task_instance_mutation_hook is noop :param session: the session to use """ # Fetch the information we need before handling the exception to avoid # PendingRollbackError due to the session being invalidated on exception # see https://github.com/apache/superset/pull/530 run_id = self.run_id try: if hook_is_noop: session.bulk_insert_mappings(TI.__mapper__, tasks) else: session.bulk_save_objects(tasks) for task_type, count in created_counts.items(): Stats.incr(f"task_instance_created_{task_type}", count, tags=self.stats_tags) # Same metric with tagging Stats.incr("task_instance_created", count, tags={**self.stats_tags, "task_type": task_type}) session.flush() except IntegrityError: self.log.info( "Hit IntegrityError while creating the TIs for %s- %s", dag_id, run_id, exc_info=True, ) self.log.info("Doing session rollback.") # TODO[HA]: We probably need to savepoint this so we can keep the transaction alive. session.rollback()
Create the necessary task instances from the given tasks. :param dag_id: DAG ID associated with the dagrun :param tasks: the tasks to create the task instances from :param created_counts: a dictionary of number of tasks -> total ti created by the task creator :param hook_is_noop: whether the task_instance_mutation_hook is noop :param session: the session to use
python
airflow-core/src/airflow/models/dagrun.py
1,910
[ "self", "dag_id", "tasks", "created_counts", "hook_is_noop", "session" ]
None
true
4
7.04
apache/airflow
43,597
sphinx
false
toInteger
public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) { if (bool == null) { return nullValue; } return bool.booleanValue() ? trueValue : falseValue; }
Converts a Boolean to an int specifying the conversion values. <pre> BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2) = 1 BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0 BooleanUtils.toInteger(null, 1, 0, 2) = 2 </pre> @param bool the Boolean to convert @param trueValue the value to return if {@code true} @param falseValue the value to return if {@code false} @param nullValue the value to return if {@code null} @return the appropriate value
java
src/main/java/org/apache/commons/lang3/BooleanUtils.java
922
[ "bool", "trueValue", "falseValue", "nullValue" ]
true
3
7.92
apache/commons-lang
2,896
javadoc
false
findQualifiedExecutor
protected @Nullable Executor findQualifiedExecutor(@Nullable BeanFactory beanFactory, String qualifier) { if (beanFactory == null) { throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() + " to access qualified executor '" + qualifier + "'"); } return BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, Executor.class, qualifier); }
Retrieve a target executor for the given qualifier. @param qualifier the qualifier to resolve @return the target executor, or {@code null} if none available @since 4.2.6 @see #getExecutorQualifier(Method)
java
spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java
212
[ "beanFactory", "qualifier" ]
Executor
true
2
7.44
spring-projects/spring-framework
59,386
javadoc
false
iter_all_en_paths
def iter_all_en_paths() -> Iterable[Path]: """ Iterate on the markdown files to translate in order of priority. """ first_dirs = [ Path("docs/en/docs/learn"), Path("docs/en/docs/tutorial"), Path("docs/en/docs/advanced"), Path("docs/en/docs/about"), Path("docs/en/docs/how-to"), ] first_parent = Path("docs/en/docs") yield from first_parent.glob("*.md") for dir_path in first_dirs: yield from dir_path.rglob("*.md") first_dirs_str = tuple(str(d) for d in first_dirs) for path in Path("docs/en/docs").rglob("*.md"): if str(path).startswith(first_dirs_str): continue if path.parent == first_parent: continue yield path
Iterate on the markdown files to translate in order of priority.
python
scripts/translate.py
771
[]
Iterable[Path]
true
5
6.88
tiangolo/fastapi
93,264
unknown
false
getBrowserEnv
function getBrowserEnv() { // Attempt to honor this environment variable. // It is specific to the operating system. // See https://github.com/sindresorhus/open#app for documentation. const value = process.env.BROWSER; const args = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(' ') : []; let action; if (!value) { // Default. action = Actions.BROWSER; } else if (value.toLowerCase().endsWith('.js')) { action = Actions.SCRIPT; } else if (value.toLowerCase() === 'none') { action = Actions.NONE; } else { action = Actions.BROWSER; } return { action, value, args }; }
Copyright (c) 2015-present, Facebook, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
typescript
code/core/src/core-server/utils/open-browser/opener.ts
25
[]
false
8
6.4
storybookjs/storybook
88,865
jsdoc
false
bfill
def bfill(self, limit: int | None = None): """ Backward fill the values. Parameters ---------- limit : int, optional Limit of how many values to fill. Returns ------- Series or DataFrame Object with missing values filled. See Also -------- Series.bfill : Backward fill the missing values in the dataset. DataFrame.bfill: Backward fill the missing values in the dataset. Series.fillna: Fill NaN values of a Series. DataFrame.fillna: Fill NaN values of a DataFrame. Examples -------- With Series: >>> index = ["Falcon", "Falcon", "Parrot", "Parrot", "Parrot"] >>> s = pd.Series([None, 1, None, None, 3], index=index) >>> s Falcon NaN Falcon 1.0 Parrot NaN Parrot NaN Parrot 3.0 dtype: float64 >>> s.groupby(level=0).bfill() Falcon 1.0 Falcon 1.0 Parrot 3.0 Parrot 3.0 Parrot 3.0 dtype: float64 >>> s.groupby(level=0).bfill(limit=1) Falcon 1.0 Falcon 1.0 Parrot NaN Parrot 3.0 Parrot 3.0 dtype: float64 With DataFrame: >>> df = pd.DataFrame( ... {"A": [1, None, None, None, 4], "B": [None, None, 5, None, 7]}, ... index=index, ... ) >>> df A B Falcon 1.0 NaN Falcon NaN NaN Parrot NaN 5.0 Parrot NaN NaN Parrot 4.0 7.0 >>> df.groupby(level=0).bfill() A B Falcon 1.0 NaN Falcon NaN NaN Parrot 4.0 5.0 Parrot 4.0 7.0 Parrot 4.0 7.0 >>> df.groupby(level=0).bfill(limit=1) A B Falcon 1.0 NaN Falcon NaN NaN Parrot NaN 5.0 Parrot 4.0 7.0 Parrot 4.0 7.0 """ return self._fill("bfill", limit=limit)
Backward fill the values. Parameters ---------- limit : int, optional Limit of how many values to fill. Returns ------- Series or DataFrame Object with missing values filled. See Also -------- Series.bfill : Backward fill the missing values in the dataset. DataFrame.bfill: Backward fill the missing values in the dataset. Series.fillna: Fill NaN values of a Series. DataFrame.fillna: Fill NaN values of a DataFrame. Examples -------- With Series: >>> index = ["Falcon", "Falcon", "Parrot", "Parrot", "Parrot"] >>> s = pd.Series([None, 1, None, None, 3], index=index) >>> s Falcon NaN Falcon 1.0 Parrot NaN Parrot NaN Parrot 3.0 dtype: float64 >>> s.groupby(level=0).bfill() Falcon 1.0 Falcon 1.0 Parrot 3.0 Parrot 3.0 Parrot 3.0 dtype: float64 >>> s.groupby(level=0).bfill(limit=1) Falcon 1.0 Falcon 1.0 Parrot NaN Parrot 3.0 Parrot 3.0 dtype: float64 With DataFrame: >>> df = pd.DataFrame( ... {"A": [1, None, None, None, 4], "B": [None, None, 5, None, 7]}, ... index=index, ... ) >>> df A B Falcon 1.0 NaN Falcon NaN NaN Parrot NaN 5.0 Parrot NaN NaN Parrot 4.0 7.0 >>> df.groupby(level=0).bfill() A B Falcon 1.0 NaN Falcon NaN NaN Parrot 4.0 5.0 Parrot 4.0 7.0 Parrot 4.0 7.0 >>> df.groupby(level=0).bfill(limit=1) A B Falcon 1.0 NaN Falcon NaN NaN Parrot NaN 5.0 Parrot 4.0 7.0 Parrot 4.0 7.0
python
pandas/core/groupby/groupby.py
4,183
[ "self", "limit" ]
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
unmodifiableEntrySet
static <K extends @Nullable Object, V extends @Nullable Object> Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) { return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet)); }
Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue} operation throws an {@link UnsupportedOperationException}, as do any operations that would modify the returned set. @param entrySet the entries for which to return an unmodifiable view @return an unmodifiable view of the entries
java
android/guava/src/com/google/common/collect/Maps.java
1,427
[ "entrySet" ]
true
1
6.32
google/guava
51,352
javadoc
false
getModules
function getModules() { // Check if TypeScript is setup const hasTsConfig = fs.existsSync(paths.appTsConfig); const hasJsConfig = fs.existsSync(paths.appJsConfig); if (hasTsConfig && hasJsConfig) { throw new Error( 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' ); } let config; // If there's a tsconfig.json we assume it's a // TypeScript project and set up the config // based on tsconfig.json if (hasTsConfig) { const ts = require( resolve.sync('typescript', { basedir: paths.appNodeModules, }) ); config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; // Otherwise we'll check if there is jsconfig.json // for non TS projects. } else if (hasJsConfig) { config = require(paths.appJsConfig); } config = config || {}; const options = config.compilerOptions || {}; const additionalModulePaths = getAdditionalModulePaths(options); return { additionalModulePaths: additionalModulePaths, webpackAliases: getWebpackAliases(options), jestAliases: getJestAliases(options), hasTsConfig, }; }
Get jest aliases based on the baseUrl of a compilerOptions object. @param {*} options
javascript
fixtures/flight/config/modules.js
94
[]
false
8
6.08
facebook/react
241,750
jsdoc
false
isBoolean
public static boolean isBoolean(char[] text, int offset, int length) { if (text == null || length == 0) { return false; } return isBoolean(new String(text, offset, length)); }
returns true iff the sequence of chars is one of "true","false". @param text sequence to check @param offset offset to start @param length length to check
java
libs/core/src/main/java/org/elasticsearch/core/Booleans.java
39
[ "text", "offset", "length" ]
true
3
6.56
elastic/elasticsearch
75,680
javadoc
false
get_child_arguments
def get_child_arguments(): """ Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading. """ import __main__ py_script = Path(sys.argv[0]) exe_entrypoint = py_script.with_suffix(".exe") args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions] if sys.implementation.name in ("cpython", "pypy"): args.extend( f"-X{key}" if value is True else f"-X{key}={value}" for key, value in sys._xoptions.items() ) # __spec__ is set when the server was started with the `-m` option, # see https://docs.python.org/3/reference/import.html#main-spec # __spec__ may not exist, e.g. when running in a Conda env. if getattr(__main__, "__spec__", None) is not None and not exe_entrypoint.exists(): spec = __main__.__spec__ if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent: name = spec.parent else: name = spec.name args += ["-m", name] args += sys.argv[1:] elif not py_script.exists(): # sys.argv[0] may not exist for several reasons on Windows. # It may exist with a .exe extension or have a -script.py suffix. if exe_entrypoint.exists(): # Should be executed directly, ignoring sys.executable. return [exe_entrypoint, *sys.argv[1:]] script_entrypoint = py_script.with_name("%s-script.py" % py_script.name) if script_entrypoint.exists(): # Should be executed as usual. return [*args, script_entrypoint, *sys.argv[1:]] raise RuntimeError("Script %s does not exist." % py_script) else: args += sys.argv return args
Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading.
python
django/utils/autoreload.py
220
[]
false
13
6.4
django/django
86,204
unknown
false
endOfData
@CanIgnoreReturnValue protected final @Nullable T endOfData() { state = State.DONE; return null; }
Implementations of {@link #computeNext} <b>must</b> invoke this method when there are no elements left in the iteration. @return {@code null}; a convenience so your {@code computeNext} implementation can use the simple statement {@code return endOfData();}
java
android/guava/src/com/google/common/collect/AbstractIterator.java
120
[]
T
true
1
6.24
google/guava
51,352
javadoc
false
get_task_log
def get_task_log(self, ti: TaskInstance, try_number: int) -> tuple[list[str], list[str]]: """ Return the task logs. :param ti: A TaskInstance object :param try_number: current try_number to read log from :return: tuple of logs and messages """ return [], []
Return the task logs. :param ti: A TaskInstance object :param try_number: current try_number to read log from :return: tuple of logs and messages
python
airflow-core/src/airflow/executors/base_executor.py
515
[ "self", "ti", "try_number" ]
tuple[list[str], list[str]]
true
1
6.72
apache/airflow
43,597
sphinx
false
lastIndexOf
public int lastIndexOf(final String str, final int startIndex) { return Strings.CS.lastIndexOf(this, str, startIndex); }
Searches the string builder to find the last reference to the specified string starting searching from the given index. <p> Note that a null input string will return -1, whereas the JDK throws an exception. </p> @param str the string to find, null returns -1 @param startIndex the index to start at, invalid index rounded to edge @return the last index of the string, or -1 if not found
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
2,360
[ "str", "startIndex" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
asList
public static <E extends @Nullable Object> List<E> asList(@ParametricNullness E first, E[] rest) { return new OnePlusArrayList<>(first, rest); }
Returns an unmodifiable list containing the specified first element and backed by the specified array of additional elements. Changes to the {@code rest} array will be reflected in the returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable. <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum argument count. <p>The returned list is serializable and implements {@link RandomAccess}. @param first the first element @param rest an array of additional elements, possibly empty @return an unmodifiable list containing the specified elements
java
android/guava/src/com/google/common/collect/Lists.java
307
[ "first", "rest" ]
true
1
6.48
google/guava
51,352
javadoc
false
optLong
public long optLong(String name) { return optLong(name, 0L); }
Returns the value mapped by {@code name} if it exists and is a long or can be coerced to a long. Returns 0 otherwise. Note that JSON represents numbers as doubles, so this is <a href="#lossy">lossy</a>; use strings to transfer numbers via JSON. @param name the name of the property @return the value or {@code 0L}
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
531
[ "name" ]
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
getBeanNamesForAnnotation
@Override public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { List<String> result = new ArrayList<>(); for (String beanName : this.beanDefinitionNames) { BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd != null && !bd.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } for (String beanName : this.manualSingletonNames) { if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } return StringUtils.toStringArray(result); }
Check whether the specified bean would need to be eagerly initialized in order to determine its type. @param factoryBeanName a factory-bean reference that the bean definition defines a factory method for @return whether eager initialization is necessary
java
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
769
[ "annotationType" ]
true
6
7.6
spring-projects/spring-framework
59,386
javadoc
false
_get_base_image_args
def _get_base_image_args(self, inputs: VllmBuildParameters) -> tuple[str, str, str]: """ Returns: - base_image_arg: docker buildx arg string for base image - final_base_image_arg: docker buildx arg string for vllm-base stage - pull_flag: --pull=true or --pull=false depending on whether the image exists locally """ if not inputs.use_local_base_image: return "", "", "" base_image = inputs.base_image # set both base image and final base image to the same local image base_image_arg = f"--build-arg BUILD_BASE_IMAGE={base_image}" final_base_image_arg = f"--build-arg FINAL_BASE_IMAGE={base_image}" if local_image_exists(base_image): pull_flag = "--pull=false" return base_image_arg, final_base_image_arg, pull_flag logger.info( "[INFO] Local image not found:%s will try to pull from remote", {base_image} ) return base_image_arg, final_base_image_arg, ""
Returns: - base_image_arg: docker buildx arg string for base image - final_base_image_arg: docker buildx arg string for vllm-base stage - pull_flag: --pull=true or --pull=false depending on whether the image exists locally
python
.ci/lumen_cli/cli/lib/core/vllm/vllm_build.py
243
[ "self", "inputs" ]
tuple[str, str, str]
true
3
6.08
pytorch/pytorch
96,034
unknown
false
doRegisterBean
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, Class<? extends Annotation> @Nullable [] qualifiers, @Nullable Supplier<T> supplier, BeanDefinitionCustomizer @Nullable [] customizers) { AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass); if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; } abd.setAttribute(ConfigurationClassUtils.CANDIDATE_ATTRIBUTE, Boolean.TRUE); abd.setInstanceSupplier(supplier); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); abd.setScope(scopeMetadata.getScopeName()); String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); if (qualifiers != null) { for (Class<? extends Annotation> qualifier : qualifiers) { if (Primary.class == qualifier) { abd.setPrimary(true); } else if (Fallback.class == qualifier) { abd.setFallback(true); } else if (Lazy.class == qualifier) { abd.setLazyInit(true); } else { abd.addQualifier(new AutowireCandidateQualifier(qualifier)); } } } if (customizers != null) { for (BeanDefinitionCustomizer customizer : customizers) { customizer.customize(abd); } } BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); }
Register a bean from the given bean class, deriving its metadata from class-declared annotations. @param beanClass the class of the bean @param name an explicit name for the bean @param qualifiers specific qualifier annotations to consider, if any, in addition to qualifiers at the bean class level @param supplier a callback for creating an instance of the bean (may be {@code null}) @param customizers one or more callbacks for customizing the factory's {@link BeanDefinition}, for example, setting a lazy-init or primary flag @since 5.0
java
spring-context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java
250
[ "beanClass", "name", "qualifiers", "supplier", "customizers" ]
void
true
8
6.4
spring-projects/spring-framework
59,386
javadoc
false
splitWorker
private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) // Direct code is quicker than StringTokenizer. // Also, StringTokenizer uses isSpace() not isWhitespace() if (str == null) { return null; } final int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } final List<String> list = new ArrayList<>(); int sizePlus1 = 1; int i = 0; int start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { // Null separator means use whitespace while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else if (separatorChars.length() == 1) { // Optimize 1 character case final char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else { // standard case while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } if (match || preserveAllTokens && lastMatch) { list.add(str.substring(start, i)); } return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
Performs the logic for the {@code split} and {@code splitPreserveAllTokens} methods that return a maximum array length. @param str the String to parse, may be {@code null}. @param separatorChars the separate character. @param max the maximum number of elements to include in the array. A zero or negative value implies no limit. @param preserveAllTokens if {@code true}, adjacent separators are treated as empty token separators; if {@code false}, adjacent separators are treated as one separator. @return an array of parsed Strings, {@code null} if null String input.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
7,606
[ "str", "separatorChars", "max", "preserveAllTokens" ]
true
23
6.8
apache/commons-lang
2,896
javadoc
false
combine_hash_arrays
def combine_hash_arrays( arrays: Iterator[np.ndarray], num_items: int ) -> npt.NDArray[np.uint64]: """ Parameters ---------- arrays : Iterator[np.ndarray] num_items : int Returns ------- np.ndarray[uint64] Should be the same as CPython's tupleobject.c """ try: first = next(arrays) except StopIteration: return np.array([], dtype=np.uint64) arrays = itertools.chain([first], arrays) mult = np.uint64(1000003) out = np.zeros_like(first) + np.uint64(0x345678) last_i = 0 for i, a in enumerate(arrays): inverse_i = num_items - i out ^= a out *= mult mult += np.uint64(82520 + inverse_i + inverse_i) last_i = i assert last_i + 1 == num_items, "Fed in wrong num_items" out += np.uint64(97531) return out
Parameters ---------- arrays : Iterator[np.ndarray] num_items : int Returns ------- np.ndarray[uint64] Should be the same as CPython's tupleobject.c
python
pandas/core/util/hashing.py
48
[ "arrays", "num_items" ]
npt.NDArray[np.uint64]
true
2
6.24
pandas-dev/pandas
47,362
numpy
false