ast_errors
stringlengths
0
3.2k
d_id
int64
44
121k
id
int64
70
338k
n_whitespaces
int64
3
14k
path
stringlengths
8
134
n_words
int64
4
4.82k
n_identifiers
int64
1
131
random_cut
stringlengths
16
15.8k
commit_message
stringlengths
2
15.3k
fun_name
stringlengths
1
84
commit_id
stringlengths
40
40
repo
stringlengths
3
28
file_name
stringlengths
5
79
ast_levels
int64
6
31
nloc
int64
1
548
url
stringlengths
31
59
complexity
int64
1
66
token_counts
int64
6
2.13k
n_ast_errors
int64
0
28
vocab_size
int64
4
1.11k
n_ast_nodes
int64
15
19.2k
language
stringclasses
1 value
documentation
dict
code
stringlengths
101
62.2k
@Deprecated(message=deprecation_message) @dataclass
27,474
123,916
110
python/ray/util/ml_utils/checkpoint_manager.py
49
12
def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: if self.checkpoint_score_attribute is None: return self.checkpoint_score_attribute prefix = "" if self.checkpoint_score_order == MIN: prefix = "min-" return f"{prefix}{self.checkpoint_score_at...
[AIR] More checkpoint configurability, `Result` extension (#25943) This PR: * Allows the user to set `keep_checkpoints_num` and `checkpoint_score_attr` in `RunConfig` using the `CheckpointStrategy` dataclass * Adds two new fields to the `Result` object - `best_checkpoints` - a list of saved best checkpoints as deter...
_tune_legacy_checkpoint_score_attr
dc7ed086a5038775e378b32cb31fb4a79f418dd9
ray
checkpoint_manager.py
9
11
https://github.com/ray-project/ray.git
3
38
1
41
111
Python
{ "docstring": "Same as ``checkpoint_score_attr`` in ``tune.run``.\n\n Only used for Legacy API compatibility.\n ", "language": "en", "n_whitespaces": 25, "n_words": 11, "vocab_size": 11 }
def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: if self.checkpoint_score_attribute is None: return self.checkpoint_score_attribute prefix = "" if self.checkpoint_score_order == MIN: prefix = "min-" return f"{prefix}{self.checkpoint_score_at...
18,600
89,979
451
tests/sentry/api/endpoints/test_project_details.py
59
30
def test_dynamic_sampling_bias_activation(self): project = self.project # force creation project.update_option( "sentry:dynamic_sampling_biases", [ {"id": "boostEnvironments", "active": False}, ], ) self.login_as(self.user) ...
ref(sampling): Prettify audit logs - Part 1 (#42534)
test_dynamic_sampling_bias_activation
b83aa7328d49e5b45357417c78b7d1a63bfb056e
sentry
test_project_details.py
16
33
https://github.com/getsentry/sentry.git
1
170
0
49
293
Python
{ "docstring": "\n Tests that when sending a request to enable a dynamic sampling bias,\n the bias will be successfully enabled and the audit log 'SAMPLING_BIAS_ENABLED' will be triggered\n ", "language": "en", "n_whitespaces": 48, "n_words": 26, "vocab_size": 22 }
def test_dynamic_sampling_bias_activation(self): project = self.project # force creation project.update_option( "sentry:dynamic_sampling_biases", [ {"id": "boostEnvironments", "active": False}, ], ) self.login_as(self.user) ...
19,844
100,351
467
lib/model/layers.py
152
25
def call(self, inputs, *args, **kwargs): input_shape = K.int_shape(inputs) if len(input_shape) != 4: raise ValueError('Inputs should have rank ' + str(4) + '; Received input shape:', str(input_shape)) if self.data_fo...
Update code to support Tensorflow versions up to 2.8 (#1213) * Update maximum tf version in setup + requirements * - bump max version of tf version in launcher - standardise tf version check * update keras get_custom_objects for tf>2.6 * bugfix: force black text in GUI file dialogs (linux) * dssim loss -...
call
c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf
faceswap
layers.py
13
27
https://github.com/deepfakes/faceswap.git
6
267
0
71
406
Python
{ "docstring": "This is where the layer's logic lives.\n\n Parameters\n ----------\n inputs: tensor\n Input tensor, or list/tuple of input tensors\n args: tuple\n Additional standard keras Layer arguments\n kwargs: dict\n Additional standard keras La...
def call(self, inputs, *args, **kwargs): input_shape = K.int_shape(inputs) if len(input_shape) != 4: raise ValueError('Inputs should have rank ' + str(4) + '; Received input shape:', str(input_shape)) if self.data_fo...
40,250
168,239
137
pandas/core/indexes/base.py
40
15
def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: warnings.warn( "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, stacklevel=find_stack_level(inspect.currentf...
PERF cache find_stack_level (#48023) cache stacklevel
to_native_types
2f8d0a36703e81e4dca52ca9fe4f58c910c1b304
pandas
base.py
12
37
https://github.com/pandas-dev/pandas.git
2
61
0
37
100
Python
{ "docstring": "\n Format specified values of `self` and return them.\n\n .. deprecated:: 1.2.0\n\n Parameters\n ----------\n slicer : int, array-like\n An indexer into `self` that specifies which values\n are used in the formatting process.\n kwargs : d...
def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: warnings.warn( "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, stacklevel=find_stack_level(inspect.currentf...
42,266
177,079
76
networkx/algorithms/distance_measures.py
44
14
def periphery(G, e=None, usebounds=False, weight=None): if usebounds is True and e is None and not G.is_directed(): return _extrema_bounding(G, compute="periphery", weight=weight)
Add weight distance metrics (#5305) Adds the weight keyword argument to allow users to compute weighted distance metrics e.g. diameter, eccentricity, periphery, etc. The kwarg works in the same fashion as the weight param for shortest paths - i.e. if a string, look up with edge attr by key, if callable, compute the...
periphery
28f78cfa9a386620ee1179582fda1db5ffc59f84
networkx
distance_measures.py
11
8
https://github.com/networkx/networkx.git
7
90
0
31
140
Python
{ "docstring": "Returns the periphery of the graph G.\n\n The periphery is the set of nodes with eccentricity equal to the diameter.\n\n Parameters\n ----------\n G : NetworkX graph\n A graph\n\n e : eccentricity dictionary, optional\n A precomputed dictionary of eccentricities.\n\n weigh...
def periphery(G, e=None, usebounds=False, weight=None): if usebounds is True and e is None and not G.is_directed(): return _extrema_bounding(G, compute="periphery", weight=weight) if e is None: e = eccentricity(G, weight=weight) diameter = max(e.values()) p = [v for v in e if e[v] =...
91,294
292,193
74
homeassistant/components/zwave_js/climate.py
30
10
def _current_mode_setpoint_enums(self) -> list[ThermostatSetpointType | None]: if self._current_mode is None: # Thermostat(valve) with no support for setting a mode is considered heating-only return [ThermostatSetpointType.HEATING] return THERMOSTA
Add type ignore error codes [N-Z] (#66779)
_current_mode_setpoint_enums
67e94f2b4ba614a37544f54ccb85984f0d600376
core
climate.py
11
5
https://github.com/home-assistant/core.git
2
43
0
27
71
Python
{ "docstring": "Return the list of enums that are relevant to the current thermostat mode.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 12 }
def _current_mode_setpoint_enums(self) -> list[ThermostatSetpointType | None]: if self._current_mode is None: # Thermostat(valve) with no support for setting a mode is considered heating-only return [ThermostatSetpointType.HEATING] return THERMOSTAT_MODE_SETPOINT_MAP.get...
13,281
63,386
54
.venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py
25
7
def line(loc, strg): lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[lastCR + 1:]
upd; format
line
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
pyparsing.py
11
7
https://github.com/jindongwang/transferlearning.git
2
54
0
19
90
Python
{ "docstring": "Returns the line of text containing loc within a string, counting newlines as line separators.\n ", "language": "en", "n_whitespaces": 21, "n_words": 15, "vocab_size": 14 }
def line(loc, strg): lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[lastCR + 1:]
21,445
102,080
150
lib/sysinfo.py
37
13
def _parse_configs(self, config_files): formatted = "" for cfile in config_files: fname = os.path.basename(cfile) ext = os.path.splitext(cfile)[1] formatted += f"\n--------- {fname} ---------\n" if ext == ".ini":
Allow decoding errors
_parse_configs
48c886b3dce3d3117ad16edaf35c8abd28dc51f5
faceswap
sysinfo.py
13
11
https://github.com/deepfakes/faceswap.git
4
71
0
26
127
Python
{ "docstring": " Parse the given list of config files into a human readable format.\n\n Parameters\n ----------\n config_files: list\n A list of paths to the faceswap config files\n\n Returns\n -------\n str\n The current configuration in the config file...
def _parse_configs(self, config_files): formatted = "" for cfile in config_files: fname = os.path.basename(cfile) ext = os.path.splitext(cfile)[1] formatted += f"\n--------- {fname} ---------\n" if ext == ".ini": formatted += self....
43,685
181,946
57
src/textual/dom.py
18
6
def parent(self) -> DOMNode: if self._parent is None: raise NoParent(f"{self} has no parent") assert isinstance(self._parent, DOMNode) return self._parent
docstrings and tidy
parent
2635f58e7c3d10b161ee69a15ebfe6499ac26daa
textual
dom.py
11
13
https://github.com/Textualize/textual.git
2
34
0
17
60
Python
{ "docstring": "Get the parent node.\n\n Raises:\n NoParent: If this is the root node.\n\n Returns:\n DOMNode: The node which is the direct parent of this node.\n ", "language": "en", "n_whitespaces": 67, "n_words": 24, "vocab_size": 17 }
def parent(self) -> DOMNode: if self._parent is None: raise NoParent(f"{self} has no parent") assert isinstance(self._parent, DOMNode) return self._parent
3,287
20,236
88
pipenv/patched/notpip/_vendor/platformdirs/unix.py
23
11
def user_documents_dir(self) -> str: documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR") if documents_dir is None: documents_dir = os.environ.get("XDG_DOCUMENTS_DIR", "").strip() if not documents_dir: documents_dir = os.path.ex
check point progress on only bringing in pip==22.0.4 (#4966) * vendor in pip==22.0.4 * updating vendor packaging version * update pipdeptree to fix pipenv graph with new version of pip. * Vendoring of pip-shims 0.7.0 * Vendoring of requirementslib 1.6.3 * Update pip index safety restrictions patch for p...
user_documents_dir
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
unix.py
13
10
https://github.com/pypa/pipenv.git
3
51
0
16
93
Python
{ "docstring": "\n :return: documents directory tied to the user, e.g. ``~/Documents``\n ", "language": "en", "n_whitespaces": 24, "n_words": 9, "vocab_size": 9 }
def user_documents_dir(self) -> str: documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR") if documents_dir is None: documents_dir = os.environ.get("XDG_DOCUMENTS_DIR", "").strip() if not documents_dir: documents_dir = os.path.expanduser("~/Documents...
76,025
259,992
230
sklearn/ensemble/tests/test_iforest.py
65
27
def test_iforest_sparse(global_random_seed): rng = check_random_state(global_random_seed) X_train, X_test = train_test_split(diabetes.data[:50], random_state=rng) grid = ParameterGrid({"m
TST use global_random_seed in sklearn/ensemble/tests/test_iforest.py (#22901) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr> Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org>
test_iforest_sparse
6ca1f5e4d0d16bc9a7f28582079a15e14f012719
scikit-learn
test_iforest.py
15
17
https://github.com/scikit-learn/scikit-learn.git
3
144
0
47
221
Python
{ "docstring": "Check IForest for various parameter settings on sparse input.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_iforest_sparse(global_random_seed): rng = check_random_state(global_random_seed) X_train, X_test = train_test_split(diabetes.data[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "bootstrap": [True, False]}) for sparse_format in [csc_matrix, csr_matrix]: X_...
75,703
259,304
76
sklearn/metrics/_scorer.py
41
17
def get_scorer_names():
API get_scorer returns a copy and introduce get_scorer_names (#22866)
get_scorer_names
7dc97a378ecbfa056dd9cfa9d1ef4c07d2d0cc1f
scikit-learn
_scorer.py
11
2
https://github.com/scikit-learn/scikit-learn.git
1
14
0
35
171
Python
{ "docstring": "Get the names of all available scorers.\n\n These names can be passed to :func:`~sklearn.metrics.get_scorer` to\n retrieve the scorer object.\n\n Returns\n -------\n list of str\n Names of all available scorers.\n ", "language": "en", "n_whitespaces": 54, "n_words": 29, ...
def get_scorer_names(): return sorted(_SCORERS.keys()) for name, metric in [ ("precision", precision_score), ("recall", recall_score), ("f1", f1_score), ("jaccard", jaccard_score), ]: _SCORERS[name] = make_scorer(metric, average="binary") for average in ["macro", "micro", "samples", "...
22,155
105,541
317
datasets/swda/swda.py
95
21
def _split_generators(self, dl_manager): # Download extract and return path of data file. dl_dir = dl_manager.download_and_extract(_URL) # Use swda/ folder. data_dir = os.path.join(dl_dir, "swda") # Handle partitions files: download extract and return paths of split fil...
Support streaming swda dataset (#4914) * Support streaming swda dataset * Remove unused import
_split_generators
f10d38b8b60b09a633823a2fb2529c83933b9c80
datasets
swda.py
13
16
https://github.com/huggingface/datasets.git
1
126
0
51
211
Python
{ "docstring": "\n Returns SplitGenerators.\n This method is tasked with downloading/extracting the data and defining the splits.\n\n Args:\n dl_manager (:obj:`datasets.utils.download_manager.DownloadManager`):\n Download manager to download and extract data files from ...
def _split_generators(self, dl_manager): # Download extract and return path of data file. dl_dir = dl_manager.download_and_extract(_URL) # Use swda/ folder. data_dir = os.path.join(dl_dir, "swda") # Handle partitions files: download extract and return paths of split fil...
83,838
281,540
30
gamestonk_terminal/stocks/discovery/disc_controller.py
8
7
def print_help(self): help
Terminal Wide Rich (#1161) * My idea for how we handle Rich moving forward * remove independent consoles * FIxed pylint issues * add a few vars * Switched print to console * More transitions * Changed more prints * Replaced all prints * Fixing tabulate * Finished replace tabulate * Finish...
print_help
82747072c511beb1b2672846ae2ee4aec53eb562
OpenBBTerminal
disc_controller.py
9
31
https://github.com/OpenBB-finance/OpenBBTerminal.git
1
21
0
8
40
Python
{ "docstring": "Print help[cmds]\n[src][Geek of Wall St][/src]\n rtearn realtime earnings from and expected moves\n[src][Finnhub][/src]\n pipo past IPOs dates\n fipo future IPOs dates\n[src][Yahoo Finance][/src]\n gainers show latest top gainers\n losers show ...
def print_help(self): help_text = console.print(text=help_text, menu="Stocks - Discovery")
50,874
204,760
308
django/core/serializers/xml_serializer.py
60
22
def handle_fk_field(self, obj, field): self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: if self.use_natural_foreign_keys and hasattr( field.remote_field.model, "natural_key" ): ...
Refs #33476 -- Reformatted code with Black.
handle_fk_field
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
xml_serializer.py
15
18
https://github.com/django/django.git
5
133
0
50
225
Python
{ "docstring": "\n Handle a ForeignKey (they need to be treated slightly\n differently from regular fields).\n ", "language": "en", "n_whitespaces": 35, "n_words": 13, "vocab_size": 13 }
def handle_fk_field(self, obj, field): self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: if self.use_natural_foreign_keys and hasattr( field.remote_field.model, "natural_key" ): ...
28,528
127,793
130
python/ray/tests/test_metrics_head.py
24
8
def test_metrics_folder(): with _ray_start(include_dashboard=True) as context: session_dir = context["session_dir"] assert os.path.exists( f"{session_dir}/metrics/grafana/provisioning/dashboards/default.yml" ) assert os.path.exists( f"{session_dir}/metric...
Export default configurations for grafana and prometheus (#28286)
test_metrics_folder
42da4445e7a3cb358a1a02ae433a004e9fa836b5
ray
test_metrics_head.py
12
14
https://github.com/ray-project/ray.git
1
62
0
17
126
Python
{ "docstring": "\n Tests that the default dashboard files get created.\n ", "language": "en", "n_whitespaces": 15, "n_words": 8, "vocab_size": 8 }
def test_metrics_folder(): with _ray_start(include_dashboard=True) as context: session_dir = context["session_dir"] assert os.path.exists( f"{session_dir}/metrics/grafana/provisioning/dashboards/default.yml" ) assert os.path.exists( f"{session_dir}/metric...
7,049
38,931
150
deepspeed/runtime/fp16/fused_optimizer.py
44
12
def state_dict(self): state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict['cur_iter'] = self.cur_iter if state_dict['dynamic_loss_scale']: state_dict['last_overflow_iter'] = self.last_...
[ZeRO] Default disable elastic ckpt in stage 1+2 and reduce CPU memory overhead during ckpt load (#1525) Co-authored-by: Olatunji Ruwase <olruwase@microsoft.com>
state_dict
3293cf72a0abd5cf77a831996bd054bc908476a6
DeepSpeed
fused_optimizer.py
10
13
https://github.com/microsoft/DeepSpeed.git
2
94
0
34
166
Python
{ "docstring": "\n Returns a dict containing the current state of this :class:`FP16_Optimizer` instance.\n This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict\n of the contained Pytorch optimizer.\n Example::\n checkpoint = {}\n checkpo...
def state_dict(self): state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict['cur_iter'] = self.cur_iter if state_dict['dynamic_loss_scale']: state_dict['last_overflow_iter'] = self.last_...
77,021
261,829
402
sklearn/naive_bayes.py
162
24
def _update_mean_variance(n_past, mu, var, X, sample_weight=None): if X.shape[0] == 0: return mu, var # Compute (potentially weighted) mean and variance of new datapoints if sample_weight is not None: n_new = float(sample_weight.sum()) if np.isclose(...
TST Add common tests for single class fitting induced by sample weights (#24140) Co-authored-by: johayon <johayon.math@gmail.com> Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
_update_mean_variance
2cce02414d4a7161f0d105450c196d94b1182220
scikit-learn
naive_bayes.py
13
22
https://github.com/scikit-learn/scikit-learn.git
5
204
0
81
314
Python
{ "docstring": "Compute online update of Gaussian mean and variance.\n\n Given starting sample count, mean, and variance, a new set of\n points X, and optionally sample weights, return the updated mean and\n variance. (NB - each dimension (column) in X is treated as independent\n -- you ge...
def _update_mean_variance(n_past, mu, var, X, sample_weight=None): if X.shape[0] == 0: return mu, var # Compute (potentially weighted) mean and variance of new datapoints if sample_weight is not None: n_new = float(sample_weight.sum()) if np.isclose(...
48,393
197,220
50
sympy/functions/combinatorial/numbers.py
9
6
def is_prime(n): sympy_deprecation_warning( ,
Deprecate redundant static methods
is_prime
b27e2b44626d138bd6ea235fbf114644baa5b144
sympy
numbers.py
9
10
https://github.com/sympy/sympy.git
1
23
0
9
41
Python
{ "docstring": "\nis_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that\ndirectly instead.\n ", "language": "en", "n_whitespaces": 18, "n_words": 12, "vocab_size": 12 }
def is_prime(n): sympy_deprecation_warning( , deprecated_since_version="1.11", active_deprecations_target='deprecated-carmichael-static-methods', ) return isprime(n)
56,186
221,074
16
python3.10.4/Lib/base64.py
12
7
def standard_b64decode(s): return b64decode(s) _urlsafe_encode_tr
add python 3.10.4 for windows
standard_b64decode
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
base64.py
7
2
https://github.com/XX-net/XX-Net.git
1
11
0
11
59
Python
{ "docstring": "Decode bytes encoded with the standard Base64 alphabet.\n\n Argument s is a bytes-like object or ASCII string to decode. The result\n is returned as a bytes object. A binascii.Error is raised if the input\n is incorrectly padded. Characters that are not in the standard alphabet\n are di...
def standard_b64decode(s): return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/')
29,975
133,298
98
python/ray/util/sgd/torch/examples/dcgan.py
29
20
def inception_score(self, imgs, batch_size=32, splits=1): N = len(imgs) dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) up = nn.Upsample( size=(28, 28), mo
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
inception_score
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
dcgan.py
12
25
https://github.com/ray-project/ray.git
4
236
0
27
105
Python
{ "docstring": "Calculate the inception score of the generated images.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 7 }
def inception_score(self, imgs, batch_size=32, splits=1): N = len(imgs) dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) up = nn.Upsample( size=(28, 28), mode="bilinear", align_corners=False, # This is to reduce user warnings fro...
14,354
66,833
9
erpnext/patches/v13_0/update_shipment_status.py
17
5
def execute(): frappe.reload_doc("stock", "doctype", "shipment") # update submitted status frappe.db.sql( )
style: format code with black
execute
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
update_shipment_status.py
8
12
https://github.com/frappe/erpnext.git
1
30
0
12
60
Python
{ "docstring": "UPDATE `tabShipment`\n\t\t\t\t\tSET status = \"Submitted\"\n\t\t\t\t\tWHERE status = \"Draft\" AND docstatus = 1UPDATE `tabShipment`\n\t\t\t\t\tSET status = \"Cancelled\"\n\t\t\t\t\tWHERE status = \"Draft\" AND docstatus = 2", "language": "en", "n_whitespaces": 22, "n_words": 27, "vocab_size":...
def execute(): frappe.reload_doc("stock", "doctype", "shipment") # update submitted status frappe.db.sql( ) # update cancelled status frappe.db.sql( )
50,753
204,496
26
django/core/files/storage.py
12
4
def url(self, name): raise NotImplementedError("subclasses of Storage must provide a url() method
Refs #33476 -- Reformatted code with Black.
url
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
storage.py
8
2
https://github.com/django/django.git
1
13
0
12
25
Python
{ "docstring": "\n Return an absolute URL where the file's contents can be accessed\n directly by a web browser.\n ", "language": "en", "n_whitespaces": 38, "n_words": 16, "vocab_size": 16 }
def url(self, name): raise NotImplementedError("subclasses of Storage must provide a url() method")
81,491
275,866
227
keras/saving/hdf5_format.py
57
10
def load_attributes_from_hdf5_group(group, name): if name in group.
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
load_attributes_from_hdf5_group
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
hdf5_format.py
17
18
https://github.com/keras-team/keras.git
7
107
0
34
174
Python
{ "docstring": "Loads attributes of the specified name from the HDF5 group.\n\n This method deals with an inherent problem\n of HDF5 file which is not able to store\n data larger than HDF5_OBJECT_HEADER_LIMIT bytes.\n\n Args:\n group: A pointer to a HDF5 group.\n name: A name of the attribut...
def load_attributes_from_hdf5_group(group, name): if name in group.attrs: data = [ n.decode("utf8") if hasattr(n, "decode") else n for n in group.attrs[name] ] else: data = [] chunk_id = 0 while "%s%d" % (name, chunk_id) in group.attrs: ...
11,429
55,970
140
src/prefect/orion/models/block_schemas.py
21
6
def _find_root_block_schema(block_schemas_with_references): return next( ( block_schema for ( block_schema, _, parent_block_schema_id, ) in block_schemas_with_references if parent_block_schema_
Nested Block Schemas (PrefectHQ/orion#1846) * Adds models and migration for block schema and block document references * Adds customization to the generation of a block schema's fields * Adds ability to reconstruct block schema fields on read * Adds ability to reconstruct block schema when read by checksum ...
_find_root_block_schema
a05e44c89acf0b6073ac876479be24a5e51d7754
prefect
block_schemas.py
10
13
https://github.com/PrefectHQ/prefect.git
3
31
0
19
46
Python
{ "docstring": "\n Attempts to find the root block schema from a list of block schemas\n with references. Returns None if a root block schema is not found.\n Returns only the first potential root block schema if multiple are found.\n ", "language": "en", "n_whitespaces": 50, "n_words": 37, "vocab_...
def _find_root_block_schema(block_schemas_with_references): return next( ( block_schema for ( block_schema, _, parent_block_schema_id, ) in block_schemas_with_references if parent_block_schema_id is None ...
4,866
25,203
465
ppocr/modeling/heads/local_graph.py
162
32
def feature_embedding(input_feats, out_feat_len): assert input_feats.ndim == 2 assert isinstance(out_feat_len, int) assert out_feat_len >= input_feats.shape[1] num_nodes = input_feats.shape[0] feat_dim = input_feats.shape[1] feat_repeat_times = out_feat_len // feat_dim residue_dim = ou...
add drrg
feature_embedding
1f9400dd7374ce9cc47981372e324ff412e53ba3
PaddleOCR
local_graph.py
20
41
https://github.com/PaddlePaddle/PaddleOCR.git
4
416
0
79
639
Python
{ "docstring": "Embed features. This code was partially adapted from\n https://github.com/GXYM/DRRG licensed under the MIT license.\n\n Args:\n input_feats (ndarray): The input features of shape (N, d), where N is\n the number of nodes in graph, d is the input feature vector length.\n o...
def feature_embedding(input_feats, out_feat_len): assert input_feats.ndim == 2 assert isinstance(out_feat_len, int) assert out_feat_len >= input_feats.shape[1] num_nodes = input_feats.shape[0] feat_dim = input_feats.shape[1] feat_repeat_times = out_feat_len // feat_dim residue_dim = ou...
76,622
261,007
71
sklearn/linear_model/_base.py
29
18
def decision_function(self, X): check_is_fitted(self) xp, _ = get_namespace(X) X = s
ENH Adds Array API support to LinearDiscriminantAnalysis (#22554) Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org> Co-authored-by: Julien Jerphanion <git@jjerphan.xyz>
decision_function
2710a9e7eefd2088ce35fd2fb6651d5f97e5ef8b
scikit-learn
_base.py
11
6
https://github.com/scikit-learn/scikit-learn.git
2
77
0
26
119
Python
{ "docstring": "\n Predict confidence scores for samples.\n\n The confidence score for a sample is proportional to the signed\n distance of that sample to the hyperplane.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n ...
def decision_function(self, X): check_is_fitted(self) xp, _ = get_namespace(X) X = self._validate_data(X, accept_sparse="csr", reset=False) scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return xp.reshape(scores, -1) if scores.shape[1] ==...
54,671
216,630
63
backend/postprocessing/rankings.py
38
11
def get_ranking(pairs): if len(pairs) == 1: return list(
ran pre-commit hook
get_ranking
38ca08446d560797522b7828720032799584d32a
Open-Assistant
rankings.py
11
6
https://github.com/LAION-AI/Open-Assistant.git
4
61
0
33
98
Python
{ "docstring": "\n Abuses concordance property to get a (not necessarily unqiue) ranking.\n The lack of uniqueness is due to the potential existance of multiple\n equally ranked winners. We have to pick one, which is where\n the non-uniqueness comes from\n ", "language": "en", "n_whitespaces": 53, ...
def get_ranking(pairs): if len(pairs) == 1: return list(pairs[0]) w = get_winner(pairs) # now remove the winner from the list of pairs p_new = np.array([(a, b) for a, b in pairs if a != w]) return [w] + get_ranking(p_new)
12,476
61,263
63
.venv/lib/python3.8/site-packages/pip/_internal/utils/misc.py
31
9
def backup_dir(dir, ext=".bak"): # type: (str, str) -> str n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extens
upd; format
backup_dir
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
misc.py
11
7
https://github.com/jindongwang/transferlearning.git
2
43
0
22
74
Python
{ "docstring": "Figure out the name of a directory to back up the given dir to\n (adding .bak, .bak2, etc)", "language": "en", "n_whitespaces": 20, "n_words": 18, "vocab_size": 16 }
def backup_dir(dir, ext=".bak"): # type: (str, str) -> str n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension
32,051
140,580
147
rllib/utils/filter_manager.py
42
22
def synchronize(local_filters, remotes, update_remote=True): remote_filters = ray.get( [r.get_filters.remote(flush_
Clean up docstyle in python modules and add LINT rule (#25272)
synchronize
905258dbc19753c81039f993477e7ab027960729
ray
filter_manager.py
12
11
https://github.com/ray-project/ray.git
7
107
0
30
164
Python
{ "docstring": "Aggregates all filters from remote evaluators.\n\n Local copy is updated and then broadcasted to all remote evaluators.\n\n Args:\n local_filters: Filters to be synchronized.\n remotes: Remote evaluators with filters.\n update_remote: Whether to push upda...
def synchronize(local_filters, remotes, update_remote=True): remote_filters = ray.get( [r.get_filters.remote(flush_after=True) for r in remotes] ) for rf in remote_filters: for k in local_filters: local_filters[k].apply_changes(rf[k], with_buffer=...
76,986
261,775
37
sklearn/tests/test_base.py
19
11
def test_estimator_empty_instance_dict(estimator): state = estimator.__getstate__() expected = {"_sklearn_version": sklearn.__version__} assert state == expected # this should not raise pickle.loads(pickle.dumps(BaseEstimator()))
FIX fix pickling for empty object with Python 3.11+ (#25188) Co-authored-by: Adrin Jalali <adrin.jalali@gmail.com> Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> Python 3.11 introduces `__getstate__` on the `object` level, which breaks our existing `__getstate__` code for objects w/o any attributes. T...
test_estimator_empty_instance_dict
9017c701833114a75903f580dd0772e1d8d7d125
scikit-learn
test_base.py
11
5
https://github.com/scikit-learn/scikit-learn.git
1
39
0
16
70
Python
{ "docstring": "Check that ``__getstate__`` returns an empty ``dict`` with an empty\n instance.\n\n Python 3.11+ changed behaviour by returning ``None`` instead of raising an\n ``AttributeError``. Non-regression test for gh-25188.\n ", "language": "en", "n_whitespaces": 39, "n_words": 27, "vocab_s...
def test_estimator_empty_instance_dict(estimator): state = estimator.__getstate__() expected = {"_sklearn_version": sklearn.__version__} assert state == expected # this should not raise pickle.loads(pickle.dumps(BaseEstimator()))
16,740
78,234
42
wagtail/admin/tests/test_templatetags.py
13
9
def test_with_variables(self): context = Context({"name": "j
Introduce new template fragment composition tags
test_with_variables
524cab82e33b43463b746c3df1a80657b3ae874a
wagtail
test_templatetags.py
11
15
https://github.com/wagtail/wagtail.git
1
37
0
11
68
Python
{ "docstring": "\n {% load wagtailadmin_tags %}\n {% fragment as my_fragment %}\n <p>Hello, {{ name|title }}</p>\n {% endfragment %}\n Text coming after:\n {{ my_fragment }}\n \n Text coming after:\n <p>Hello, Jonathan ...
def test_with_variables(self): context = Context({"name": "jonathan wells"}) template = expected = self.assertHTMLEqual(expected, Template(template).render(context))
78,390
266,422
122
lib/ansible/executor/module_common.py
54
15
def _extract_interpreter(b_module_data): interpreter = None args = [] b_lines = b_module_data.split(b"\n", 1) if b_lines[0].startswith(b"#!"): b_shebang = b_lines[0].strip() # shlex.split on python-2.6 needs bytes. On python-3.x it needs text cli_split =
Allow specifying specific python via shebang (#76677) modules with python were always normalized to /usr/bin/python, while other interpreters could have specific versions. * now shebang is always constructed by get_shebang and args are preserved * only update shebang if interpreter changed * updated test e...
_extract_interpreter
9142be2f6cabbe6597c9254c5bb9186d17036d55
ansible
module_common.py
14
11
https://github.com/ansible/ansible.git
3
98
0
39
162
Python
{ "docstring": "\n Used to extract shebang expression from binary module data and return a text\n string with the shebang, or None if no shebang is detected.\n ", "language": "en", "n_whitespaces": 34, "n_words": 24, "vocab_size": 23 }
def _extract_interpreter(b_module_data): interpreter = None args = [] b_lines = b_module_data.split(b"\n", 1) if b_lines[0].startswith(b"#!"): b_shebang = b_lines[0].strip() # shlex.split on python-2.6 needs bytes. On python-3.x it needs text cli_split = shlex.split(to_na...
28,198
126,557
72
python/ray/tune/tests/test_tune_restore.py
26
9
def test_resource_exhausted_info(self):
[tune] Fix test_resource_exhausted_info test (#27426) #27213 broke this test Signed-off-by: Kai Fricke <kai@anyscale.com>
test_resource_exhausted_info
46ed3557ba6b4f4f72c15ef960aba5270ada2a9c
ray
test_tune_restore.py
11
11
https://github.com/ray-project/ray.git
2
51
0
25
56
Python
{ "docstring": "This is to test if helpful information is displayed when\n the objects captured in trainable/training function are too\n large and RESOURCES_EXHAUSTED error of gRPC is triggered.", "language": "en", "n_whitespaces": 39, "n_words": 26, "vocab_size": 24 }
def test_resource_exhausted_info(self): # generate some random data to be captured implicitly in training func. from sklearn.datasets import fetch_olivetti_faces a_large_array = [] for i in range(50): a_large_array.append(fetch_olivetti_faces())
11,268
55,193
394
tests/conftest.py
77
22
def testing_session_settings(): with tempfile.TemporaryDirectory() as tmpdir: profile = prefect.settings.Profile( name="test-session", settings={ # Set PREFECT_HOME to a temporary directory to avoid clobbering # environments and settings ...
Squash issues with tests
testing_session_settings
4adc737611ffa284d9952779ba2f68174a7e73cc
prefect
conftest.py
14
21
https://github.com/PrefectHQ/prefect.git
1
87
0
62
146
Python
{ "docstring": "\n Creates a fixture for the scope of the test session that modifies setting defaults.\n\n This ensures that tests are isolated from existing settings, databases, etc.\n ", "language": "en", "n_whitespaces": 35, "n_words": 25, "vocab_size": 23 }
def testing_session_settings(): with tempfile.TemporaryDirectory() as tmpdir: profile = prefect.settings.Profile( name="test-session", settings={ # Set PREFECT_HOME to a temporary directory to avoid clobbering # environments and settings ...
34,592
149,925
25
tests/strategy/strats/hyperoptable_strategy.py
11
7
def bot_start(self, **kwargs) -> None: self.buy_rsi =
Enhance hyperoptable strategy to test instance parameters
bot_start
5bf021be2e8f1479753e66573575fa7cde00a2b6
freqtrade
hyperoptable_strategy.py
10
5
https://github.com/freqtrade/freqtrade.git
1
31
0
11
50
Python
{ "docstring": "\n Parameters can also be defined here ...\n ", "language": "en", "n_whitespaces": 22, "n_words": 7, "vocab_size": 7 }
def bot_start(self, **kwargs) -> None: self.buy_rsi = IntParameter([0, 50], default=30, space='buy')
50,864
204,736
33
django/core/serializers/base.py
8
5
def getvalue(self): if callable(getattr(self.stream, "getvalue", None)): return self.stream.getvalue()
Refs #33476 -- Reformatted code with Black.
getvalue
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
base.py
10
3
https://github.com/django/django.git
2
29
0
8
50
Python
{ "docstring": "\n Return the fully serialized queryset (or None if the output stream is\n not seekable).\n ", "language": "en", "n_whitespaces": 36, "n_words": 14, "vocab_size": 13 }
def getvalue(self): if callable(getattr(self.stream, "getvalue", None)): return self.stream.getvalue()
22,470
106,845
450
py/visdom/__init__.py
106
24
def boxplot(self, X, win=None, env=None, opts=None): X = np.squeeze(X) assert X.ndim == 1 or X.ndim == 2, "X should be one or two-dimensional" if X.ndim == 1: X = X[:, None] opts = {} if opts is None else opts _title2str(opts) _assert_opts(opts) ...
apply black py to all python files
boxplot
5b8b7f267cfaf76a2a39a727ef31a62b3909a093
visdom
__init__.py
14
32
https://github.com/fossasia/visdom.git
7
215
0
82
357
Python
{ "docstring": "\n This function draws boxplots of the specified data. It takes as input\n an `N` or an `NxM` tensor `X` that specifies the `N` data values of\n which to construct the `M` boxplots.\n\n The following plot-specific `opts` are currently supported:\n - `opts.legend`: la...
def boxplot(self, X, win=None, env=None, opts=None): X = np.squeeze(X) assert X.ndim == 1 or X.ndim == 2, "X should be one or two-dimensional" if X.ndim == 1: X = X[:, None] opts = {} if opts is None else opts _title2str(opts) _assert_opts(opts) ...
50,282
203,275
248
tests/requests/tests.py
65
12
def test_body_after_POST_multipart_related(self): # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', ...
Refs #33476 -- Refactored problematic code before reformatting by Black. In these cases Black produces unexpected results, e.g. def make_random_password( self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789', ): or cursor.execute(""" SELECT ... """, ...
test_body_after_POST_multipart_related
c5cd8783825b5f6384417dac5f3889b4210b7d08
django
tests.py
12
17
https://github.com/django/django.git
1
83
0
58
146
Python
{ "docstring": "\n Reading body after parsing multipart that isn't form-data is allowed\n ", "language": "en", "n_whitespaces": 25, "n_words": 10, "vocab_size": 10 }
def test_body_after_POST_multipart_related(self): # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', ...
8,978
46,739
172
airflow/providers/arangodb/hooks/arangodb.py
39
13
def query(self, query, **kwargs) -> Result: try: if self.db_conn: result = self.db_conn.aql.execute(query, **kwargs) return result else: raise AirflowException( f"Failed to execute AQLQuery, error connecting to ...
Adding ArangoDB Provider (#22548) * Adding ArangoDB Provider
query
c758c76ac336c054fd17d4b878378aa893b7a979
airflow
arangodb.py
15
18
https://github.com/apache/airflow.git
3
56
0
31
109
Python
{ "docstring": "\n Function to create a arangodb session\n and execute the AQL query in the session.\n\n :param query: AQL query\n :return: Result\n ", "language": "en", "n_whitespaces": 56, "n_words": 20, "vocab_size": 17 }
def query(self, query, **kwargs) -> Result: try: if self.db_conn: result = self.db_conn.aql.execute(query, **kwargs) return result else: raise AirflowException( f"Failed to execute AQLQuery, error connecting to ...
75,968
259,883
192
sklearn/datasets/tests/test_arff_parser.py
64
14
def test_post_process_frame(feature_names, target_names): pd = pytest.importorskip("pandas") X_original = pd.DataFrame( { "col_int_as_integer": [1, 2, 3], "col_int_as_numeric": [1, 2, 3], "col_float_as_real": [1.0, 2.0, 3.0], "col_float_as_numeric": ...
ENH improve ARFF parser using pandas (#21938) Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> Co-authored-by: Olivier Grisel <olivier.grisel@gmail.com> Co-authored-by: Adrin Jalali <adrin.jalali@gmail.com>
test_post_process_frame
a47d569e670fd4102af37c3165c9b1ddf6fd3005
scikit-learn
test_arff_parser.py
12
20
https://github.com/scikit-learn/scikit-learn.git
3
158
0
46
233
Python
{ "docstring": "Check the behaviour of the post-processing function for splitting a dataframe.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 10 }
def test_post_process_frame(feature_names, target_names): pd = pytest.importorskip("pandas") X_original = pd.DataFrame( { "col_int_as_integer": [1, 2, 3], "col_int_as_numeric": [1, 2, 3], "col_float_as_real": [1.0, 2.0, 3.0], "col_float_as_numeric": ...
51,718
206,806
222
django/views/debug.py
64
19
def cleanse_setting(self, key, value): try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False if is_sensitive: cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: s...
Refs #33476 -- Reformatted code with Black.
cleanse_setting
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
debug.py
15
18
https://github.com/django/django.git
10
138
0
37
219
Python
{ "docstring": "\n Cleanse an individual setting key/value of sensitive content. If the\n value is a dictionary, recursively cleanse the keys in that dictionary.\n ", "language": "en", "n_whitespaces": 43, "n_words": 21, "vocab_size": 20 }
def cleanse_setting(self, key, value): try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False if is_sensitive: cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: s...
81,751
276,840
105
keras/utils/generic_utils.py
42
20
def func_dump(func): if os.name == "nt": raw_code = marshal.dumps(func.__code__).replace(b"\\", b"/") code = codecs.encode(raw_code, "base64").decode("ascii") else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
func_dump
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
generic_utils.py
14
13
https://github.com/keras-team/keras.git
4
109
0
28
185
Python
{ "docstring": "Serializes a user defined function.\n\n Args:\n func: the function to serialize.\n\n Returns:\n A tuple `(code, defaults, closure)`.\n ", "language": "en", "n_whitespaces": 40, "n_words": 17, "vocab_size": 17 }
def func_dump(func): if os.name == "nt": raw_code = marshal.dumps(func.__code__).replace(b"\\", b"/") code = codecs.encode(raw_code, "base64").decode("ascii") else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_code, "base64").decode("ascii") defaults ...
47,486
195,948
56
sympy/polys/polyclasses.py
13
7
def cauchy_upper_bound(f): if not f.lev:
Add new methods to `DMP` class, corresp. to new funcs.
cauchy_upper_bound
d032a7a870672667f778be8bf02a3eba4ae89381
sympy
polyclasses.py
11
5
https://github.com/sympy/sympy.git
2
30
0
13
53
Python
{ "docstring": "Computes the Cauchy upper bound on the roots of ``f``. ", "language": "en", "n_whitespaces": 10, "n_words": 10, "vocab_size": 9 }
def cauchy_upper_bound(f): if not f.lev: return dup_cauchy_upper_bound(f.rep, f.dom) else: raise ValueError('univariate polynomial expected')
48,459
197,316
868
sympy/core/sympify.py
288
29
def kernS(s): hit = False quoted = '"' in s or "'" in s if '(' in s and not quoted: if s.count('(') != s.count(")"): raise SympifyError('unmatched left parenthesis') # strip all space from s s = ''.join(s.split()) olds = s # now use space to represen...
Remove abbreviations in documentation
kernS
65be461082dda54c8748922f9c29a19af1279fe1
sympy
sympify.py
16
53
https://github.com/sympy/sympy.git
17
307
0
166
535
Python
{ "docstring": "Use a hack to try keep autosimplification from distributing a\n a number into an Add; this modification does not\n prevent the 2-arg Mul from becoming an Add, however.\n\n Examples\n ========\n\n >>> from sympy.core.sympify import kernS\n >>> from sympy.abc import x, y\n\n The 2-a...
def kernS(s): hit = False quoted = '"' in s or "'" in s if '(' in s and not quoted: if s.count('(') != s.count(")"): raise SympifyError('unmatched left parenthesis') # strip all space from s s = ''.join(s.split()) olds = s # now use space to represen...
117,007
319,856
56
src/documents/tests/test_classifier.py
17
11
def test_load_corrupt_file(self, patched_pickle_load): # First load is the schema version p
Updates the classifier to catch warnings from scikit-learn and rebuild the model file when this happens
test_load_corrupt_file
77fbbe95ffb965525136982846f50e3ad8244de9
paperless-ngx
test_classifier.py
10
4
https://github.com/paperless-ngx/paperless-ngx.git
1
36
0
17
63
Python
{ "docstring": "\n GIVEN:\n - Corrupted classifier pickle file\n WHEN:\n - An attempt is made to load the classifier\n THEN:\n - The ClassifierModelCorruptError is raised\n ", "language": "en", "n_whitespaces": 84, "n_words": 22, "vocab_size": 18 }
def test_load_corrupt_file(self, patched_pickle_load): # First load is the schema version patched_pickle_load.side_effect = [DocumentClassifier.FORMAT_VERSION, OSError()] with self.assertRaises(ClassifierModelCorruptError): self.classifier.load()
86,883
287,694
20
homeassistant/components/plugwise/select.py
6
6
def current_option(self) -> str: return self.device[self.entity_description.current_option_key]
Rename property in Plugwise EntityDescription (#78935)
current_option
5c7d40cccf473c3549900949fe410dbe9d2e1a19
core
select.py
8
3
https://github.com/home-assistant/core.git
1
19
0
6
32
Python
{ "docstring": "Return the selected entity option to represent the entity state.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 8 }
def current_option(self) -> str: return self.device[self.entity_description.current_option_key]
4,771
24,604
172
ppstructure/table/convert_label2html.py
63
18
def gen_html(img): html_code = img['html']['structure']['tokens'].copy() to_insert = [i for i, tag in enumerate(html_code) if tag in ('<td>', '>')] for i, cell in zip(to_insert[::-1], img['html']['cells'][::-1]): if cell['tokens']: text = ''.join(cell['tokens']) # skip e...
add copyright
gen_html
97f7f748085fbe516952d36808735902d305da40
PaddleOCR
convert_label2html.py
14
14
https://github.com/PaddlePaddle/PaddleOCR.git
6
149
0
46
265
Python
{ "docstring": " \n Formats HTML code from tokenized annotation of img\n ", "language": "en", "n_whitespaces": 16, "n_words": 8, "vocab_size": 8 }
def gen_html(img): html_code = img['html']['structure']['tokens'].copy() to_insert = [i for i, tag in enumerate(html_code) if tag in ('<td>', '>')] for i, cell in zip(to_insert[::-1], img['html']['cells'][::-1]): if cell['tokens']: text = ''.join(cell['tokens']) # skip e...
44,978
185,332
35
src/textual/events.py
10
8
def key_aliases(self) -> Iterable[str]: for alias in _get_key_aliases(self.key): yi
Move aliasing/normalisation logic into Key
key_aliases
bd3a723d86f9c550b0324153975580b70509cb22
textual
events.py
10
4
https://github.com/Textualize/textual.git
2
26
0
10
44
Python
{ "docstring": "Get the aliases for the key, including the key itself", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 8 }
def key_aliases(self) -> Iterable[str]: for alias in _get_key_aliases(self.key): yield _normalize_key(alias)
78,141
265,561
227
netbox/ipam/tests/test_api.py
69
30
def test_create_single_available_ip(self): vrf = VRF.objects.create(name='VRF 1') prefix = Prefix.objects.create(prefix=IPNetwork('192.0.2.0/30'), vrf=vrf, is_pool=True) u
Closes #10031: Enforce 'application/json' content type for REST API requests
test_create_single_available_ip
bfbf97aec9119539f7f42cf16f52d0ca8203ba60
netbox
test_api.py
13
16
https://github.com/netbox-community/netbox.git
2
194
0
57
323
Python
{ "docstring": "\n Test retrieval of the first available IP address within a parent prefix.\n ", "language": "en", "n_whitespaces": 27, "n_words": 12, "vocab_size": 12 }
def test_create_single_available_ip(self): vrf = VRF.objects.create(name='VRF 1') prefix = Prefix.objects.create(prefix=IPNetwork('192.0.2.0/30'), vrf=vrf, is_pool=True) url = reverse('ipam-api:prefix-available-ips', kwargs={'pk': prefix.pk}) self.add_permissions('ipam.view_pref...
@pytest.fixture(name="climate_adc_t3000_missing_mode")
91,775
292,702
105
tests/components/zwave_js/conftest.py
38
17
def climate_adc_t3000_missing_setpoint_fixture(client, climate_adc_t3000_state): data = copy.deepcopy(climate_adc_t3000_state) data["name"] = f"{data['name']} missing setpoint" for value in data["values"][:]: if ( value["commandClassName"] == "Humidity Control Setpoint" ...
Add Humidifier support to zwave_js (#65847)
climate_adc_t3000_missing_setpoint_fixture
87593fa3ec4edd1fb467ed0709ef57c3c41e0fc4
core
conftest.py
13
12
https://github.com/home-assistant/core.git
4
84
1
32
171
Python
{ "docstring": "Mock a climate ADC-T3000 node with missing de-humidify setpoint.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def climate_adc_t3000_missing_setpoint_fixture(client, climate_adc_t3000_state): data = copy.deepcopy(climate_adc_t3000_state) data["name"] = f"{data['name']} missing setpoint" for value in data["values"][:]: if ( value["commandClassName"] == "Humidity Control Setpoint" ...
r""" Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of ...
49,006
198,577
14
sympy/solvers/ode/ode.py
12
106
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r
Allow initial conditions of the form f(0): f(0) in dsolve There was a check that the replacement value does not contain f, but this makes perfect sense. The check was changed to checking that the value doesn't contain x. Fixes #23702
classify_ode
32589850ff6a970bee8af3034980e37932db2eb9
sympy
ode.py
10
270
https://github.com/sympy/sympy.git
66
1,582
28
12
439
Python
{ "docstring": "\n Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`\n classifications for an ODE.\n\n The tuple is ordered so that first item is the classification that\n :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In\n general, classifications at the near th...
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r
69,724
241,885
259
scipy/stats/_stats_py.py
108
35
def mode(a, axis=0, nan_policy='propagate'): a, axis = _chk_asarray(a, axis) if a.size == 0: return ModeResult(np.array([]), np.array([])) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return msta...
MAINT: stats: mode: fix negative axis issue with np.moveaxis instead of custom code (#15421)
mode
7438fe5edfb565ff341fa6ab054461fcdd504aa2
scipy
_stats_py.py
13
31
https://github.com/scipy/scipy.git
8
340
0
78
336
Python
{ "docstring": "Return an array of the modal (most common) value in the passed array.\n\n If there is more than one such value, only the smallest is returned.\n The bin-count for the modal bins is also returned.\n\n Parameters\n ----------\n a : array_like\n n-dimensional array of which to find ...
def mode(a, axis=0, nan_policy='propagate'): a, axis = _chk_asarray(a, axis) if a.size == 0: return ModeResult(np.array([]), np.array([])) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return msta...
79,298
268,024
38
test/lib/ansible_test/_internal/host_profiles.py
10
6
def wait_for_instance(self) -> AnsibleCoreCI: core_ci = self.get_instance() cor
ansible-test - Use more native type hints. (#78435) * ansible-test - Use more native type hints. Simple search and replace to switch from comments to native type hints for return types of functions with no arguments. * ansible-test - Use more native type hints. Conversion of simple single-line function annota...
wait_for_instance
3eb0485dd92c88cc92152d3656d94492db44b183
ansible
host_profiles.py
8
5
https://github.com/ansible/ansible.git
1
22
0
9
40
Python
{ "docstring": "Wait for an AnsibleCoreCI VM instance to become ready.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def wait_for_instance(self) -> AnsibleCoreCI: core_ci = self.get_instance() core_ci.wait() return core_ci
49,306
199,635
90
sympy/polys/orthopolys.py
41
16
def spherical_bessel_fn(n, x=None, polys=False): if n < 0: dup = dup_spherical_bessel_fn_minus(-int(n), ZZ) else: dup = dup_spherical_bessel_fn(int(n), ZZ) poly = DMP(dup, ZZ) if x is not None: poly = Poly.new(poly, 1/x) else: poly = PurePoly.new(poly, 1/Dummy...
Link Appell sequences to corresponding continuous functions
spherical_bessel_fn
c6be089c27dd1891d4e273e7701926f7e5cf4d6f
sympy
orthopolys.py
15
11
https://github.com/sympy/sympy.git
4
97
0
28
154
Python
{ "docstring": "\n Coefficients for the spherical Bessel functions.\n\n Those are only needed in the jn() function.\n\n The coefficients are calculated from:\n\n fn(0, z) = 1/z\n fn(1, z) = 1/z**2\n fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z)\n\n Parameters\n ==========\n\n n : int\n ...
def spherical_bessel_fn(n, x=None, polys=False): if n < 0: dup = dup_spherical_bessel_fn_minus(-int(n), ZZ) else: dup = dup_spherical_bessel_fn(int(n), ZZ) poly = DMP(dup, ZZ) if x is not None: poly = Poly.new(poly, 1/x) else: poly = PurePoly.new(poly, 1/Dummy...
46,857
192,158
263
torchvision/models/optical_flow/raft.py
65
25
def raft_large(*, pretrained=False, progress=True, **kwargs): return _raft( arch="raft_large", pretrained=pretrained, progress=progress, # Feature encoder feature_encoder_layers=(64, 64, 96, 128, 256), feature_encoder_block=ResidualBlock, feature_encoder...
Change default weights of RAFT model builders (#5381) * Change default weights of RAFT model builders * update handle_legacy_interface input * Oops, wrong default
raft_large
97eddc5d6a83a9bf620070075ef1e1864c9a68ac
vision
raft.py
10
23
https://github.com/pytorch/vision.git
1
152
0
52
205
Python
{ "docstring": "RAFT model from\n `RAFT: Recurrent All Pairs Field Transforms for Optical Flow <https://arxiv.org/abs/2003.12039>`_.\n\n Args:\n pretrained (bool): Whether to use weights that have been pre-trained on\n :class:`~torchvsion.datasets.FlyingChairs` + :class:`~torchvsion.datasets.F...
def raft_large(*, pretrained=False, progress=True, **kwargs): return _raft( arch="raft_large", pretrained=pretrained, progress=progress, # Feature encoder feature_encoder_layers=(64, 64, 96, 128, 256), feature_encoder_block=ResidualBlock, feature_encoder...
2,034
11,433
408
jina/hubble/hubio.py
66
22
def _get_prettyprint_usage(self, console, executor_name, usage_kind=None): from rich.panel import Panel from rich.syntax import Syntax flow_plain = f flow_docker = f flow_sandbox = f panels = [ Panel( Syntax( p[0], ...
feat: add sandbox after push (#4349)
_get_prettyprint_usage
c07f3c151d985b207af87ccc9115bc94c3164e55
jina
hubio.py
13
39
https://github.com/jina-ai/jina.git
4
141
0
51
231
Python
{ "docstring": "from jina import Flow\n\nf = Flow().add(uses='jinahub://{executor_name}')\nfrom jina import Flow\n\nf = Flow().add(uses='jinahub+docker://{executor_name}')\nfrom jina import Flow\n\nf = Flow().add(uses='jinahub+sandbox://{executor_name}')\n", "language": "en", "n_whitespaces": 15, "n_words": 21,...
def _get_prettyprint_usage(self, console, executor_name, usage_kind=None): from rich.panel import Panel from rich.syntax import Syntax flow_plain = f flow_docker = f flow_sandbox = f panels = [ Panel( Syntax( p[0], ...
51,352
206,070
66
django/http/request.py
16
7
def encoding(self, val): self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._p
Refs #33476 -- Reformatted code with Black.
encoding
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
request.py
8
6
https://github.com/django/django.git
3
37
0
13
63
Python
{ "docstring": "\n Set the encoding used for GET/POST accesses. If the GET or POST\n dictionary has already been created, remove and recreate it on the\n next access (so that it is decoded correctly).\n ", "language": "en", "n_whitespaces": 60, "n_words": 31, "vocab_size": 28 }
def encoding(self, val): self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post
46,052
189,432
197
manim/mobject/geometry.py
44
15
def scale(self, factor, scale_tips=False, **kwargs): r if self.get_length() == 0: return self if scale_tips: super().scale(factor, **kwargs) self._set_stroke_width_from_length() return self has_tip = self.has_tip() has_start_tip =...
Hide more private methods from the docs. (#2468) * hide privs from text_mobject.py * hide privs from tex_mobject.py * hide privs from code_mobject.py * hide privs from svg_mobject.py * remove SVGPath and utils from __init__.py * don't import string_to_numbers * hide privs from geometry.py * hide p...
scale
902e7eb4f0147b5882a613b67467e38a1d47f01e
manim
geometry.py
11
45
https://github.com/ManimCommunity/manim.git
7
124
0
29
200
Python
{ "docstring": "Scale an arrow, but keep stroke width and arrow tip size fixed.\n\n See Also\n --------\n :meth:`~.Mobject.scale`\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0)\n >>> scaled_arrow = ...
def scale(self, factor, scale_tips=False, **kwargs): r if self.get_length() == 0: return self if scale_tips: super().scale(factor, **kwargs) self._set_stroke_width_from_length() return self has_tip = self.has_tip() has_start_tip =...
56,213
221,110
604
python3.10.4/Lib/bdb.py
151
17
def effective(file, line, frame): possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # I...
add python 3.10.4 for windows
effective
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
bdb.py
18
25
https://github.com/XX-net/XX-Net.git
9
131
0
96
217
Python
{ "docstring": "Determine which breakpoint for this file:line is to be acted upon.\n\n Called only if we know there is a breakpoint at this location. Return\n the breakpoint that was triggered and a boolean that indicates if it is\n ok to delete a temporary breakpoint. Return (None, None) if there is no\n ...
def effective(file, line, frame): possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # I...
@_wraps(osp_stats.truncnorm.logpdf, update_doc=False)
27,169
122,380
234
jax/_src/scipy/stats/truncnorm.py
172
23
def _log_gauss_mass(a, b): a, b = jnp.array(a), jnp.array(b) a, b = jnp.broadcast_arrays(a, b) # Note: Docstring carried over from scipy # Calculations in right tail are inaccurate, so we'll exploit the # symmetry and work only in the left tail case_left = b <= 0 case_right = a > 0 ca
implement truncnorm in jax.scipy.stats fix some shape and type issues import into namespace imports into non-_src library working logpdf test cleanup working tests for cdf and sf after fixing select relax need for x to be in (a, b) ensure behavior with invalid input matches scipy remove enforcing valid paramet...
_log_gauss_mass
5784d61048facfa9dac1f1d309bde2d60a32810c
jax
truncnorm.py
13
14
https://github.com/google/jax.git
1
100
1
115
271
Python
{ "docstring": "Log of Gaussian probability mass within an interval", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def _log_gauss_mass(a, b): a, b = jnp.array(a), jnp.array(b) a, b = jnp.broadcast_arrays(a, b) # Note: Docstring carried over from scipy # Calculations in right tail are inaccurate, so we'll exploit the # symmetry and work only in the left tail case_left = b <= 0 case_right = a > 0 case_central = ~(...
@RunIf(min_gpus=2)
69,683
241,753
763
tests/trainer/logging_/test_logger_connector.py
249
30
def test_fx_validator_integration(tmpdir): not_supported = { None: "`self.trainer` reference is not registered", "on_before_accelerator_backend_setup": "You can't", "setup": "You can't", "configure_sharded_model": "You can't", "on_configure_sharded_model": "You can't", ...
Add `LightningModule.lr_scheduler_step` (#10249) Co-authored-by: Carlos Mocholi <carlossmocholi@gmail.com>
test_fx_validator_integration
82c8875f33addb0becd7761c95e9674ccc98c7ee
lightning
test_logger_connector.py
11
72
https://github.com/Lightning-AI/lightning.git
2
322
1
106
644
Python
{ "docstring": "Tries to log inside all `LightningModule` and `Callback` hooks to check any expected errors.", "language": "en", "n_whitespaces": 13, "n_words": 14, "vocab_size": 13 }
def test_fx_validator_integration(tmpdir): not_supported = { None: "`self.trainer` reference is not registered", "on_before_accelerator_backend_setup": "You can't", "setup": "You can't", "configure_sharded_model": "You can't", "on_configure_sharded_model": "You can't", ...
43,741
182,049
32
src/textual/drivers/win32.py
17
10
def enable_application_mode() -> Callable[[], None]: terminal_in = sys.stdin terminal_out = sys.stdout current_console_mode_in = _get_console_mode(terminal_in) current_console_m
working windows driver
enable_application_mode
988838a872d2c7af6a1113546ace4f15b74a3254
textual
win32.py
8
16
https://github.com/Textualize/textual.git
1
53
0
14
59
Python
{ "docstring": "Enable application mode.\n\n Returns:\n Callable[[], None]: A callable that will restore terminal to previous state.\n ", "language": "en", "n_whitespaces": 28, "n_words": 15, "vocab_size": 15 }
def enable_application_mode() -> Callable[[], None]: terminal_in = sys.stdin terminal_out = sys.stdout current_console_mode_in = _get_console_mode(terminal_in) current_console_mode_out = _get_console_mode(terminal_out)
78,616
266,836
53
lib/ansible/utils/_junit_xml.py
10
7
def get_attributes(self) -> dict[str, str]:
Simplify existing type hints.
get_attributes
871b2ca73adcba3a35551247cf839246cf121231
ansible
_junit_xml.py
9
6
https://github.com/ansible/ansible.git
1
29
0
10
45
Python
{ "docstring": "Return a dictionary of attributes for this instance.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def get_attributes(self) -> dict[str, str]: return _attributes( message=self.message, type=self.type, )
34,289
148,549
695
freqtrade/freqtradebot.py
125
41
def check_handle_timedout(self) -> None: for trade in Trade.get_open_order_trades(): try: if not trade.open_order_id: continue order = self.exchange.fetch_order(trade.open_order_id, trade.pair) except (ExchangeError): ...
Extract timeout handling from freqtradebot class
check_handle_timedout
7bef9a9b3ec8593dac0701e7c5f8df6d77b5d4e0
freqtrade
freqtradebot.py
21
38
https://github.com/freqtrade/freqtrade.git
17
283
0
82
483
Python
{ "docstring": "\n Check if any orders are timed out and cancel if necessary\n :param timeoutvalue: Number of minutes until order is considered timed out\n :return: None\n ", "language": "en", "n_whitespaces": 53, "n_words": 24, "vocab_size": 21 }
def check_handle_timedout(self) -> None: for trade in Trade.get_open_order_trades(): try: if not trade.open_order_id: continue order = self.exchange.fetch_order(trade.open_order_id, trade.pair) except (ExchangeError): ...
18,345
87,972
590
tests/snuba/api/endpoints/test_organization_events.py
119
35
def test_user_misery_denominator(self): ProjectTransactionThreshold.objects.create( project=self.project, organization=self.project.organization, threshold=600, metric=TransactionMetric.LCP.value, ) lcps = [ 400, 40...
fix(tests): Discover backend test flakes (#41057) - `MetricsQueryBuilder` wasn't sorting environment tags - Consistent timestamps on test_organization_events - Updated `apply_feature_flag_on_cls` to only apply decorator on the run method
test_user_misery_denominator
618ae63cf2ba419e44e79ce578d88e8b062d7dd9
sentry
test_organization_events.py
16
47
https://github.com/getsentry/sentry.git
2
287
0
84
478
Python
{ "docstring": "This is to test against a bug where the denominator of misery(total unique users) was wrong\n This is because the total unique users for a LCP misery should only count users that have had a txn with lcp,\n and not count all transactions (ie. uniq_if(transaction has lcp) not just uniq())\...
def test_user_misery_denominator(self): ProjectTransactionThreshold.objects.create( project=self.project, organization=self.project.organization, threshold=600, metric=TransactionMetric.LCP.value, ) lcps = [ 400, 40...
12,264
60,726
62
.venv/lib/python3.8/site-packages/pip/_internal/index/collector.py
25
7
def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url
upd; format
_determine_base_url
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
collector.py
11
6
https://github.com/jindongwang/transferlearning.git
3
36
0
22
63
Python
{ "docstring": "Determine the HTML document's base URL.\n\n This looks for a ``<base>`` tag in the HTML document. If present, its href\n attribute denotes the base URL of anchor tags in the document. If there is\n no such tag (or if it does not have a valid href attribute), the HTML\n file's URL is used a...
def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url
1,622
9,465
23
reconstruction/ostec/external/stylegan2/metrics/precision_recall.py
10
9
def pairwise_distances(self, U, V): return self._distance_block.eval(feed_dict={self._features_batch1: U, self._features
initialize ostec
pairwise_distances
7375ee364e0df2a417f92593e09557f1b2a3575a
insightface
precision_recall.py
11
2
https://github.com/deepinsight/insightface.git
1
33
0
9
52
Python
{ "docstring": "Evaluate pairwise distances between two batches of feature vectors.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def pairwise_distances(self, U, V): return self._distance_block.eval(feed_dict={self._features_batch1: U, self._features_batch2: V}) #----------------------------------------------------------------------------
25,917
117,187
421
mindsdb/migrations/versions/2022-10-14_43c52d23845a_projects.py
110
45
def upgrade(): op.create_table( 'project', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('na...
Projects structure (#3532) Projects structure
upgrade
7c02e15aa403a4ca1fa34489dd2df9136d6c961c
mindsdb
2022-10-14_43c52d23845a_projects.py
15
60
https://github.com/mindsdb/mindsdb.git
3
446
0
67
766
Python
{ "docstring": "\n update predictor set project_id = :project_id\n \n update view set project_id = :project_id\n \n select id, name from view\n where exists (select 1 from predictor where view.name = predictor.name)\n \n update view\n set name = :name...
def upgrade(): op.create_table( 'project', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('na...
24,381
111,338
89
spacy/pipeline/span_ruler.py
21
14
def clear(self) -> None: self._patterns: List[PatternType] = [] self.matcher: Matcher = Matcher(self.nlp.vocab, validate=self.validate) self.phrase_matcher: P
Add SpanRuler component (#9880) * Add SpanRuler component Add a `SpanRuler` component similar to `EntityRuler` that saves a list of matched spans to `Doc.spans[spans_key]`. The matches from the token and phrase matchers are deduplicated and sorted before assignment but are not otherwise filtered. * Update spa...
clear
a322d6d5f2f85c2da6cded4fcd6143d41b5a9e96
spaCy
span_ruler.py
10
13
https://github.com/explosion/spaCy.git
1
66
0
19
102
Python
{ "docstring": "Reset all patterns.\n\n RETURNS: None\n DOCS: https://spacy.io/api/spanruler#clear\n ", "language": "en", "n_whitespaces": 28, "n_words": 7, "vocab_size": 7 }
def clear(self) -> None: self._patterns: List[PatternType] = [] self.matcher: Matcher = Matcher(self.nlp.vocab, validate=self.validate) self.phrase_matcher: PhraseMatcher = PhraseMatcher( self.nlp.vocab, attr=self.phrase_matcher_attr, validate=self.va...
56,928
223,483
317
python3.10.4/Lib/doctest.py
88
19
def _from_module(self, module, object): if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): return module.__dict__ is object.__globals__ elif in...
add python 3.10.4 for windows
_from_module
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
doctest.py
13
23
https://github.com/XX-net/XX-Net.git
10
148
0
47
242
Python
{ "docstring": "\n Return true if the given object is defined in the given\n module.\n ", "language": "en", "n_whitespaces": 34, "n_words": 12, "vocab_size": 10 }
def _from_module(self, module, object): if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): return module.__dict__ is object.__globals__ elif in...
53,568
213,001
945
DemoPrograms/Demo_Script_Launcher_ANSI_Color_Output.py
258
33
def cut_ansi_string_into_parts(string_with_ansi_codes): color_codes_english = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Reset'] color_codes = ["30m", "31m", "32m", "33m", "34m", "35m", "36m", "37m", "0m"] effect_codes_english = ['Italic', 'Underline', 'Slow Blink', 'Rapid...
Removed old code that used Popen and instead uses the PySimpleGUI Exec API calls for an all-in-one demo. Added expansion of the Multilline and a SizeGrip so that it's obvious to user the window is resizable.
cut_ansi_string_into_parts
a35687ac51dac5a2a0664ca20e7dd7cba6836c7b
PySimpleGUI
Demo_Script_Launcher_ANSI_Color_Output.py
21
57
https://github.com/PySimpleGUI/PySimpleGUI.git
19
603
0
131
973
Python
{ "docstring": "\n Converts a string with ambedded ANSI Color Codes and parses it to create\n a list of tuples describing pieces of the input string.\n :param string_with_ansi_codes:\n :return: [(sty, str, str, str), ...] A list of tuples. Each tuple has format: (text, text color, background color, effect...
def cut_ansi_string_into_parts(string_with_ansi_codes): color_codes_english = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Reset'] color_codes = ["30m", "31m", "32m", "33m", "34m", "35m", "36m", "37m", "0m"] effect_codes_english = ['Italic', 'Underline', 'Slow Blink', 'Rapid...
39,296
162,765
472
research/neo_peq/legacy_frequency_response.py
147
30
def interpolate(self, f=None, f_step=DEFAULT_STEP, pol_order=1, f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX): # Remove None values i = 0 while i < len(self.raw): if self.raw[i] is None: self.raw = np.delete(self.raw, i) self.frequency = np.delete...
Added PEQ configs to CLI and function interfaces. Improved default value handling for PEQ parameters and added more predefined configs. Removed legacy PEQ optimization. Fixed readme write. Improved shelf filter initialization. Added plot method to PEQ. Notebook for comparing old and new optimizers. Bug fixes.
interpolate
9120cdffe618c6c2ff16fe6a311b6a1367efdbc8
AutoEq
legacy_frequency_response.py
14
29
https://github.com/jaakkopasanen/AutoEq.git
12
273
0
94
423
Python
{ "docstring": "Interpolates missing values from previous and next value. Resets all but raw data.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 13 }
def interpolate(self, f=None, f_step=DEFAULT_STEP, pol_order=1, f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX): # Remove None values i = 0 while i < len(self.raw): if self.raw[i] is None: self.raw = np.delete(self.raw, i) self.frequency = np.delete...
119,869
331,584
947
timm/optim/lars.py
182
34
def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param_groups[0]['params'][0].device one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars...
fix lars
step
cdcd0a92ca8a3dc120336a5dde1b7d6ecd5e9186
pytorch-image-models
lars.py
19
44
https://github.com/huggingface/pytorch-image-models.git
11
331
0
118
534
Python
{ "docstring": "Performs a single optimization step.\n\n Args:\n closure (callable, optional): A closure that reevaluates the model and returns the loss.\n ", "language": "en", "n_whitespaces": 44, "n_words": 19, "vocab_size": 17 }
def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param_groups[0]['params'][0].device one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars...
95,399
296,416
30
homeassistant/components/hunterdouglas_powerview/cover.py
9
5
async def _async_force_resync(self, *_): self._forced_resync = None
Fix handling of powerview stale state (#70195)
_async_force_resync
2c2b678e80db615e50a7b72c3ec107730cc6f8dd
core
cover.py
8
3
https://github.com/home-assistant/core.git
1
20
0
9
37
Python
{ "docstring": "Force a resync after an update since the hub may have stale state.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 13 }
async def _async_force_resync(self, *_): self._forced_resync = None await self._async_force_refresh_state()
7,511
42,251
273
seaborn/palettes.py
90
18
def set_color_codes(palette="deep"): if palette == "reset": colors = [
Convert color palette docstrings to notebooks (#3034) * Convert color palette docstrings to notebooks and rerun all with py310 kernel * Add v0.12.1 release notes to index * Improve failure mode when ipywidgets is not involved * Update palettes docstrings * Remove all other doctest-style examples * Remov...
set_color_codes
e644793f0ac2b1be178425f20f529121f37f29de
seaborn
palettes.py
13
25
https://github.com/mwaskom/seaborn.git
6
207
0
57
280
Python
{ "docstring": "Change how matplotlib color shorthands are interpreted.\n\n Calling this will change how shorthand codes like \"b\" or \"g\"\n are interpreted by matplotlib in subsequent plots.\n\n Parameters\n ----------\n palette : {deep, muted, pastel, dark, bright, colorblind}\n Named seabor...
def set_color_codes(palette="deep"): if palette == "reset": colors = [ (0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, 0., .75), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.) ] elif not isinstance(palette, st...
7,877
43,220
20
tests/models/test_dagrun.py
11
9
def test_mapped_literal_length_increase_at_runtime_adds_additional_tis(dag_maker, session):
Fix mapped task immutability after clear (#23667) We should be able to detect if the structure of mapped task has changed and verify the integrity. This PR ensures this Co-authored-by: Tzu-ping Chung <uranusjr@gmail.com>
test_mapped_literal_length_increase_at_runtime_adds_additional_tis
b692517ce3aafb276e9d23570e9734c30a5f3d1f
airflow
test_dagrun.py
9
39
https://github.com/apache/airflow.git
5
311
0
11
51
Python
{ "docstring": "Test that when the length of mapped literal increases at runtime, additional ti is added", "language": "en", "n_whitespaces": 14, "n_words": 15, "vocab_size": 15 }
def test_mapped_literal_length_increase_at_runtime_adds_additional_tis(dag_maker, session): from airflow.models import Variable Variable.set(key='arg1', value=[1, 2, 3])
116,988
319,729
44
src/documents/tests/test_management_convert_thumbnail.py
16
8
def create_png_thumbnail_file(self, thumb_dir): thumb_file = Path(thumb_dir) / Path(f"{self.doc.pk:07}.png") thumb_file.write_text("this is a dummy p
Fixes existing testing, adds test coverage of new command
create_png_thumbnail_file
08c3d6e84b17da2acfb10250438fe357398e5e0e
paperless-ngx
test_management_convert_thumbnail.py
13
4
https://github.com/paperless-ngx/paperless-ngx.git
1
28
0
15
62
Python
{ "docstring": "\n Creates a dummy PNG thumbnail file in the given directory, based on\n the database Document\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 14 }
def create_png_thumbnail_file(self, thumb_dir): thumb_file = Path(thumb_dir) / Path(f"{self.doc.pk:07}.png") thumb_file.write_text("this is a dummy png file") return thumb_file
45,702
187,141
47
tests/test_api_validate.py
16
10
def test_parse_html(self): a
plugin.api.validate: implement ValidationError - Implement `ValidationError` - Inherit from `ValueError` to preserve backwards compatiblity - Allow collecting multiple errors (AnySchema) - Keep an error stack of parent `ValidationError`s or other exceptions - Format error stack when converting error to string ...
test_parse_html
3d44da082b3ba202b9d0557bfd8ce747a1d7960c
streamlink
test_api_validate.py
11
8
https://github.com/streamlink/streamlink.git
1
44
0
15
79
Python
{ "docstring": "\n ValidationError:\n Unable to parse HTML: can only parse strings (None)\n ", "language": "en", "n_whitespaces": 42, "n_words": 10, "vocab_size": 9 }
def test_parse_html(self): assert validate(parse_html(), '<!DOCTYPE html><body>&quot;perfectly&quot;<a>valid<div>HTML').tag == "html" with self.assertRaises(ValueError) as cm: validate(parse_html(), None) assert_validationerror(cm.exception, )
75,377
258,712
264
sklearn/utils/validation.py
107
16
def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): feature_names_in_ = getattr(estimator, "feature_names_in_", None) n_features_in_ = getattr(estimator, "n_features_in_", None) if input_features is not None: input_features = np.asarray(input_features, dtype=o...
ENH Adds feature_names_out to preprocessing module (#21079) Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org> Co-authored-by: 赵丰 (Zhao Feng) <616545598@qq.com> Co-authored-by: Niket Jain <51831161+nikJ13@users.noreply.github.com> Co-authored-by: Loïc Estève <loic.esteve@ymail.com>
_check_feature_names_in
d7feac0ccfe1a7b8a55f2e16f249f77508a91fe1
scikit-learn
validation.py
16
22
https://github.com/scikit-learn/scikit-learn.git
10
141
0
62
244
Python
{ "docstring": "Check `input_features` and generate names if needed.\n\n Commonly used in :term:`get_feature_names_out`.\n\n Parameters\n ----------\n input_features : array-like of str or None, default=None\n Input features.\n\n - If `input_features` is `None`, then `feature_names_in_` is\n...
def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): feature_names_in_ = getattr(estimator, "feature_names_in_", None) n_features_in_ = getattr(estimator, "n_features_in_", None) if input_features is not None: input_features = np.asarray(input_features, dtype=o...
41,810
176,293
41
networkx/algorithms/shortest_paths/weighted.py
22
6
def all_pairs_bellman_ford_path(G, weight="weight"): path = single_source_bellm
DOC: Update documentation to include callables for weight argument (#5307) Update docs to include functions as valid input for weight argument.
all_pairs_bellman_ford_path
b5d41847b8db0c82372faf69cd3a339d11da7ef0
networkx
weighted.py
12
4
https://github.com/networkx/networkx.git
2
33
0
22
54
Python
{ "docstring": "Compute shortest paths between all nodes in a weighted graph.\n\n Parameters\n ----------\n G : NetworkX graph\n\n weight : string or function (default=\"weight\")\n If this is a string, then edge weights will be accessed via the\n edge attribute with this key (that is, the w...
def all_pairs_bellman_ford_path(G, weight="weight"): path = single_source_bellman_ford_path # TODO This can be trivially parallelized. for n in G: yield (n, path(G, n, weight=weight))
14,863
68,774
20
erpnext/manufacturing/doctype/bom_update_log/test_bom_update_log.py
24
6
def update_cost_in_all_boms_in_test(): log = enqueue_update_cost() # create BOM Update Log while log.status != "Completed": resume_bom_cost_update_jobs() # run cron job until complete log.reload() return log
chore: Less hacky tests, versioning (replace bom) and clearing log data (update cost) - Remove `auto_commit_on_many_writes` in `update_cost_in_level()` as commits happen every N BOMs - Auto commit every 50 BOMs - test: Remove hacky `frappe.flags.in_test` returns - test: Enqueue `now` if in tests (for update cost and r...
update_cost_in_all_boms_in_test
3fa0a46f39f7024c5d0b235a7725eaa9ad0f3869
erpnext
test_bom_update_log.py
9
6
https://github.com/frappe/erpnext.git
2
27
0
22
54
Python
{ "docstring": "\n\tUtility to run 'Update Cost' job in tests without Cron job until fully complete.\n\t", "language": "en", "n_whitespaces": 13, "n_words": 14, "vocab_size": 13 }
def update_cost_in_all_boms_in_test(): log = enqueue_update_cost() # create BOM Update Log while log.status != "Completed": resume_bom_cost_update_jobs() # run cron job until complete log.reload() return log
45,161
185,757
81
src/textual/widgets/_data_table.py
18
10
def clear(self) -> None: self.row_count = 0 self._clear_caches()
ffixed table refresh on add row
clear
b524fa08eecadc83b0b694278db1c79d90feb9d8
textual
_data_table.py
8
14
https://github.com/Textualize/textual.git
1
54
0
15
94
Python
{ "docstring": "Clear the table.\n\n Args:\n columns (bool, optional): Also clear the columns. Defaults to False.\n ", "language": "en", "n_whitespaces": 39, "n_words": 14, "vocab_size": 13 }
def clear(self) -> None: self.row_count = 0 self._clear_caches() self._y_offsets.clear() self.data.clear() self.rows.clear() self._line_no = 0 self._require_update_dimensions = True self.refresh()
42,686
178,399
207
nuitka/utils/FileOperations.py
43
15
def copyFile(source_path, dest_path): while 1: try: shutil.copyfile(source_path, dest_path) except PermissionError as e: if e.errno != errno.EACCES: raise general.warning("Problem copying file %s:" % e) try: repl...
UI: In case of PermissionError, allow uses to retry * Esp. on Windows it happens a lot that running programs cannot be updated by Nuitka, this avoids the cryptic error somewhere ranomly.
copyFile
2c20b90946a8aa5ad4ee39ad365ff1b83f182770
Nuitka
FileOperations.py
17
16
https://github.com/Nuitka/Nuitka.git
7
72
0
37
132
Python
{ "docstring": "Improved version of shutil.copy\n\n This handles errors with a chance to correct them, e.g. on Windows, files might be\n locked by running program or virus checkers.\n ", "language": "en", "n_whitespaces": 35, "n_words": 26, "vocab_size": 26 }
def copyFile(source_path, dest_path): while 1: try: shutil.copyfile(source_path, dest_path) except PermissionError as e: if e.errno != errno.EACCES: raise general.warning("Problem copying file %s:" % e) try: repl...
76,027
259,994
106
sklearn/ensemble/tests/test_iforest.py
37
14
def test_iforest(global_random_seed): X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid( {"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]} ) with ignore_warnings(): for params in grid: Isolat...
TST use global_random_seed in sklearn/ensemble/tests/test_iforest.py (#22901) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr> Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org>
test_iforest
6ca1f5e4d0d16bc9a7f28582079a15e14f012719
scikit-learn
test_iforest.py
16
11
https://github.com/scikit-learn/scikit-learn.git
2
109
0
32
164
Python
{ "docstring": "Check Isolation Forest for various parameter settings.", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 7 }
def test_iforest(global_random_seed): X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid( {"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]} ) with ignore_warnings(): for params in grid: Isolat...
55,189
218,189
22
python3.10.4/Lib/importlib/abc.py
7
9
def invalidate_caches(self): _register
add python 3.10.4 for windows
invalidate_caches
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
abc.py
6
1
https://github.com/XX-net/XX-Net.git
1
6
0
7
40
Python
{ "docstring": "An optional method for clearing the finder's cache, if any.\n This method is used by importlib.invalidate_caches().\n ", "language": "en", "n_whitespaces": 30, "n_words": 16, "vocab_size": 15 }
def invalidate_caches(self): _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder)
17,223
81,589
131
awx/main/dispatch/reaper.py
49
28
def reap(instance=None, status='failed', excluded_uuids=[]): me = instance if me is None: try: me = Instance.objects.me() except RuntimeError as e: logger.warning(f'Local instance is not registered, not running reaper: {e}') return workflow_ctype_id =...
Split reaper for running and waiting jobs Avoid running jobs that have already been reapted Co-authored-by: Elijah DeLee <kdelee@redhat.com> Remove unnecessary extra actions Fix waiting jobs in other cases of reaping
reap
278db2cddebec97ec48011ecae45129be1ac43a4
awx
reaper.py
18
14
https://github.com/ansible/awx.git
4
122
0
40
205
Python
{ "docstring": "\n Reap all jobs in running for this instance.\n ", "language": "en", "n_whitespaces": 15, "n_words": 8, "vocab_size": 8 }
def reap(instance=None, status='failed', excluded_uuids=[]): me = instance if me is None: try: me = Instance.objects.me() except RuntimeError as e: logger.warning(f'Local instance is not registered, not running reaper: {e}') return workflow_ctype_id =...
7,566
42,481
106
nltk/corpus/reader/wordnet.py
44
12
def closure(self, rel, depth=-1): from nltk.util import acyclic_breadth_first for synset in acyclic_breadth_first(self, rel, depth): if s
Fix some tests in Wordnet-related DocStrings
closure
692adaff901dd9daf29400fdf3385130aefbfb2a
nltk
wordnet.py
10
5
https://github.com/nltk/nltk.git
3
38
0
29
89
Python
{ "docstring": "\n Return the transitive closure of source under the rel\n relationship, breadth-first, discarding cycles:\n\n >>> from nltk.corpus import wordnet as wn\n >>> computer = wn.synset('computer.n.01')\n >>> topic = lambda s:s.topic_domains()\n >>> print(list(compu...
def closure(self, rel, depth=-1): from nltk.util import acyclic_breadth_first for synset in acyclic_breadth_first(self, rel, depth): if synset != self: yield synset from nltk.util import acyclic_depth_first as acyclic_tree from nltk.util import unweighted_...
20,505
101,068
157
plugins/convert/writer/opencv.py
46
13
def _get_save_args(self) -> Tuple[int, ...]: filetype = self
Convert: Add option to output mask separately for draw-transparent
_get_save_args
049314429f71a21e6595e9d27e9e36f6a3479c42
faceswap
opencv.py
11
18
https://github.com/deepfakes/faceswap.git
5
98
0
31
165
Python
{ "docstring": " Obtain the save parameters for the file format.\n\n Returns\n -------\n tuple\n The OpenCV specific arguments for the selected file format\n ", "language": "en", "n_whitespaces": 61, "n_words": 20, "vocab_size": 16 }
def _get_save_args(self) -> Tuple[int, ...]: filetype = self.config["format"] args: Tuple[int, ...] = tuple() if filetype == "jpg" and self.config["jpg_quality"] > 0: args = (cv2.IMWRITE_JPEG_QUALITY, # pylint: disable=no-member self.config["jpg_quality"...
22,598
107,133
32
lib/matplotlib/figure.py
7
7
def set_constrained_layout_pads(self, **kwargs): if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.
ENH: implement and use base layout_engine for more flexible layout.
set_constrained_layout_pads
ec4dfbc3c83866f487ff0bc9c87b0d43a1c02b22
matplotlib
figure.py
11
3
https://github.com/matplotlib/matplotlib.git
2
32
0
7
55
Python
{ "docstring": "\n Set padding for ``constrained_layout``.\n\n Tip: The parameters can be passed from a dictionary by using\n ``fig.set_constrained_layout(**pad_dict)``.\n\n See :doc:`/tutorials/intermediate/constrainedlayout_guide`.\n\n Parameters\n ----------\n w_pad...
def set_constrained_layout_pads(self, **kwargs): if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs)
35,062
151,595
85
freqtrade/freqai/freqai_interface.py
32
6
def track_current_candle(self): if self.dd.current_candle > self.current_candle: self.get_corr_dataframes = True
start tracking the current candle in FreqAI, add robustness to corr_df caching and inference timer, add test for cache corr_df
track_current_candle
255eb71270991fe480cd642ee5ea2ce69964f8a9
freqtrade
freqai_interface.py
10
5
https://github.com/freqtrade/freqtrade.git
2
36
0
28
62
Python
{ "docstring": "\n Checks if the latest candle appended by the datadrawer is\n equivalent to the latest candle seen by FreqAI. If not, it\n asks to refresh the cached corr_dfs, and resets the pair\n counter.\n ", "language": "en", "n_whitespaces": 68, "n_words": 32, "vocab_s...
def track_current_candle(self): if self.dd.current_candle > self.current_candle: self.get_corr_dataframes = True self.pair_it = 0 self.current_candle = self.dd.current_candle # Following methods which are overridden by user made prediction models. # See freq...
13,215
63,228
76
.venv/lib/python3.8/site-packages/pip/_vendor/pkg_resources/__init__.py
26
8
def find(self, req): dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX a
upd; format
find
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
__init__.py
9
5
https://github.com/jindongwang/transferlearning.git
3
40
0
22
64
Python
{ "docstring": "Find a distribution matching requirement `req`\n\n If there is an active distribution for the requested project, this\n returns it as long as it meets the version requirement specified by\n `req`. But, if there is an active distribution for the project and it\n does *not* ...
def find(self, req): dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist
25,019
113,746
161
nni/mutable/frozen.py
36
13
def current() -> dict | None: try: ContextStack.top(_FROZEN_CONTEXT_KEY) sample: Sample = {} for ctx in ContextStack
Mutable equal, frozen context, new labels (#5247)
current
a67180283b8d273b19f6a3497c6b898ab0c97b7d
nni
frozen.py
15
19
https://github.com/microsoft/nni.git
4
61
0
35
106
Python
{ "docstring": "Retrieve the current frozen context.\n If multiple layers have been found, they would be merged from bottom to top.\n\n Returns\n -------\n The sample in frozen context.\n If no sample is found, return none.\n ", "language": "en", "n_whitespaces": 75, "n...
def current() -> dict | None: try: ContextStack.top(_FROZEN_CONTEXT_KEY) sample: Sample = {} for ctx in ContextStack.stack(_FROZEN_CONTEXT_KEY): if not isinstance(ctx, dict): raise TypeError(f'Expect architecture to be a dict, foun...
44
70
371
packages/syft/tests/syft/core/tensor/tensor_serde_test.py
230
37
def test_rept_child() -> None: rows = 10_000 cols = 7 rept_row_count = 5 # these times and sizes are based on the above constants # and Madhavas MacBook Pro 2019 expected_rept_mem_size = 4.010650634765625 expected_rept_ser_size = 7.4926300048828125 macbook_pro_2019_ser_time = 0.187...
Started DPTensor resource optimization - Added initial REPT and SEPT benchmarking tests - Deleted unused old Tensor classes - Added pympler for memory size tests Co-authored-by: @IshanMi Co-authored-by: @rasswanth-s
test_rept_child
10ae1d589044a6ae4722ead7aedc63fcdc4923b5
PySyft
tensor_serde_test.py
10
41
https://github.com/OpenMined/PySyft.git
2
278
0
132
501
Python
{ "docstring": "We need to benchmark both the size and time to serialize and deserialize REPTs", "language": "en", "n_whitespaces": 13, "n_words": 14, "vocab_size": 12 }
def test_rept_child() -> None: rows = 10_000 cols = 7 rept_row_count = 5 # these times and sizes are based on the above constants # and Madhavas MacBook Pro 2019 expected_rept_mem_size = 4.010650634765625 expected_rept_ser_size = 7.4926300048828125 macbook_pro_2019_ser_time = 0.187...
48,294
197,037
798
sympy/ntheory/ecm.py
319
56
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.p...
Refactored import ordering in functions
_ecm_one_factor
e0dc14eca132f37c5f49369eb4051eae37c9b119
sympy
ecm.py
19
58
https://github.com/sympy/sympy.git
15
615
0
170
933
Python
{ "docstring": "Returns one factor of n using\n Lenstra's 2 Stage Elliptic curve Factorization\n with Suyama's Parameterization. Here Montgomery\n arithmetic is used for fast computation of addition\n and doubling of points in elliptic curve.\n\n This ECM method considers elliptic curves in Montgomery\...
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.p...
107,219
308,463
386
tests/components/command_line/test_cover.py
78
11
async def test_unique_id(hass): await setup_test_entity( hass, { "unique": { "command_open": "echo open", "command_close": "echo close", "command_stop": "echo stop", "u
Add unique_id configuration variable to command_line integration (#58596)
test_unique_id
d26275011ae4e8ba0a8dcdc2a7ef81b5911d3900
core
test_cover.py
13
32
https://github.com/home-assistant/core.git
1
138
0
38
264
Python
{ "docstring": "Test unique_id option and if it only creates one cover per id.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 12 }
async def test_unique_id(hass): await setup_test_entity( hass, { "unique": { "command_open": "echo open", "command_close": "echo close", "command_stop": "echo stop", "unique_id": "unique", }, "no...
@pytest.fixture
88,829
289,693
110
tests/components/mqtt/test_config_flow.py
28
7
def mock_ssl_context(): with patch( "homeassistant.components.mqtt.config_flow.SSLC
Move advanced MQTT options to entry (#79351) * Move advanced broker settings to entry * Add repair issue for deprecated settings * Split CONFIG_SCHEMA * Do not store certificate UI flags in entry * Keep entered password in next dialog * Do not process yaml config in flow * Correct typo
mock_ssl_context
5e7f571f019c0b992b9cb8ffa545c12e8169d395
core
test_config_flow.py
11
13
https://github.com/home-assistant/core.git
1
42
1
20
92
Python
{ "docstring": "Mock the SSL context used to load the cert chain and to load verify locations.", "language": "en", "n_whitespaces": 14, "n_words": 15, "vocab_size": 12 }
def mock_ssl_context(): with patch( "homeassistant.components.mqtt.config_flow.SSLContext" ) as mock_context, patch( "homeassistant.components.mqtt.config_flow.load_pem_private_key" ) as mock_key_check, patch( "homeassistant.components.mqtt.config_flow.load_pem_x509_certificate"...
7,671
42,640
274
tests/cli/commands/test_task_command.py
21
13
def test_task_states_for_dag_run_when_dag_run_not_exists(self): with pytest.raises(DagRunNotFound): default_date2 = t
Replaced all days_ago functions with datetime functions (#23237) Co-authored-by: Dev232001 <thedevhooda@gmail.com>
test_task_states_for_dag_run_when_dag_run_not_exists
f352ee63a5d09546a7997ba8f2f8702a1ddb4af7
airflow
test_task_command.py
14
15
https://github.com/apache/airflow.git
1
56
0
20
97
Python
{ "docstring": "\n task_states_for_dag_run should return an AirflowException when invalid dag id is passed\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 11 }
def test_task_states_for_dag_run_when_dag_run_not_exists(self): with pytest.raises(DagRunNotFound): default_date2 = timezone.datetime(2016, 1, 9) task_command.task_states_for_dag_run( self.parser.parse_args( [ 'tasks', ...
15,993
73,217
29
wagtail/contrib/modeladmin/tests/test_page_modeladmin.py
8
5
def test_title_present(self): response = self.get(4) self.assertConta
Reformat with black
test_title_present
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
test_page_modeladmin.py
8
3
https://github.com/wagtail/wagtail.git
1
24
0
8
42
Python
{ "docstring": "\n The page title should appear three times. Once in the header, and two times\n in the field listing (as the actual title and as the draft title)\n ", "language": "en", "n_whitespaces": 49, "n_words": 27, "vocab_size": 21 }
def test_title_present(self): response = self.get(4) self.assertContains(response, "Christmas", 3)
22,669
107,267
121
lib/matplotlib/axes/_base.py
30
16
def _set_position(self, pos, which='both'): i
Fix typos
_set_position
f7e4349b6c20d127e88a8f750fe1df7462350971
matplotlib
_base.py
12
9
https://github.com/matplotlib/matplotlib.git
5
85
0
23
143
Python
{ "docstring": "\n Private version of set_position.\n\n Call this internally to get the same functionality of `set_position`,\n but not to take the axis out of the constrained_layout hierarchy.\n ", "language": "en", "n_whitespaces": 54, "n_words": 25, "vocab_size": 20 }
def _set_position(self, pos, which='both'): if not isinstance(pos, mtransforms.BboxBase): pos = mtransforms.Bbox.from_bounds(*pos) for ax in self._twinned_axes.get_siblings(self): if which in ('both', 'active'): ax._position.set(pos) if which ...