complexity int64 1 56 | n_identifiers int64 1 114 | code stringlengths 19 12.7k | path stringlengths 8 134 | n_ast_nodes int64 12 2.35k | ast_errors stringlengths 0 4.01k | repo stringlengths 3 28 | documentation dict | n_words int64 2 866 | language stringclasses 1
value | vocab_size int64 2 323 | commit_id stringlengths 40 40 | file_name stringlengths 5 79 | id int64 243 338k | nloc int64 1 228 | token_counts int64 5 1.4k | fun_name stringlengths 1 77 | url stringlengths 31 60 | commit_message stringlengths 3 15.3k | n_whitespaces int64 1 3.23k | n_ast_errors int64 0 20 | d_id int64 74 121k | ast_levels int64 4 29 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4 | 11 | def check_compressionlib(cls, value):
try:
compresser = from_qualified_name(value)
except (ImportError, AttributeError) as exc:
raise ValueError(
f"Failed to import requested compression library: {value!r}."
) from exc
if not callable... | src/prefect/serializers.py | 139 | prefect | {
"docstring": "\n Check that the given pickle library is importable and has compress/decompress\n methods.\n ",
"language": "en",
"n_whitespaces": 34,
"n_words": 12,
"vocab_size": 12
} | 62 | Python | 42 | 295fd5d4b65dc967d8ddc99817b52d8273301063 | serializers.py | 59,407 | 16 | 75 | check_compressionlib | https://github.com/PrefectHQ/prefect.git | Add `CompressedSerializer` for compression of other result serializers (#7164)
Co-authored-by: Terrence Dorsey <terrence@prefect.io> | 226 | 0 | 11,900 | 12 | |
4 | 10 | def prefer_url(self, url1, url2):
result = url2
if url1:
s1 = self.score_url(url1)
s2 = self.score_url(url2)
if s1 > s2:
result = url1
if result != url2:
logger.debug('Not replacing %r with %r', url1, url2)
... | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/locators.py | 113 | transferlearning | {
"docstring": "\n Choose one of two URLs where both are candidates for distribution\n archives for the same version of a distribution (for example,\n .tar.gz vs. zip).\n\n The current implementation favours https:// URLs over http://, archives\n from PyPI over those from other loca... | 42 | Python | 27 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | locators.py | 62,018 | 12 | 69 | prefer_url | https://github.com/jindongwang/transferlearning.git | upd; format | 170 | 0 | 12,828 | 13 | |
2 | 15 | def system_exec(command):
try:
res = subprocess.run(command.split(' '), stdout=subprocess.PIPE).stdout.decode('utf-8')
except Exception as e:
logger.debug('Can not evaluate command {} ({})'.format(command, e))
res = ''
return res.rstrip()
| glances/compat.py | 109 | glances | {
"docstring": "Execute a system command and return the result as a str",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 10
} | 24 | Python | 22 | b3c009b22ef6c47a54faa4c8bf4e10bb62caeef4 | compat.py | 69,944 | 7 | 61 | system_exec | https://github.com/nicolargo/glances.git | Correct unitary test failed | 57 | 0 | 15,190 | 16 | |
1 | 4 | def getdata(im, offset=(0, 0), **params):
| src/PIL/GifImagePlugin.py | 28 | Pillow | {
"docstring": "\n Legacy Method\n\n Return a list of strings representing this image.\n The first string is a local image header, the rest contains\n encoded image data.\n\n To specify duration, add the time in milliseconds,\n e.g. ``getdata(im_frame, duration=1000)``\n\n :param im: Image object... | 5 | Python | 5 | 1997c814abcbc071fb9f289fda021e8d08cad4a7 | GifImagePlugin.py | 242,759 | 24 | 50 | getdata | https://github.com/python-pillow/Pillow.git | Move useful comment into docstring | 8 | 0 | 69,911 | 6 | |
2 | 20 | def test_shared_deployment_handle(serve_instance):
ray_dag, _ = get_shared_deployment_handle_dag()
with DAGNodeNameGenerator() as node_name_generator:
serve_root_dag = ray_dag.apply_recursive(
lambda node: transform_ray_dag_to_serve_dag(node, node_name_generator)
)
print(f"... | python/ray/serve/pipeline/tests/test_generate.py | 143 | ray | {
"docstring": "\n Test we can re-use the same deployment handle multiple times or in\n multiple places, without incorrectly parsing duplicated deployments.\n ",
"language": "en",
"n_whitespaces": 29,
"n_words": 19,
"vocab_size": 18
} | 40 | Python | 36 | 5c06e3f14900e3812061416759c25ff2b88c8a23 | test_generate.py | 138,804 | 14 | 83 | test_shared_deployment_handle | https://github.com/ray-project/ray.git | [DAG] add basic plotting on Ray DAGs (#24223)
To add basic plotting feature for Ray DAGs.
`ray.experimental.dag.plot(dag: DAGNode, to_file=None)`
### Behavior
1. dump the dag plot (Dot) to file.
2. also render the image whenever possible. E.g. if running in Jupyter notebook, the image will not only be saved, ... | 106 | 0 | 31,529 | 13 | |
1 | 4 | async def async_disable_motion_detection(self) -> None:
self._attr_motion_detection_enabled = False
self.async_write_ha_state()
| homeassistant/components/demo/camera.py | 34 | core | {
"docstring": "Disable the motion detection in base station (Disarm).",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 9 | Python | 9 | 57fd84e20c9e98df52a6e81af1fa84ee86028aa8 | camera.py | 315,082 | 4 | 18 | async_disable_motion_detection | https://github.com/home-assistant/core.git | Improve type hints in demo (#74236) | 30 | 0 | 113,679 | 7 | |
2 | 18 | def directed_modularity_matrix(G, nodelist=None, weight=None):
import numpy as np
if nodelist is None:
nodelist = list(G)
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
k_in = A.sum(axis=0)
k_out = A.sum(axis=1)
m = k_in.sum()
# Expected adjacen... | networkx/linalg/modularitymatrix.py | 147 | networkx | {
"docstring": "Returns the directed modularity matrix of G.\n\n The modularity matrix is the matrix B = A - <A>, where A is the adjacency\n matrix and <A> is the expected adjacency matrix, assuming that the graph\n is described by the configuration model.\n\n More specifically, the element B_ij of B is d... | 44 | Python | 35 | 8a325d26aa7fdd3a72580c4720fa97f971bbefcb | modularitymatrix.py | 177,335 | 10 | 92 | directed_modularity_matrix | https://github.com/networkx/networkx.git | Use scipy.sparse array datastructure (#6037)
* Use scipy.sparse array datastructure
* Add reminder to rm wrapper when scipy adds creation fns.
* Rm mention of np matrix from code comment.
* Update networkx/algorithms/bipartite/matrix.py
Co-authored-by: Stefan van der Walt <sjvdwalt@gmail.com>
Co-authore... | 81 | 0 | 42,354 | 10 | |
2 | 5 | def get_nccl_reduce_op(reduce_op):
if reduce_op not in NCCL_REDUCE_OP_MAP:
raise RuntimeError("NCCL does not support reduce op: '{}'.".format(reduce_op))
return NCCL_REDUCE_OP_MAP[reduce_op]
| python/ray/util/collective/collective_group/nccl_util.py | 47 | ray | {
"docstring": "Map the reduce op to NCCL reduce op type.\n\n Args:\n reduce_op (ReduceOp): ReduceOp Enum (SUM/PRODUCT/MIN/MAX).\n Returns:\n (nccl.ncclRedOp_t): the mapped NCCL reduce op.\n ",
"language": "en",
"n_whitespaces": 45,
"n_words": 22,
"vocab_size": 17
} | 17 | Python | 16 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | nccl_util.py | 133,019 | 4 | 27 | get_nccl_reduce_op | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 33 | 0 | 29,926 | 12 | |
2 | 6 | def audit_enum(self) -> AuditMode:
try:
return AuditMode(self.audit)
except ValueError:
raise ValueError(f'Docker completion entry "{self.name}" has an invalid value "{self.audit}" for the "audit" setting.') from None
| test/lib/ansible_test/_internal/completion.py | 62 | ansible | {
"docstring": "The audit requirements for the container. Raises an exception if the value is invalid.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | 25 | Python | 25 | cda16cc5e9aa8703fb4e1ac0a0be6b631d9076cc | completion.py | 268,709 | 6 | 28 | audit_enum | https://github.com/ansible/ansible.git | ansible-test - Improve container management. (#78550)
See changelogs/fragments/ansible-test-container-management.yml for details. | 68 | 0 | 79,610 | 13 | |
1 | 24 | def test_post_build_adapt_update_dataset(self):
input_dataset = tf.data.Dataset.from_tensor_slices(
np.array([[1], [2], [3], [4], [5], [0]])
)
input_data = keras.Input(shape=(1,))
layer = AddingPreprocessingLayer()
output = layer(input_data)
model = ... | keras/engine/base_preprocessing_layer_test.py | 193 | keras | {
"docstring": "Test that preproc layers can adapt() after build() is called.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 35 | Python | 30 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | base_preprocessing_layer_test.py | 271,003 | 11 | 133 | test_post_build_adapt_update_dataset | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 116 | 0 | 80,650 | 12 | |
1 | 2 | def iconsize(self):
return self["iconsize"]
| packages/python/plotly/plotly/graph_objs/layout/mapbox/layer/_symbol.py | 22 | plotly.py | {
"docstring": "\n Sets the symbol icon size (mapbox.layer.layout.icon-size). Has\n an effect only when `type` is set to \"symbol\".\n\n The 'iconsize' property is a number and may be specified as:\n - An int or float\n\n Returns\n -------\n int|float\n ",
"... | 4 | Python | 4 | 43e3a4011080911901176aab919c0ecf5046ddd3 | _symbol.py | 232,063 | 2 | 11 | iconsize | https://github.com/plotly/plotly.py.git | switch to black .22 | 18 | 0 | 63,507 | 7 | |
10 | 17 | def gnu_getopt(args, shortopts, longopts = []):
opts = []
prog_args = []
if isinstance(longopts, str):
longopts = [longopts]
else:
longopts = list(longopts)
# Allow options after non-option arguments?
if shortopts.startswith('+'):
shortopts = shortopts[1:]
... | python3.10.4/Lib/getopt.py | 339 | XX-Net | {
"docstring": "getopt(args, options[, long_options]) -> opts, args\n\n This function works like getopt(), except that GNU style scanning\n mode is used by default. This means that option and non-option\n arguments may be intermixed. The getopt() function stops\n processing options as soon as a non-option... | 96 | Python | 54 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | getopt.py | 217,531 | 30 | 209 | gnu_getopt | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 325 | 0 | 54,836 | 16 | |
2 | 6 | def _dict_like(x):
try:
_ = dict(x)
except (TypeError, ValueError):
return False
return True
| ludwig/utils/numerical_test_utils.py | 43 | ludwig | {
"docstring": "Returns true if an object is a dict or convertible to one, false if not.",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 14
} | 13 | Python | 12 | caaab8ba561850c1b274088f278ff2d27a6f5227 | numerical_test_utils.py | 8,509 | 6 | 25 | _dict_like | https://github.com/ludwig-ai/ludwig.git | Check for nans before testing equality in test_training_determinism (#2687)
* Adds test_numerical_test_utils
* Check finite metrics before checking equality.
* Catch TypeError and ValueError in _dict_like and _enumerable.
* Edits comments. | 39 | 0 | 1,440 | 10 | |
3 | 31 | def to_rotation_matrix(self, v=None, normal=False):
q = self
s = q.norm()**-2
# diagonal elements are different according to parameter normal
if normal:
m00 = s*(q.a**2 + q.b**2 - q.c**2 - q.d**2)
m11 = s*(q.a**2 - q.b**2 + q.c**2 - q.d**2)
... | sympy/algebras/quaternion.py | 690 | sympy | {
"docstring": "Returns the equivalent rotation transformation matrix of the quaternion\n which represents rotation about the origin if v is not passed.\n\n Parameters\n ==========\n\n v : tuple or None\n Default value: None\n normal : bool\n When True, gives a... | 173 | Python | 92 | 34555f1ebe2a2ed1fab2a0a2ae9a8457a75eaa26 | quaternion.py | 200,685 | 28 | 464 | to_rotation_matrix | https://github.com/sympy/sympy.git | changed homogeneous to normal | 450 | 0 | 49,764 | 15 | |
1 | 24 | def test_overriding_has_module_permission(self):
articles = Article._meta.verbose_name_plural.title()
sections = Section._meta.verbose_name_plural.title()
index_url = reverse("admin7:index")
self.client.force_login(self.superuser)
response = self.client.get(index_url)
... | tests/admin_views/tests.py | 459 | django | {
"docstring": "\n If has_module_permission() always returns False, the module shouldn't\n be displayed on the admin index page for any users.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 17
} | 79 | Python | 39 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,841 | 31 | 280 | test_overriding_has_module_permission | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 310 | 0 | 52,128 | 13 | |
1 | 11 | def test_precedence(self):
with self.settings(
INSTALLED_APPS=[
"admin_scripts.complex_app",
"admin_scripts.simple_app",
"django.contrib.auth",
"django.contrib.contenttypes",
]
):
out = StringIO(... | tests/admin_scripts/tests.py | 187 | django | {
"docstring": "\n Apps listed first in INSTALLED_APPS have precedence.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | 34 | Python | 19 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,308 | 23 | 102 | test_precedence | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 299 | 0 | 51,924 | 13 | |
2 | 6 | def clear(self):
for key in self.conn.keys():
self.conn.delete(key)
| .venv/lib/python3.8/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py | 43 | transferlearning | {
"docstring": "Helper for clearing all the keys in a database. Use with\n caution!",
"language": "en",
"n_whitespaces": 18,
"n_words": 12,
"vocab_size": 12
} | 7 | Python | 7 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | redis_cache.py | 61,481 | 3 | 25 | clear | https://github.com/jindongwang/transferlearning.git | upd; format | 32 | 0 | 12,588 | 10 | |
1 | 15 | def upfirdn_2d(x, k, upx=1, upy=1, downx=1, downy=1, padx0=0, padx1=0, pady0=0, pady1=0, impl='cuda'):
r
impl_dict = {
'ref': _upfirdn_2d_ref,
'cuda': _upfirdn_2d_cuda,
}
return impl_dict[impl](x=x, k=k, upx=upx, upy=upy, downx=downx, downy=downy, padx0=padx0, padx1=padx1, pady0=pady0,... | reconstruction/ostec/external/stylegan2/dnnlib/tflib/ops/upfirdn_2d.py | 144 | insightface | {
"docstring": "Pad, upsample, FIR filter, and downsample a batch of 2D images.\n\n Accepts a batch of 2D images of the shape `[majorDim, inH, inW, minorDim]`\n and performs the following operations for each image, batched across\n `majorDim` and `minorDim`:\n\n 1. Pad the image with zeros by the specifie... | 33 | Python | 33 | 7375ee364e0df2a417f92593e09557f1b2a3575a | upfirdn_2d.py | 9,408 | 43 | 103 | upfirdn_2d | https://github.com/deepinsight/insightface.git | initialize ostec | 58 | 0 | 1,608 | 9 | |
1 | 2 | def start(self) -> 'BasePod':
...
| jina/peapods/pods/__init__.py | 20 | jina | {
"docstring": "Start to run all :class:`Pea` in this BasePod.\n\n .. note::\n If one of the :class:`Pea` fails to start, make sure that all of them\n are properly closed.\n ",
"language": "en",
"n_whitespaces": 63,
"n_words": 27,
"vocab_size": 23
} | 5 | Python | 5 | 933415bfa1f9eb89f935037014dfed816eb9815d | __init__.py | 9,880 | 8 | 9 | start | https://github.com/jina-ai/jina.git | feat: star routing (#3900)
* feat(proto): adjust proto for star routing (#3844)
* feat(proto): adjust proto for star routing
* feat(proto): generate proto files
* feat(grpc): refactor grpclet interface (#3846)
* feat: refactor connection pool for star routing (#3872)
* feat(k8s): add more labels to k8s ... | 19 | 0 | 1,750 | 6 | |
6 | 19 | def get_date_list(self, queryset, date_type=None, ordering="ASC"):
date_field = self.get_date_field()
allow_empty = self.get_allow_empty()
if date_type is None:
date_type = self.get_date_list_period()
if self.uses_datetime_field:
date_list = queryset.dat... | django/views/generic/dates.py | 175 | django | {
"docstring": "\n Get a date list by calling `queryset.dates/datetimes()`, checking\n along the way for empty lists that aren't allowed.\n ",
"language": "en",
"n_whitespaces": 39,
"n_words": 17,
"vocab_size": 17
} | 55 | Python | 38 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | dates.py | 206,860 | 17 | 108 | get_date_list | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 230 | 0 | 51,761 | 15 | |
6 | 16 | def unquote_unreserved(uri):
parts = uri.split("%")
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL(f"Invalid percent-escape sequence: '{h}'"... | pipenv/patched/pip/_vendor/requests/utils.py | 215 | pipenv | {
"docstring": "Un-escape any percent-escape sequences in a URI that are unreserved\n characters. This leaves all reserved, illegal and non-ASCII bytes encoded.\n\n :rtype: str\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 22,
"vocab_size": 22
} | 50 | Python | 37 | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | utils.py | 22,163 | 16 | 119 | unquote_unreserved | https://github.com/pypa/pipenv.git | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 198 | 0 | 4,233 | 16 | |
1 | 9 | def set_3d_properties(self, path, zs=0, zdir='z'):
Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir)
self._code3d = path.codes
| lib/mpl_toolkits/mplot3d/art3d.py | 63 | matplotlib | {
"docstring": "\n Set the *z* position and direction of the path patch.\n\n Parameters\n ----------\n path :\n zs : float\n The location along the *zdir* axis in 3D space to position the\n path patch.\n zdir : {'x', 'y', 'z', 3-tuple}\n Plane... | 12 | Python | 12 | df6f95703b60348e01603f98a439b133da2938a0 | art3d.py | 109,925 | 3 | 41 | set_3d_properties | https://github.com/matplotlib/matplotlib.git | Improve mpl_toolkit documentation | 33 | 0 | 23,832 | 8 | |
1 | 4 | def name(self) -> str:
return self._name
| airbyte-cdk/python/airbyte_cdk/sources/declarative/declarative_stream.py | 22 | airbyte | {
"docstring": "\n :return: Stream name. By default this is the implementing class name, but it can be overridden as needed.\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 18,
"vocab_size": 18
} | 6 | Python | 6 | 150ab593f8ca1f1aa960a0811aece26c46ba6c75 | declarative_stream.py | 5,311 | 5 | 12 | name | https://github.com/airbytehq/airbyte.git | Low code connectors: core structure (#12850)
* checkout from alex/cac
* doc
* doc
* remove broken test
* rename
* rename file
* delete unused file
* rename
* abstract property
* isort
* update state
* Update comment
* remove incremental mixin
* delete comment
* update comments... | 20 | 0 | 749 | 6 | |
15 | 58 | def lattice_reference(G, niter=5, D=None, connectivity=True, seed=None):
import numpy as np
from networkx.utils import cumulative_distribution, discrete_sequence
local_conn = nx.connectivity.local_edge_connectivity
if len(G) < 4:
raise nx.NetworkXError("Graph has fewer than four nodes.")... | networkx/algorithms/smallworld.py | 858 | @py_random_state(3)
@not_implemented_for("directed")
@not_implemented_for("multigraph") | networkx | {
"docstring": "Latticize the given graph by swapping edges.\n\n Parameters\n ----------\n G : graph\n An undirected graph.\n\n niter : integer (optional, default=1)\n An edge is rewired approximatively niter times.\n\n D : numpy.array (optional, default=None)\n Distance to the dia... | 350 | Python | 221 | 9d5e11f27033049282e2d244132b0e946df6557d | smallworld.py | 177,545 | 52 | 533 | lattice_reference | https://github.com/networkx/networkx.git | bug fix in smallworld.py: random_reference and lattice_reference (#6151)
* raise exception if graph has less than 2 edges in random_reference and lattice_reference and tested
* Updated lattice_reference doc
* Update networkx/algorithms/smallworld.py
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
* U... | 997 | 1 | 42,433 | 17 |
1 | 10 | def binary_matches(y_true, y_pred, threshold=0.5):
y_pred = tf.convert_to_tensor(y_pred)
threshold = tf.cast(threshold, y_pred.dtype)
y_pred = tf.cast(y_pred > threshold, y_pred.dtype)
return tf.cast(tf.equal(y_true, y_pred), tf.int8) | keras/utils/metrics_utils.py | 98 | keras | {
"docstring": "Creates int Tensor, 1 for label-prediction match, 0 for mismatch.\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n threshold: (Optional) Float representing the threshold for deciding whether\n ... | 21 | Python | 17 | 119cd4655d01570a70c70879dff4461ea46161bf | metrics_utils.py | 268,987 | 5 | 66 | binary_matches | https://github.com/keras-team/keras.git | Added util metric method for binary_matches. Decoupled from public metric binarry_acc | 26 | 0 | 79,806 | 9 | |
2 | 5 | def _flatten_parameters(self):
[m.flatten_parameters() for m in self._to_flatten]
| synthesizer/models/sublayer/cbhg.py | 33 | MockingBird | {
"docstring": "Calls `flatten_parameters` on all the rnns used by the WaveRNN. Used\n to improve efficiency and avoid PyTorch yelling at us.",
"language": "en",
"n_whitespaces": 26,
"n_words": 20,
"vocab_size": 19
} | 7 | Python | 7 | 6abdd0ebf06ddede5cdf91329143b56167492a17 | cbhg.py | 161,297 | 2 | 19 | _flatten_parameters | https://github.com/babysor/MockingBird.git | Refactor (#649)
* Refactor model
* Refactor and fix bug to save plots | 21 | 0 | 38,959 | 8 | |
2 | 7 | def compat_system(source_dir):
try:
system = load_system(source_dir)
except (FileNotFoundError, KeyError):
system = {}
system.setdefault(
'build-backend',
'setuptools.build_meta:__legacy__',
)
system.setdefault('requires', ['setuptools', 'wheel'])
return syst... | .venv/lib/python3.8/site-packages/pip/_vendor/pep517/build.py | 87 | transferlearning | {
"docstring": "\n Given a source dir, attempt to get a build system backend\n and requirements from pyproject.toml. Fallback to\n setuptools but only if the file was not found or a build\n system was not indicated.\n ",
"language": "en",
"n_whitespaces": 49,
"n_words": 33,
"vocab_size": 26
} | 21 | Python | 18 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | build.py | 62,961 | 11 | 48 | compat_system | https://github.com/jindongwang/transferlearning.git | upd; format | 70 | 0 | 13,077 | 10 | |
2 | 7 | def table(self, data=None):
if _use_arrow():
return self.dg._arrow_table(data)
else:
return self.dg._legacy_table(data)
| lib/streamlit/elements/dataframe_selector.py | 59 | streamlit | {
"docstring": "Display a static table.\n\n This differs from `st.dataframe` in that the table in this case is\n static: its entire contents are laid out directly on the page.\n\n Parameters\n ----------\n data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, Iterabl... | 10 | Python | 9 | 72703b38029f9358a0ec7ca5ed875a6b438ece19 | dataframe_selector.py | 118,729 | 5 | 35 | table | https://github.com/streamlit/streamlit.git | Replace static apps with live Cloud apps (#4317)
Co-authored-by: kajarenc <kajarenc@gmail.com> | 53 | 0 | 26,386 | 11 | |
8 | 41 | def _galois_group_degree_4_simple(T, max_tries=30, randomize=False):
r
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.named_groups import (
CyclicGroup, AbelianGroup, DihedralGroup, AlternatingGroup, SymmetricGroup
)
# Consider the resolvent for the form
... | sympy/polys/numberfields/galoisgroups.py | 522 | sympy | {
"docstring": "\n Compute the Galois group of a polynomial of degree 4, using Alg 6.3.6\n of Cohen.\n\n References\n ==========\n\n .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.\n\n ",
"language": "en",
"n_whitespaces": 47,
"n_words": 28,
"vocab_size": 26
} | 223 | Python | 154 | d3c0fc825c4a80904a1fb9a2092137c3d9e0c3fe | galoisgroups.py | 195,690 | 46 | 353 | _galois_group_degree_4_simple | https://github.com/sympy/sympy.git | Add a `galois_group()` function | 429 | 0 | 47,373 | 16 | |
1 | 4 | def unsaved_files(self) -> List[str]:
| certbot-apache/certbot_apache/_internal/interfaces.py | 20 | certbot | {
"docstring": "\n Returns a list of file paths that have been changed since the last save\n (or the initial configuration parse). The intended use for this method\n is to tell the Reverter which files need to be included in a checkpoint.\n\n This is typically called for the root of the Pa... | 4 | Python | 4 | 7d9e9a49005de7961e84d2a7c608db57dbab3046 | interfaces.py | 186,652 | 11 | 11 | unsaved_files | https://github.com/certbot/certbot.git | Add typing to certbot.apache (#9071)
* Add typing to certbot.apache
Co-authored-by: Adrien Ferrand <ferrand.ad@gmail.com> | 11 | 0 | 45,560 | 6 | |
4 | 31 | def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
origBbox = fig.bbox
origBboxInches = fig.bbox_inches
orig_layout = fig.get_layout_engine()
fig.set_layout_engine(None)
_boxout = fig.transFigure._boxout
old_aspect = []
locator_list = []
sentinel = object()
for ax in fig.axes:
... | lib/matplotlib/_tight_bbox.py | 221 | matplotlib | {
"docstring": "\n Temporarily adjust the figure so that only the specified area\n (bbox_inches) is saved.\n\n It modifies fig.bbox, fig.bbox_inches,\n fig.transFigure._boxout, and fig.patch. While the figure size\n changes, the scale of the original figure is conserved. A\n function which restore... | 63 | Python | 51 | ec4dfbc3c83866f487ff0bc9c87b0d43a1c02b22 | _tight_bbox.py | 107,130 | 32 | 274 | adjust_bbox | https://github.com/matplotlib/matplotlib.git | ENH: implement and use base layout_engine for more flexible layout. | 164 | 0 | 22,596 | 13 | |
2 | 7 | def get_currency(symbol) -> str:
ticker_info = yf.Ticker(symbol).info
if "financialCurrency" in ticker_info:
return ticker_info["financialCurrency"]
return "Not Specified"
| openbb_terminal/stocks/fundamental_analysis/yahoo_finance_model.py | 56 | OpenBBTerminal | {
"docstring": "Quick helper to get currency for financial statements",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 16 | Python | 15 | 92991fc4e3097fdd9ac9f4f39bdd8e46289176cd | yahoo_finance_model.py | 285,622 | 6 | 30 | get_currency | https://github.com/OpenBB-finance/OpenBBTerminal.git | Get rid of option expirations in the past for Nasdaq + bugs (#2498)
* Get rid of option expirations in the past for Nasdaq + clean up bug
* Add in currency for yfinance financials
* Added fixes
Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>
Co-authored-by: colin99d <colin99delah... | 35 | 0 | 85,330 | 9 | |
1 | 23 | def _solve_eigen(self, X, y, shrinkage, covariance_estimator):
| sklearn/discriminant_analysis.py | 46 | """Eigenvalue solver.
The eigenvalue solver computes the optimal solution of thecoefficient (basically the ratio of between class scatter to within | scikit-learn | {
"docstring": "Eigenvalue solver.\n\n The eigenvalue solver computes the optimal solution of the Rayleigh\n coefficient (basically the ratio of between class scatter to within",
"language": "en",
"n_whitespaces": 35,
"n_words": 22,
"vocab_size": 19
} | 6 | Python | 6 | e1db2a8173ca37e561cdfa4384481501c4d50868 | discriminant_analysis.py | 258,768 | 18 | 187 | _solve_eigen | https://github.com/scikit-learn/scikit-learn.git | Use check_finite=False in discriminant analysis (#18909)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com> | 13 | 2 | 75,415 | 5 |
2 | 7 | def model_call_inputs(model, keep_original_batch_size=False):
input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size)
if input_specs is None:
return None, None
input_specs = _enforce_names_consistency(input_specs)
return input_specs
| keras/saving/saving_utils.py | 63 | keras | {
"docstring": "Inspect model to get its input signature.\n\n The model's input signature is a list with a single (possibly-nested) object.\n This is due to the Keras-enforced restriction that tensor inputs must be\n passed in as the first argument.\n\n For example, a model with input {'feature1': <Tensor... | 19 | Python | 14 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | saving_utils.py | 276,243 | 6 | 38 | model_call_inputs | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 41 | 0 | 81,601 | 10 | |
1 | 10 | def test_login_redirect_for_direct_get(self):
response = self.client.get(reverse("admin:login"))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context[REDIRECT_FIELD_NAME], reverse("admin:index"))
| tests/admin_views/tests.py | 77 | django | {
"docstring": "\n Login redirect should be to the admin index page when going directly to\n /admin/login/.\n ",
"language": "en",
"n_whitespaces": 36,
"n_words": 14,
"vocab_size": 13
} | 9 | Python | 9 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,740 | 4 | 45 | test_login_redirect_for_direct_get | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 37 | 0 | 52,079 | 11 | |
3 | 19 | def tokenizer_from_json(json_string):
tokenizer_config = json.loads(json_string)
config = tokenizer_config.get("config")
word_counts = json.loads(config.pop("word_counts"))
word_docs = json.loads(config.pop("word_docs"))
index_docs = json.loads(config.pop("index_docs"))
# Integer indexing ... | keras/preprocessing/text.py | 274 | keras | {
"docstring": "Parses a JSON tokenizer configuration and returns a tokenizer instance.\n\n Deprecated: `tf.keras.preprocessing.text.Tokenizer` does not operate on\n tensors and is not recommended for new code. Prefer\n `tf.keras.layers.TextVectorization` which provides equivalent functionality\n through ... | 70 | Python | 41 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | text.py | 275,787 | 17 | 161 | tokenizer_from_json | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 124 | 0 | 81,466 | 11 | |
1 | 4 | def shape(self):
return (self.rows, self.cols)
| sympy/matrices/common.py | 27 | sympy | {
"docstring": "The shape (dimensions) of the matrix as the 2-tuple (rows, cols).\n\n Examples\n ========\n\n >>> from sympy import zeros\n >>> M = zeros(2, 3)\n >>> M.shape\n (2, 3)\n >>> M.rows\n 2\n >>> M.cols\n 3\n ",
"language": "en",... | 5 | Python | 5 | 59d22b6bb7287613d598611027f640d068ca5748 | common.py | 196,368 | 2 | 16 | shape | https://github.com/sympy/sympy.git | Moved imports to higher level | 19 | 0 | 47,868 | 7 | |
3 | 20 | def test_sync_call_healthy_only(self):
actors = [Actor.remote(i) for i in range(4)]
manager = FaultTolerantActorManager(actors=actors)
results = []
for _ in range(10):
results.extend(
manager.foreach_actor(
lambda w: w.call(), hea... | rllib/utils/tests/test_actor_manager.py | 144 | ray | {
"docstring": "Test synchronous remote calls to only healthy actors.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 114 | Python | 86 | d329147ae28c57b290f6b932f9f3044523f67c4e | test_actor_manager.py | 135,567 | 12 | 83 | test_sync_call_healthy_only | https://github.com/ray-project/ray.git | [RLlib] Introduce FaultTolerantActorManager (#29703)
Signed-off-by: Jun Gong <jungong@anyscale.com> | 298 | 0 | 30,658 | 16 | |
5 | 23 | def _get_time_micros(self) -> npt.NDArray[np.int64]:
values = self._data._local_timestamps()
reso = self._data._reso
ppd = periods_per_day(reso)
frac = values % ppd
if reso == NpyDatetimeUnit.NPY_FR_ns.value:
micros = frac // 1000
elif reso == NpyDa... | pandas/core/indexes/datetimes.py | 185 | pandas | {
"docstring": "\n Return the number of microseconds since midnight.\n\n Returns\n -------\n ndarray[int64_t]\n ",
"language": "en",
"n_whitespaces": 46,
"n_words": 10,
"vocab_size": 10
} | 64 | Python | 35 | 80c005e67f96f431674a37ecd8a9e8a2808f7db4 | datetimes.py | 167,469 | 24 | 113 | _get_time_micros | https://github.com/pandas-dev/pandas.git | ENH: DatetimeIndex.indexer_between_time support non-nano (#47535) | 204 | 0 | 40,025 | 10 | |
2 | 5 | def test_whether_worker_leaked_when_task_finished_with_errors(ray_start_regular):
driver_template = | python/ray/tests/test_advanced_2.py | 22 | driver_template = """
import ray
import os
import ray
import numpy as np
import time
ray.init(address="{address}", namespace="test")@ray.remote | ray | {
"docstring": "\nimport ray\nimport os\nimport ray\nimport numpy as np\nimport time\n\nray.init(address=\"{address}\", namespace=\"test\")\n\n# The util actor to store the pid cross jobs.\n@ray.remote",
"language": "en",
"n_whitespaces": 17,
"n_words": 25,
"vocab_size": 20
} | 4 | Python | 4 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | test_advanced_2.py | 131,209 | 60 | 139 | test_whether_worker_leaked_when_task_finished_with_errors | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 7 | 2 | 29,485 | 5 |
1 | 14 | async def endpoint_discovery(self, empty, context) -> jina_pb2.EndpointsProto:
endpointsProto = jina_pb2.EndpointsProto()
endpointsProto.endpoints.extend(
list(self._data_request_handler._executor.requests.keys())
)
return endpointsProto
| jina/serve/runtimes/worker/__init__.py | 73 | jina | {
"docstring": "\n Process the the call requested and return the list of Endpoints exposed by the Executor wrapped inside this Runtime\n\n :param empty: The service expects an empty protobuf message\n :param context: grpc context\n :returns: the response request\n ",
"language": "... | 15 | Python | 14 | 65d6d6da50cb795499ea5e361bf14908f62a3168 | __init__.py | 12,303 | 13 | 44 | endpoint_discovery | https://github.com/jina-ai/jina.git | feat: gateway endpoint discovery (#4756) | 61 | 0 | 2,252 | 14 | |
1 | 7 | def to_json(self) -> dict:
return {
"name": self.name,
"type": self.type.name,
"class": self.class_.name,
}
@dataclass | mitmproxy/dns.py | 61 | @dataclass | mitmproxy | {
"docstring": "\n Converts the question into json for mitmweb.\n Sync with web/src/flow.ts.\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 10,
"vocab_size": 10
} | 14 | Python | 14 | ea6f9727dab03b0811c180bab761d28b7e57ef50 | dns.py | 250,941 | 10 | 33 | to_json | https://github.com/mitmproxy/mitmproxy.git | [dns] use snake_case in web flows | 67 | 1 | 73,570 | 9 |
4 | 23 | def test_higher_rank_inputs_for_importance_weights(self):
for fw in framework_iterator(frameworks=("torch", "tf"), session=True):
vtrace = vtrace_tf if fw != "torch" else vtrace_torch
if fw == "tf":
inputs_ = {
"log_rhos": tf1.placeholder(
... | rllib/agents/impala/tests/test_vtrace.py | 447 | ray | {
"docstring": "Checks support for additional dimensions in inputs.",
"language": "en",
"n_whitespaces": 6,
"n_words": 7,
"vocab_size": 7
} | 96 | Python | 47 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | test_vtrace.py | 133,740 | 29 | 315 | test_higher_rank_inputs_for_importance_weights | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 583 | 0 | 30,091 | 18 | |
11 | 36 | def CCompiler_spawn(self, cmd, display=None, env=None):
env = env if env is not None else dict(os.environ)
if display is None:
display = cmd
if is_sequence(display):
display = " ".join(list(display))
log.info(display)
try:
if self.verbose:
subprocess.... | sklearn/externals/_numpy_compiler_patch.py | 374 | scikit-learn | {
"docstring": "\n Execute a command in a sub-process.\n\n Parameters\n ----------\n cmd : str\n The command to execute.\n display : str or sequence of str, optional\n The text to add to the log file kept by `numpy.distutils`.\n If not given, `display` is equal to `cmd`.\n env: ... | 195 | Python | 126 | 8a6cf1a33e80d0e4caa16205ce199a9e1bea7657 | _numpy_compiler_patch.py | 259,371 | 35 | 213 | CCompiler_spawn | https://github.com/scikit-learn/scikit-learn.git | BLD Monkeypatch windows build to stablize build (#22693) | 481 | 0 | 75,736 | 15 | |
1 | 4 | def not_public(self):
return self.filter(self.private_q())
| wagtail/query.py | 31 | wagtail | {
"docstring": "\n Filters the QuerySet to only contain pages that are in a private\n section and their descendants.\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 16,
"vocab_size": 16
} | 4 | Python | 4 | 180d43a200163f5b7c75280f7bbf7cb4e5de1b91 | query.py | 79,209 | 2 | 17 | not_public | https://github.com/wagtail/wagtail.git | Fix Page queryset.not_public returning all pages when no page restrictions exist. (#9067)
Fixes #8952 | 18 | 0 | 16,893 | 9 | |
1 | 10 | def get_previous_release(self, project):
return (
ReleaseProject.objects.filter(project=project, release__date_added__lt=self.date_added)
.order_by("-release__date_added")
.first()
)
| src/sentry/models/release.py | 60 | sentry | {
"docstring": "Get the release prior to this one. None if none exists",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 10 | Python | 10 | 272d35503a2d5174dfa8cad57f94a2354e453bf3 | release.py | 93,634 | 6 | 36 | get_previous_release | https://github.com/getsentry/sentry.git | feat(ingest): Automatically associate commits to checksum release (#36491)
Feature for Workflow 2.0. If the SDK is configured to file an event with the release version matching the release commit SHA, ingest will look to see if there have been commits between the release version and the previous release on Github. If ... | 64 | 0 | 19,000 | 14 | |
2 | 6 | def trace(log_dir, create_perfetto_link=False, create_perfetto_trace=False):
start_trace(log_dir, create_perfetto_link, create_perfetto_trace)
try:
yield
finally:
stop_trace()
| jax/_src/profiler.py | 51 | jax | {
"docstring": "Context manager to take a profiler trace.\n\n The trace will capture CPU, GPU, and/or TPU activity, including Python\n functions and JAX on-device operations.\n\n The resulting trace can be viewed with TensorBoard. Note that TensorBoard\n doesn't need to be running when collecting the trace.\n\n ... | 11 | Python | 11 | 260f1d8b843483df46cf397ae5a1afc0abc9c64f | profiler.py | 121,807 | 6 | 30 | trace | https://github.com/google/jax.git | Add option to generate perfetto trace without generating link | 21 | 0 | 27,075 | 10 | |
4 | 13 | def repartition(self, axis=None):
if StorageFormat.get() == "Hdk":
# Hdk uses only one partition, it makes
# no sense for it to repartition the dataframe.
return self
axes = [0, 1] if axis is None else [axis]
new_query_compiler = self
for _a... | modin/core/storage_formats/base/query_compiler.py | 113 | modin | {
"docstring": "\n Repartitioning QueryCompiler objects to get ideal partitions inside.\n\n Allows to improve performance where the query compiler can't improve\n yet by doing implicit repartitioning.\n\n Parameters\n ----------\n axis : {0, 1, None}, optional\n Th... | 61 | Python | 49 | 704ded959541bcf55acadfb49f3fda804267b767 | query_compiler.py | 155,395 | 12 | 70 | repartition | https://github.com/modin-project/modin.git | FEAT-#5367: Introduce new API for repartitioning Modin objects (#5366)
Co-authored-by: Iaroslav Igoshev <Poolliver868@mail.ru>
Co-authored-by: Vasily Litvinov <fam1ly.n4me@yandex.ru>
Signed-off-by: Anatoly Myachev <anatoly.myachev@intel.com> | 210 | 0 | 36,375 | 14 | |
2 | 12 | def show_compilers():
# XXX this "knows" that the compiler option it's describing is
# "--compiler", which just happens to be the case for the three
# commands that use it.
from distutils.fancy_getopt import FancyGetopt
compilers = []
for compiler in compiler_class.keys():
compilers... | python3.10.4/Lib/distutils/ccompiler.py | 106 | XX-Net | {
"docstring": "Print list of available compilers (used by the \"--help-compiler\"\n options to \"build\", \"build_ext\", \"build_clib\").\n ",
"language": "en",
"n_whitespaces": 20,
"n_words": 14,
"vocab_size": 14
} | 52 | Python | 44 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | ccompiler.py | 222,587 | 9 | 61 | show_compilers | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 114 | 0 | 56,655 | 12 | |
1 | 12 | def test_acquire_unavailable(ray_start_4_cpus):
manager = PlacementGroupResourceManager(update_interval_s=0)
assert not manager.acquire_resources(REQUEST_2_CPU)
manager.request_resources(REQUEST_2_CPU)
ray.wait(manager.get_resource_futures(), num_returns=1)
assert manager.acquire_resources(REQ... | python/ray/air/tests/test_resource_manager_placement_group.py | 82 | ray | {
"docstring": "Test that acquiring resources that are not available returns None.\n\n - Try to acquire\n - Assert this does not work\n - Request resources\n - Wait until ready\n - Acquire\n - Assert this did work\n ",
"language": "en",
"n_whitespaces": 55,
"n_words": 34,
"vocab_size": 23... | 13 | Python | 11 | edb17fd2069844f12237c85ba6607afae536401d | test_resource_manager_placement_group.py | 138,061 | 6 | 49 | test_acquire_unavailable | https://github.com/ray-project/ray.git | [air/tune] Internal resource management 1 - Ray AIR resource manager implementation (#30777)
Prerequisite to #30016
This PR adds a new Ray AIR resource manager to replace the PlacementGroupManager of Ray Tune. Details can be found in #30016.
Specifically, this PR
- Adds the main resource manager abstractions
-... | 31 | 0 | 31,300 | 9 | |
23 | 25 | def multiset_derangements(s):
ms = multiset(s)
mx = max(ms.values())
n = len(s)
# special cases
# 0) impossible case
if mx*2 > n:
return
# 1) singletons
if len(ms) == n:
for p in generate_derangements(s):
yield p
return
for M in ms:
... | sympy/utilities/iterables.py | 486 | sympy | {
"docstring": "Generate derangements of the elements of s *in place*.\n\n Examples\n ========\n\n >>> from sympy.utilities.iterables import multiset_derangements, uniq\n\n Because the derangements of multisets (not sets) are generated\n in place, copies of the return value must be made if a collection... | 190 | Python | 90 | 25aaf2c3a6ac0d39da710d6e67f244930b56d669 | iterables.py | 195,921 | 45 | 358 | multiset_derangements | https://github.com/sympy/sympy.git | fix repeat covers all but 1 | 569 | 0 | 47,476 | 16 | |
1 | 7 | def content_type(model):
return ContentType.objects.get_for_model(model)
@register.filter() | netbox/utilities/templatetags/builtins/filters.py | 38 | @register.filter() | netbox | {
"docstring": "\n Return the ContentType for the given object.\n ",
"language": "en",
"n_whitespaces": 14,
"n_words": 7,
"vocab_size": 6
} | 5 | Python | 5 | 7c105019d8ae9205051c302e7499b33a455f9176 | filters.py | 264,445 | 2 | 15 | content_type | https://github.com/netbox-community/netbox.git | Closes #8600: Document built-in template tags & filters | 10 | 1 | 77,731 | 8 |
4 | 18 | def set_weights(self, weights):
params = self.weights
if len(params) != len(weights):
raise ValueError(
"Length of the specified weight list ("
+ str(len(weights))
+ ") does not match the number of weights "
"of the opt... | keras/optimizers/optimizer_v1.py | 212 | keras | {
"docstring": "Sets the weights of the optimizer, from Numpy arrays.\n\n Should only be called after computing the gradients\n (otherwise the optimizer has no weights).\n\n Args:\n weights: a list of Numpy arrays. The number of arrays and their shape\n must match number o... | 82 | Python | 56 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | optimizer_v1.py | 275,342 | 21 | 125 | set_weights | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 341 | 0 | 81,383 | 17 | |
1 | 11 | def test__render_filenames_undefined_template():
path = "/srv/salt/saltines"
dest = "/srv/salt/cheese"
saltenv = "base"
template = "biscuits"
ret = (path, dest)
pytest.raises(
CommandExecutionError, cp._render_filenames, path, dest, saltenv, template
)
| tests/pytests/unit/modules/test_cp.py | 73 | salt | {
"docstring": "\n Test if _render_filenames fails upon getting a template not in\n TEMPLATE_REGISTRY.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 11,
"vocab_size": 11
} | 26 | Python | 21 | ba58c71c55f8d65e702525faf435c2de91aae85c | test_cp.py | 215,688 | 9 | 42 | test__render_filenames_undefined_template | https://github.com/saltstack/salt.git | move cp exec module tests to pytest | 57 | 0 | 54,099 | 8 | |
9 | 10 | def match(self, node, results=None):
if self.type is not None and node.type != self.type:
return False
if self.content is not None:
r = None
if results is not None:
r = {}
if not self._submatch(node, r):
return Fals... | python3.10.4/Lib/lib2to3/pytree.py | 145 | XX-Net | {
"docstring": "\n Does this pattern exactly match a node?\n\n Returns True if it matches, False if not.\n\n If results is not None, it must be a dict which will be\n updated with the nodes matching named subpatterns.\n\n Default implementation for non-wildcard patterns.\n ",... | 52 | Python | 29 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | pytree.py | 218,860 | 14 | 93 | match | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 198 | 0 | 55,510 | 11 | |
2 | 5 | def endswith_cr(line):
return line.endswith("\r" if isinstance(line, str) else b"\r")
| django/core/files/base.py | 43 | django | {
"docstring": "Return True if line (a text or bytestring) ends with '\\r'.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 9 | Python | 9 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | base.py | 204,478 | 2 | 23 | endswith_cr | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 15 | 0 | 50,741 | 10 | |
3 | 10 | def _get_n_args(self, args, example, n):
# type: (List[str], str, int) -> Any
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise Pip... | .venv/lib/python3.8/site-packages/pip/_internal/commands/configuration.py | 93 | transferlearning | {
"docstring": "Helper to make sure the command got the right number of arguments\n ",
"language": "en",
"n_whitespaces": 19,
"n_words": 12,
"vocab_size": 11
} | 45 | Python | 43 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | configuration.py | 60,598 | 11 | 56 | _get_n_args | https://github.com/jindongwang/transferlearning.git | upd; format | 165 | 0 | 12,217 | 13 | |
5 | 19 | def tmpfile(extension="", dir=None):
extension = extension.lstrip(".")
if extension:
extension = "." + extension
handle, filename = tempfile.mkstemp(extension, dir=dir)
os.close(handle)
os.remove(filename)
try:
yield filename
finally:
if os.path.exists(filename)... | dask/utils.py | 179 | @contextmanager | dask | {
"docstring": "\n Function to create and return a unique temporary file with the given extension, if provided.\n\n Parameters\n ----------\n extension : str\n The extension of the temporary file to be created\n dir : str\n If ``dir`` is not None, the file will be created in that director... | 43 | Python | 35 | bf66221722cce8f09a9b09895bdb4596f14a5430 | utils.py | 156,915 | 16 | 100 | tmpfile | https://github.com/dask/dask.git | `tmpfile` does not end files with period on empty extension (#9429) | 167 | 1 | 36,805 | 17 |
2 | 19 | def test_normalized_P5_directed(self):
G = nx.DiGraph()
nx.add_path(G, range(5))
b_answer = {0: 0, 1: 1.0 / 12.0, 2: 1.0 / 12.0, 3: 0, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[3], normalized=True, weight=None
)
for n ... | networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py | 162 | networkx | {
"docstring": "Betweenness Centrality Subset: Normalized Directed P5",
"language": "en",
"n_whitespaces": 5,
"n_words": 6,
"vocab_size": 6
} | 43 | Python | 36 | 4376a6f751874dceff9dadc0a6a6bfc2dfa04000 | test_betweenness_centrality_subset.py | 177,474 | 9 | 120 | test_normalized_P5_directed | https://github.com/networkx/networkx.git | PR for issue #6033 Improve test coverage for algorithms in betweenness_subset.py #6033 (#6083)
* Updated test_betweenness_centrality_subset.py
* add test of normalized in test_betweenness_centrality_subset.py
* add test of normalized in test_betweenness_centrality_subset.py
* update test of normalized in test... | 114 | 0 | 42,386 | 11 | |
2 | 10 | def window_frame_rows_start_end(self, start=None, end=None):
if not self.connection.features.supports_over_clause:
raise NotSupportedError("This backend does not support window expressions.")
return self.window_frame_start(start), self.window_frame_end(end)
| django/db/backends/base/operations.py | 71 | django | {
"docstring": "\n Return SQL for start and end points in an OVER clause window frame.\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 13,
"vocab_size": 13
} | 18 | Python | 17 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | operations.py | 204,877 | 4 | 43 | window_frame_rows_start_end | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 50 | 0 | 50,950 | 10 | |
4 | 17 | def completion_item_yank(self, sel=False):
text = self._cmd.selectedText()
if not text:
index = self.currentIndex()
if not index.isValid():
raise cmdutils.CommandError("No item selected!")
text = self._model().data(index)
if not utils... | qutebrowser/completion/completionwidget.py | 133 | qutebrowser | {
"docstring": "Yank the current completion item into the clipboard.\n\n Args:\n sel: Use the primary selection instead of the clipboard.\n ",
"language": "en",
"n_whitespaces": 43,
"n_words": 18,
"vocab_size": 14
} | 30 | Python | 22 | a20bb67a878b2e68abf8268c1b0a27f018d01352 | completionwidget.py | 320,775 | 10 | 78 | completion_item_yank | https://github.com/qutebrowser/qutebrowser.git | mypy: Upgrade to PyQt5-stubs 5.15.6.0
For some unknown reason, those new stubs cause a *lot* of things now to be
checked by mypy which formerly probably got skipped due to Any being implied
somewhere.
The stubs themselves mainly improved, with a couple of regressions too.
In total, there were some 337 (!) new mypy e... | 124 | 0 | 117,342 | 12 | |
1 | 3 | def show_panel_furniture(self):
return self.is_shown()
| wagtail/admin/panels.py | 23 | wagtail | {
"docstring": "\n Whether this panel shows the panel furniture instead of being rendered outside of it.\n ",
"language": "en",
"n_whitespaces": 37,
"n_words": 14,
"vocab_size": 12
} | 4 | Python | 4 | 9a1606c809b2daee005591d98e9e2058e4823c79 | panels.py | 79,326 | 2 | 12 | show_panel_furniture | https://github.com/wagtail/wagtail.git | Add show_panel_furniture() in BoundPanel
This allows TabbedInterface to hide a tab but still render its children | 26 | 0 | 16,917 | 7 | |
2 | 11 | def header_encode(header_bytes, charset='iso-8859-1'):
# Return empty headers as an empty string.
if not header_bytes:
return ''
# Iterate over every byte, encoding if necessary.
encoded = header_bytes.decode('latin1').translate(_QUOPRI_HEADER_MAP)
# Now add the RFC chrome to each encod... | python3.10.4/Lib/email/quoprimime.py | 107 | XX-Net | {
"docstring": "Encode a single header line with quoted-printable (like) encoding.\n\n Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but\n used specifically for email header fields to allow charsets with mostly 7\n bit characters (and some 8 bit) to remain more or less readable in no... | 58 | Python | 48 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | quoprimime.py | 223,870 | 5 | 37 | header_encode | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 90 | 0 | 57,121 | 11 | |
3 | 47 | def forward(self, src_word, trg_word):
r
src_max_len = paddle.shape(src_word)[-1]
trg_max_len = paddle.shape(trg_word)[-1]
src_slf_attn_bias = paddle.cast(
src_word == self.bos_id,
dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e4
src_slf_attn_bia... | paddlenlp/transformers/transformer/modeling.py | 457 | PaddleNLP | {
"docstring": "\n The Transformer forward methods. The input are source/target sequences, and\n returns logits.\n\n Args:\n src_word (Tensor):\n The ids of source sequences words. It is a tensor with shape\n `[batch_size, source_sequence_length]` and its ... | 115 | Python | 67 | b0c35d5e1ff02a634fa26392b60d3885c2c78677 | modeling.py | 322,101 | 84 | 301 | forward | https://github.com/PaddlePaddle/PaddleNLP.git | Fix the attention mask for fp16 (#1585) | 528 | 0 | 118,058 | 14 | |
1 | 5 | def is_nan(self, a):
a = _convert_other(a, raiseit=True)
return a.is_nan()
| python3.10.4/Lib/_pydecimal.py | 40 | XX-Net | {
"docstring": "Return True if the operand is a qNaN or sNaN;\n otherwise return False.\n\n >>> ExtendedContext.is_nan(Decimal('2.50'))\n False\n >>> ExtendedContext.is_nan(Decimal('NaN'))\n True\n >>> ExtendedContext.is_nan(Decimal('-sNaN'))\n True\n >>> Extend... | 9 | Python | 9 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | _pydecimal.py | 219,742 | 3 | 24 | is_nan | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 30 | 0 | 55,761 | 9 | |
12 | 21 | def _set_hyperopt_defaults(self):
if not self.hyperopt:
return
scheduler = self.hyperopt.get("executor", {}).get("scheduler")
if not scheduler:
return
if EXECUTOR in self.hyperopt:
set_default_value(self.hyperopt[EXECUTOR], TYPE, RAY)
... | ludwig/schema/model_config.py | 326 | ludwig | {
"docstring": "This function was migrated from defaults.py with the intention of setting some hyperopt defaults while\n the hyperopt section of the config object is not fully complete.\n\n Returns:\n None -> modifies trainer and hyperopt sections\n ",
"language": "en",
"n_whitespa... | 189 | Python | 106 | 4d2d81f9fdefc52eea6a9bf0826a6f2ffc8d681b | model_config.py | 8,418 | 28 | 188 | _set_hyperopt_defaults | https://github.com/ludwig-ai/ludwig.git | Config Object (#2426)
* Fixed loss instances across features
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fixed binary OneOfImplementation
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
... | 517 | 0 | 1,427 | 14 | |
6 | 29 | def update(self, data):
data = np.atleast_1d(np.array(data, dtype=object))
# check if convertible to number:
convertible = True
for val in OrderedDict.fromkeys(data):
# OrderedDict just iterates over unique values in data.
_api.check_isinstance((str, byte... | lib/matplotlib/category.py | 238 | matplotlib | {
"docstring": "\n Map new values to integer identifiers.\n\n Parameters\n ----------\n data : iterable of str or bytes\n\n Raises\n ------\n TypeError\n If elements in *data* are neither str nor bytes.\n ",
"language": "en",
"n_whitespaces": 95,
... | 117 | Python | 85 | c0a384e9f41673207eac75e276b293418bd32965 | category.py | 108,041 | 14 | 100 | update | https://github.com/matplotlib/matplotlib.git | Fix incorrect deprecation warning | 317 | 0 | 23,035 | 13 | |
9 | 17 | def putpixel(self, xy, value):
if self.readonly:
self._copy()
self.load()
if self.pyaccess:
return self.pyaccess.putpixel(xy, value)
if (
self.mode in ("P", "PA")
and isinstance(value, (list, tuple))
and len(value) i... | src/PIL/Image.py | 225 | Pillow | {
"docstring": "\n Modifies the pixel at the given position. The color is given as\n a single numerical value for single-band images, and a tuple for\n multi-band images. In addition to this, RGB and RGBA tuples are\n accepted for P and PA images.\n\n Note that this method is relati... | 71 | Python | 49 | a37593f004247ebf69d5582524da6dc5143cb023 | Image.py | 243,180 | 18 | 142 | putpixel | https://github.com/python-pillow/Pillow.git | Allow RGB and RGBA values for PA image putpixel | 264 | 0 | 70,002 | 14 | |
11 | 54 | def batch(_func=None, max_batch_size=10, batch_wait_timeout_s=0.0):
| python/ray/serve/batching.py | 167 | """Converts a function to asynchronously handle batches.
The function can be a standalonea class method. Inthe function must betake a list ofits solereturn a list of the sameainvokedthe caller passes a single object. These will beand executed asynchronously oncea batch ofor `batch_wait_timeout_s` hasoccurs first:
... | ray | {
"docstring": "Converts a function to asynchronously handle batches.\n\n The function can be a standalone function or a class method. In both\n cases, the function must be `async def` and take a list of objects as\n its sole argument and return a list of the same length as a result.\n\n When invoked, the... | 4 | Python | 4 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | batching.py | 130,855 | 21 | 137 | batch | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 7 | 14 | 29,405 | 10 |
1 | 3 | def n(self):
return self.args[0]
| sympy/combinatorics/graycode.py | 23 | sympy | {
"docstring": "\n Returns the dimension of the Gray code.\n\n Examples\n ========\n\n >>> from sympy.combinatorics import GrayCode\n >>> a = GrayCode(5)\n >>> a.n\n 5\n ",
"language": "en",
"n_whitespaces": 78,
"n_words": 21,
"vocab_size": 18
} | 4 | Python | 4 | 498015021131af4dbb07eb110e5badaba8250c7b | graycode.py | 196,096 | 2 | 13 | n | https://github.com/sympy/sympy.git | Updated import locations | 18 | 0 | 47,596 | 7 | |
1 | 6 | def test_session_not_accessed(self):
response = self.client.get("/auth_processor_no_attr_access/")
self.assertContains(response, "Session not accessed")
| tests/auth_tests/test_context_processors.py | 45 | django | {
"docstring": "\n The session is not accessed simply by including\n the auth context processor\n ",
"language": "en",
"n_whitespaces": 34,
"n_words": 12,
"vocab_size": 12
} | 9 | Python | 9 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | test_context_processors.py | 201,203 | 3 | 24 | test_session_not_accessed | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 30 | 0 | 49,899 | 9 | |
4 | 10 | def iterencode(iterator, encoding, errors='strict', **kwargs):
encoder = getincrementalencoder(encoding)(errors, **kwargs)
for input in iterator:
output = encoder.encode(input)
if output:
yield output
output = encoder.encode("", True)
if output:
yield output
| python3.10.4/Lib/codecs.py | 100 | XX-Net | {
"docstring": "\n Encoding iterator.\n\n Encodes the input strings from the iterator using an IncrementalEncoder.\n\n errors and kwargs are passed through to the IncrementalEncoder\n constructor.\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 22,
"vocab_size": 20
} | 28 | Python | 20 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | codecs.py | 221,370 | 9 | 60 | iterencode | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 75 | 0 | 56,383 | 10 | |
1 | 9 | def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]:
return self.grouper.indices
| pandas/core/groupby/groupby.py | 41 | pandas | {
"docstring": "\n Dict {group name -> group indices}.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 6,
"vocab_size": 6
} | 7 | Python | 7 | f65417656ba8c59438d832b6e2a431f78d40c21c | groupby.py | 167,771 | 5 | 26 | indices | https://github.com/pandas-dev/pandas.git | TYP: more return annotations in core/ (#47618)
* TYP: more return annotations in core/
* from __future__ import annotations
* more __future__ | 21 | 0 | 40,114 | 7 | |
1 | 15 | def register(model, field_name, mappings):
logger.debug(f'Registering denormalized field {model}.{field_name}')
field = model._meta.get_field(field_name)
rel_model = field.related_model
registry['denormalized_fields'][rel_model].append(
(model, field_name, mappings)
)
@receiver(post... | netbox/netbox/denormalized.py | 97 | @receiver(post_save) | netbox | {
"docstring": "\n Register a denormalized model field to ensure that it is kept up-to-date with the related object.\n\n Args:\n model: The class being updated\n field_name: The name of the field related to the triggering instance\n mappings: Dictionary mapping of local to remote fields\n ... | 20 | Python | 17 | e96620260a6c1b5cf8cff2112d40d061984a7b2c | denormalized.py | 265,475 | 7 | 50 | register | https://github.com/netbox-community/netbox.git | Closes #9903: Implement a mechanism for automatically updating denormalized fields | 44 | 1 | 78,110 | 10 |
1 | 9 | def switch_platform_only():
with patch(
"homeassistant.components.zha.PLATFORMS",
(
Platform.DEVICE_TRACKER,
Platform.SENSOR,
Platform.SELECT,
Platform.SWITCH,
),
):
yield
@pytest.fixture | tests/components/zha/test_switch.py | 61 | @pytest.fixture | core | {
"docstring": "Only setup the switch and required base platforms to speed up tests.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | 14 | Python | 14 | 4bc5d7bfed07c20d6f3438ab91c734a620505a33 | test_switch.py | 313,987 | 11 | 32 | switch_platform_only | https://github.com/home-assistant/core.git | Speed up zha tests (#73627) | 94 | 1 | 112,598 | 11 |
3 | 9 | def report_start(self, out, test, example):
if self._verbose:
if example.want:
out('Trying:\n' + _indent(example.source) +
'Expecting:\n' + _indent(example.want))
else:
out('Trying:\n' + _indent(example.source) +
... | python3.10.4/Lib/doctest.py | 104 | XX-Net | {
"docstring": "\n Report that the test runner is about to process the given\n example. (Only displays a message if verbose=True)\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 18,
"vocab_size": 17
} | 23 | Python | 16 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | doctest.py | 223,420 | 8 | 57 | report_start | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 127 | 0 | 56,893 | 17 | |
1 | 9 | def test_cached_file_client(get_loader, minion_opts):
with patch("salt.channel.client.ReqChannel.factory", Mock()):
loader_a = SaltCacheLoader(minion_opts)
loader_b = SaltCacheLoader(minion_opts)
assert loader_a._file_client is loader_b._file_client
| tests/pytests/unit/utils/jinja/test_salt_cache_loader.py | 67 | salt | {
"docstring": "\n Multiple instantiations of SaltCacheLoader use the cached file client\n ",
"language": "en",
"n_whitespaces": 16,
"n_words": 9,
"vocab_size": 9
} | 16 | Python | 14 | 56045b0ee4c11b395895cb0a11279dfea8c2242f | test_salt_cache_loader.py | 215,577 | 5 | 38 | test_cached_file_client | https://github.com/saltstack/salt.git | Clean up salt.transport.(client,server) references | 39 | 0 | 54,037 | 11 | |
1 | 8 | def get_css_variables(self) -> dict[str, str]:
variables = self.design.generate(self.dark)
return variables
| src/textual/app.py | 44 | textual | {
"docstring": "Get a mapping of variables used to pre-populate CSS.\n\n Returns:\n dict[str, str]: A mapping of variable name to value.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 19,
"vocab_size": 16
} | 10 | Python | 9 | b115db9d8d4f1c9ab20a3d3bef5d5a729ea8b57a | app.py | 182,785 | 8 | 27 | get_css_variables | https://github.com/Textualize/textual.git | docstring | 31 | 0 | 43,965 | 9 | |
1 | 26 | def test_multi_sso_redirect_to_cas(self) -> None:
channel = self.make_request(
"GET",
"/_synapse/client/pick_idp?redirectUrl="
+ urllib.parse.quote_plus(TEST_CLIENT_REDIRECT_URL)
+ "&idp=cas",
shorthand=False,
)
self.assertEqu... | tests/rest/client/test_login.py | 239 | synapse | {
"docstring": "If CAS is chosen, should redirect to the CAS server",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 86 | Python | 66 | 64c73c6ac88a740ee480a0ad1f9afc8596bccfa4 | test_login.py | 246,600 | 20 | 143 | test_multi_sso_redirect_to_cas | https://github.com/matrix-org/synapse.git | Add type hints to `tests/rest/client` (#12066) | 260 | 0 | 71,290 | 13 | |
5 | 7 | def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
if session_hooks is None or session_hooks.get("response") == []:
return request_hooks
if request_hooks is None or request_hooks.get("response") == []:
return session_hooks
return merge_setting(request_hooks, sessio... | pipenv/patched/pip/_vendor/requests/sessions.py | 90 | pipenv | {
"docstring": "Properly merges both requests and session hooks.\n\n This is necessary because when request_hooks == {'response': []}, the\n merge breaks Session hooks entirely.\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 22,
"vocab_size": 22
} | 28 | Python | 17 | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | sessions.py | 22,107 | 6 | 55 | merge_hooks | https://github.com/pypa/pipenv.git | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 54 | 0 | 4,184 | 10 | |
1 | 12 | def _decode(self, pre_chars, features, hidden):
| ppocr/modeling/heads/table_att_head.py | 28 | """
Predict tablecoordinates for each | PaddleOCR | {
"docstring": "\n Predict table label and coordinates for each step",
"language": "en",
"n_whitespaces": 15,
"n_words": 8,
"vocab_size": 8
} | 5 | Python | 5 | ddaa2c2552e19635cd6cdf38619f1f176c358f89 | table_att_head.py | 24,443 | 7 | 60 | _decode | https://github.com/PaddlePaddle/PaddleOCR.git | add SLANet | 12 | 2 | 4,732 | 7 |
3 | 9 | def _full_shape(self) -> Tuple[int]:
sampled_shape = tuple()
for d in self._expected_shape:
if isinstance(d, int):
sampled_shape += (d,)
else:
sampled_shape += (1,)
return sampled_shape
| rllib/models/specs/specs_base.py | 76 | ray | {
"docstring": "Converts the expected shape to a shape by replacing the unknown dimension\n sizes with a value of 1.",
"language": "en",
"n_whitespaces": 24,
"n_words": 18,
"vocab_size": 15
} | 23 | Python | 19 | 3e7c207f02e7368e1245e2cfafd27cb0bf179ff7 | specs_base.py | 128,381 | 10 | 47 | _full_shape | https://github.com/ray-project/ray.git | [RLlib] Introduce TensorSpec data structure for RLModule / Model definitions (#28946)
* added tensor specs
Signed-off-by: Kourosh Hakhamaneshi <kourosh@anyscale.com>
* lint
Signed-off-by: Kourosh Hakhamaneshi <kourosh@anyscale.com>
* 1. Added numpy specs
2. Added spec.sample()
Signed-off-by: Kourosh Ha... | 103 | 0 | 28,689 | 12 | |
2 | 21 | def laplacian_matrix(G, nodelist=None, weight="weight"):
import scipy as sp
import scipy.sparse # call as sp.sparse
if nodelist is None:
nodelist = list(G)
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
n, m = A.shape
# TODO: rm csr_array wrapper w... | networkx/linalg/laplacianmatrix.py | 167 | @not_implemented_for("directed") | networkx | {
"docstring": "Returns the Laplacian matrix of G.\n\n The graph Laplacian is the matrix L = D - A, where\n A is the adjacency matrix and D is the diagonal matrix of node degrees.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph\n\n nodelist : list, optional\n The rows and colu... | 53 | Python | 43 | 8a325d26aa7fdd3a72580c4720fa97f971bbefcb | laplacianmatrix.py | 177,333 | 9 | 98 | laplacian_matrix | https://github.com/networkx/networkx.git | Use scipy.sparse array datastructure (#6037)
* Use scipy.sparse array datastructure
* Add reminder to rm wrapper when scipy adds creation fns.
* Rm mention of np matrix from code comment.
* Update networkx/algorithms/bipartite/matrix.py
Co-authored-by: Stefan van der Walt <sjvdwalt@gmail.com>
Co-authore... | 87 | 1 | 42,352 | 13 |
5 | 15 | def global_efficiency(G):
n = len(G)
denom = n * (n - 1)
if denom != 0:
lengths = nx.all_pairs_shortest_path_length(G)
g_eff = 0
for source, targets in lengths:
for target, distance in targets.items():
if distance > 0:
g_eff += 1 /... | networkx/algorithms/efficiency_measures.py | 138 | @not_implemented_for("directed") | networkx | {
"docstring": "Returns the average global efficiency of the graph.\n\n The *efficiency* of a pair of nodes in a graph is the multiplicative\n inverse of the shortest path distance between the nodes. The *average\n global efficiency* of a graph is the average efficiency of all pairs of\n nodes [1]_.\n\n ... | 92 | Python | 55 | 435b4622d106d14a3627e162ee163b113bac9854 | efficiency_measures.py | 176,967 | 14 | 76 | global_efficiency | https://github.com/networkx/networkx.git | added examples to efficiency_measures.py (#5643)
* added example on efficiency
* added example on global_efficiency
* added example on local_efficiency
* adjused round up | 227 | 1 | 42,195 | 15 |
1 | 5 | def image(self) -> ImageTk.PhotoImage:
assert self._preview_image_tk is not None
return self._preview_image_tk
| lib/gui/utils/image.py | 35 | faceswap | {
"docstring": ":class:`PIL.ImageTk.PhotoImage` The preview image for displaying in a tkinter canvas ",
"language": "en",
"n_whitespaces": 10,
"n_words": 10,
"vocab_size": 10
} | 11 | Python | 10 | 2e8ef5e3c8f2df0f1cca9b342baa8aaa6f620650 | image.py | 101,978 | 4 | 21 | image | https://github.com/deepfakes/faceswap.git | GUI - Preview updates
- Training preview. Embed preview pop-out window
- Bugfix - convert/extract previews | 32 | 0 | 21,352 | 7 | |
1 | 20 | def test_ddp_sharded_strategy_fit_ckpt_path_downsize_gpus(tmpdir):
model = BoringModel()
trainer = Trainer(strategy="ddp_sharded_spawn", fast_dev_run=True, gpus=2)
trainer.fit(model)
checkpoint_path = os.path.join(tmpdir, "model.pt")
trainer.save_checkpoint(checkpoint_path)
model = Borin... | tests/strategies/test_sharded_strategy.py | 158 | @RunIf(min_gpus=1, skip_windows=True, fairscale=True) | lightning | {
"docstring": "Test to ensure that resuming from checkpoint works when downsizing number of GPUS.",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 13
} | 29 | Python | 20 | 650c710efacd633fa283955145342bb64063c883 | test_sharded_strategy.py | 241,585 | 9 | 82 | test_ddp_sharded_strategy_fit_ckpt_path_downsize_gpus | https://github.com/Lightning-AI/lightning.git | Rename training plugin test files & names to strategy (#11303) | 55 | 1 | 69,610 | 10 |
1 | 4 | def test_cancel_logcontexts(self):
complete_lookup: "Deferred[None]" = Deferred()
| tests/util/caches/test_descriptors.py | 27 | synapse | {
"docstring": "Test that cancellation does not break logcontexts.\n\n * The `CancelledError` must be raised with the correct logcontext.\n * The inner lookup must not resume with a finished logcontext.\n * The inner lookup must not restore a finished logcontext when done.\n ",
"language... | 6 | Python | 6 | 2fcf4b3f6cd2a0be6597622664636d2219957c2a | test_descriptors.py | 247,588 | 16 | 81 | test_cancel_logcontexts | https://github.com/matrix-org/synapse.git | Add cancellation support to `@cached` and `@cachedList` decorators (#12183)
These decorators mostly support cancellation already. Add cancellation
tests and fix use of finished logging contexts by delaying cancellation,
as suggested by @erikjohnston.
Signed-off-by: Sean Quah <seanq@element.io> | 20 | 0 | 71,762 | 8 | |
1 | 9 | def test_supports_transactions(self):
with mock.patch(
"django.db.connection.features._mysql_storage_engine", "InnoDB"
):
self.assertTrue(connection.features.supports_transactions)
del connection.features.supports_transactions
with mock.patch(
... | tests/backends/mysql/test_features.py | 105 | django | {
"docstring": "\n All storage engines except MyISAM support transactions.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | 18 | Python | 12 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | test_features.py | 201,697 | 11 | 58 | test_supports_transactions | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 111 | 0 | 49,980 | 11 | |
2 | 16 | def _apply_mask(cls, y_true, y_pred, mask_channel, mask_prop=1.0):
if mask_channel == -1:
logger.debug("No mask to apply")
return y_true[..., :3], y_pred[..., :3]
logger.debug("Applying mask from channel %s", mask_channel)
mask = K.tile(K.expand_dims(y_true[...... | lib/model/losses_plaid.py | 187 | faceswap | {
"docstring": " Apply the mask to the input y_true and y_pred. If a mask is not required then\n return the unmasked inputs.\n\n Parameters\n ----------\n y_true: tensor or variable\n The ground truth value\n y_pred: tensor or variable\n The predicted value\n ... | 61 | Python | 42 | 94c3dcff7ebd02a5a5758f33a3eb2bfc66282117 | losses_plaid.py | 100,868 | 11 | 127 | _apply_mask | https://github.com/deepfakes/faceswap.git | Training updates
- Add multiple selected loss functions
- Unlock loss as a model configuration
- Phaze-A remove encoder scaling max xap | 146 | 0 | 20,319 | 12 | |
11 | 39 | def wasLastResponseDelayed():
# 99.9999999997440% of all non time-based SQL injection affected
# response times should be inside +-7*stdev([normal response times])
# Math reference: http://www.answers.com/topic/standard-deviation
deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, []))
... | lib/core/common.py | 327 | sqlmap | {
"docstring": "\n Returns True if the last web request resulted in a time-delay\n ",
"language": "en",
"n_whitespaces": 18,
"n_words": 11,
"vocab_size": 11
} | 153 | Python | 110 | df4293473d2fb6e887e31522cab5aff95e201581 | common.py | 123,465 | 23 | 200 | wasLastResponseDelayed | https://github.com/sqlmapproject/sqlmap.git | Fixing DeprecationWarning (logger.warn) | 360 | 0 | 27,379 | 18 | |
2 | 20 | def generate_navigator(os=None, navigator=None, platform=None, device_type=None):
if platform is not None:
os = platform
warn(
"The `platform` option is deprecated." " Use `os` option instead.",
stacklevel=3,
)
device_type, os_id, navigator_id = pick_config_... | build/pyinstaller/user_agent/base.py | 321 | OpenBBTerminal | {
"docstring": "\n Generates web navigator's config\n\n :param os: limit list of oses for generation\n :type os: string or list/tuple or None\n :param navigator: limit list of browser engines for generation\n :type navigator: string or list/tuple or None\n :param device_type: limit possible oses by ... | 102 | Python | 79 | ab4de1dd70fba866930150e440a03e461a6ca6a8 | base.py | 283,199 | 31 | 190 | generate_navigator | https://github.com/OpenBB-finance/OpenBBTerminal.git | Create a packaged app bundle with Pyinstaller (#1525)
* Add dashboard widget assets
* Add ipywidgets and ipyflex to project
* Add currencies dashboard notebook
* Update docs and docstrings
* Add pyinstaller to project deps
* Add pyinstaller artifacts to gitignore
* Fix linter errors in terminal.py
... | 311 | 0 | 84,465 | 11 | |
1 | 3 | def isTechnical(self):
return self.technical
| nuitka/nodes/ModuleNodes.py | 19 | Nuitka | {
"docstring": "Must be present as it's used in CPython library initialization.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 4 | Python | 4 | 3b1c76ce9d79543de81353f358b3108df91078fc | ModuleNodes.py | 178,747 | 2 | 10 | isTechnical | https://github.com/Nuitka/Nuitka.git | Standalone: Exclude more of standard library modules
* This removes tkinter and many modules expected to never
be implicit dependencies.
* The real reduction will be achieved using Python PGO once
it covers bytecode too.
* Don't keep required extension modules as root modules,
instead make them proper early in... | 18 | 0 | 42,811 | 6 | |
8 | 17 | def fes(self, name=None, frame=None):
# what frames are we searching in?
if frame is not None:
if isinstance(frame, int):
frames = [self.frame(frame)]
elif isinstance(frame, str):
frames = self.frames(frame)
else:
... | nltk/corpus/reader/framenet.py | 169 | nltk | {
"docstring": "\n Lists frame element objects. If 'name' is provided, this is treated as\n a case-insensitive regular expression to filter by frame name.\n (Case-insensitivity is because casing of frame element names is not always\n consistent across frames.) Specify 'frame' to filter by ... | 57 | Python | 40 | 8a4cf5d94eb94b6427c5d1d7907ba07b119932c5 | framenet.py | 42,538 | 16 | 108 | fes | https://github.com/nltk/nltk.git | Docstring tests (#3050)
* fixed pytests
* fixed more pytests
* fixed more pytest and changed multiline pytest issues fixes for snowball.py and causal.py
* fixed pytests (mainly multiline or rounding issues)
* fixed treebank pytests, removed test for return_string=True (deprecated)
* fixed destructive.py... | 232 | 0 | 7,600 | 13 | |
1 | 41 | def test_mark_task_instance_state(test_app):
from airflow.models import DAG, DagBag, TaskInstance
from airflow.operators.dummy import DummyOperator
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timezone import datetime
from airflow... | tests/www/views/test_views.py | 285 | airflow | {
"docstring": "\n Test that _mark_task_instance_state() does all three things:\n - Marks the given TaskInstance as SUCCESS;\n - Clears downstream TaskInstances in FAILED/UPSTREAM_FAILED state;\n - Set DagRun to QUEUED.\n ",
"language": "en",
"n_whitespaces": 42,
"n_words": 26,
"vocab_size": 24... | 78 | Python | 57 | 2b4bf7fe67fc656ceb7bdaad36453b7a5b83ef04 | test_views.py | 44,001 | 56 | 437 | test_mark_task_instance_state | https://github.com/apache/airflow.git | Use `DagRun.run_id` instead of `execution_date` when updating state of TIs(UI & REST API) (#18724)
We can now use run_id as well as execution_date to update states
of task instances
Co-authored-by: Tzu-ping Chung <uranusjr@gmail.com>
Co-authored-by: Ash Berlin-Taylor <ash_github@firemirror.com> | 197 | 0 | 8,118 | 12 | |
1 | 16 | def test_delete_view_uses_get_deleted_objects(self):
book = Book.objects.create(name="Test Book")
response = self.client.get(
reverse("admin2:admin_views_book_delete", args=(book.pk,))
)
# BookAdmin.get_deleted_objects() returns custom text.
self.assertContai... | tests/admin_views/tests.py | 98 | @override_settings(ROOT_URLCONF="admin_views.urls") | django | {
"docstring": "The delete view uses ModelAdmin.get_deleted_objects().",
"language": "en",
"n_whitespaces": 4,
"n_words": 5,
"vocab_size": 5
} | 22 | Python | 21 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,727 | 6 | 48 | test_delete_view_uses_get_deleted_objects | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 74 | 1 | 52,072 | 13 |
1 | 5 | def _apply_from_right_to(self, op, **options):
return dispatch_method(self, '_apply_from_right_to', op, **options)
| sympy/physics/quantum/state.py | 37 | sympy | {
"docstring": "Apply an Operator to this Ket as Operator*Ket\n\n This method will dispatch to methods having the format::\n\n ``def _apply_from_right_to_OperatorName(op, **options):``\n\n Subclasses should define these methods (one for each OperatorName) to\n teach the Ket how to impl... | 9 | Python | 8 | 00ed353dda66aa068dd43d44018f6a394d1fb0a1 | state.py | 200,169 | 2 | 23 | _apply_from_right_to | https://github.com/sympy/sympy.git | Fix the Ket*Op->Op*Ket bug | 23 | 0 | 49,559 | 8 | |
1 | 10 | def unrank_gray(self, rank, superset):
graycode_bitlist = GrayCode.unrank(len(superset), rank)
return Subset.subset_from_bitlist(superset, graycode_bitlist)
| sympy/combinatorics/subsets.py | 50 | sympy | {
"docstring": "\n Gets the Gray code ordered subset of the specified rank.\n\n Examples\n ========\n\n >>> from sympy.combinatorics import Subset\n >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset\n ['a', 'b']\n >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset\n ... | 11 | Python | 11 | 498015021131af4dbb07eb110e5badaba8250c7b | subsets.py | 196,203 | 3 | 32 | unrank_gray | https://github.com/sympy/sympy.git | Updated import locations | 32 | 0 | 47,703 | 10 | |
6 | 12 | def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
if not isinstance(ids, (list, tuple)):
return self._convert_id_to_token(ids)
tokens = [self._convert_id_to_token(_id) for _id in ids]
if skip_special_tokens:
return [
token fo... | paddlenlp/transformers/prophetnet/tokenizer.py | 100 | PaddleNLP | {
"docstring": "\r\n Converts a single index or a sequence of indices to a token or\r\n a sequence of tokens, using the vocabulary and added tokens.\r\n\r\n Args:\r\n ids (int or List[int]):\r\n The token id (or token ids) to be converted to token(s).\r\n skip... | 35 | Python | 23 | 487162262196bead8d9b4c2306f313b8f64edf9b | tokenizer.py | 322,456 | 10 | 66 | convert_ids_to_tokens | https://github.com/PaddlePaddle/PaddleNLP.git | Add model Prohetnet (#1698)
* add Prohetnet model
* update prohetnet
* update format
* pre commit
* add prophetnet example
* update tokenizer.py,run_train.sh,train_prophetnet.py
* remove evaluate/gigaword/__init__.py
Co-authored-by: smallv0221 <33639025+smallv0221@users.noreply.github.com> | 133 | 0 | 118,173 | 11 | |
2 | 9 | def vocabulary_size(self):
if tf.executing_eagerly():
return (
int(self.lookup_table.size().numpy())
+ self._token_start_index()
)
else:
return self.lookup_table.size() + self._token_start_index()
| keras/layers/preprocessing/index_lookup.py | 90 | keras | {
"docstring": "Gets the current size of the layer's vocabulary.\n\n Returns:\n The integer size of the vocabulary, including optional mask and oov indices.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 21,
"vocab_size": 17
} | 15 | Python | 12 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | index_lookup.py | 273,174 | 8 | 52 | vocabulary_size | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 99 | 0 | 81,097 | 16 | |
1 | 7 | def get_host_target_type_map() -> t.Dict[t.Type[HostConfig], t.Type[TargetFilter]]:
return get_type_map(TargetFilter, HostConfig)
| test/lib/ansible_test/_internal/commands/integration/filters.py | 48 | ansible | {
"docstring": "Create and return a mapping of HostConfig types to TargetFilter types.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 8 | Python | 8 | 3eb0485dd92c88cc92152d3656d94492db44b183 | filters.py | 267,900 | 3 | 31 | get_host_target_type_map | https://github.com/ansible/ansible.git | 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... | 14 | 0 | 79,176 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.