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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 37 | def test_gpu_stats_monitor_no_queries(tmpdir):
model = BoringModel()
with pytest.deprecated_call(match="GPUStatsMonitor` callback was deprecated in v1.5"):
gpu_stats = GPUStatsMonitor(
memory_utilization=False,
gpu_utilization=False,
intra_step_time=True,
... | tests/callbacks/test_gpu_stats_monitor.py | 283 | @pytest.mark.skipif(torch.cuda.is_available(), reason="test requires CPU machine") | lightning | {
"docstring": "Test GPU logger doesn't fail if no \"nvidia-smi\" queries are to be performed.",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 13
} | 59 | Python | 49 | 4710a8128b52179be2b1fa46b17677eda7b849ea | test_gpu_stats_monitor.py | 241,709 | 26 | 159 | test_gpu_stats_monitor_no_queries | https://github.com/Lightning-AI/lightning.git | Update test_gpu_stats_monitor.py to use `devices` instead of `gpus` or `ipus` (#11340) | 224 | 1 | 69,662 | 12 |
6 | 33 | def _unpack_observation(self, obs_batch):
unpacked = _unpack_obs(
np.array(obs_batch, dtype=np.float32),
self.observation_space.original_space,
tensorlib=np,
)
if isinstance(unpacked[0], dict):
assert "obs" in unpacked[0]
unp... | rllib/agents/qmix/qmix_policy.py | 338 | ray | {
"docstring": "Unpacks the observation, action mask, and state (if present)\n from agent grouping.\n\n Returns:\n obs (np.ndarray): obs tensor of shape [B, n_agents, obs_size]\n mask (np.ndarray): action mask, if any\n state (np.ndarray or None): state tensor of shape [... | 75 | Python | 50 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | qmix_policy.py | 133,808 | 27 | 223 | _unpack_observation | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 332 | 0 | 30,117 | 15 | |
3 | 15 | def test_create_accessible(self):
response, page = self._create_page(Page.objects.get(pk=2))
self.assertIsNotNone(page.url)
self.assertTrue(
any(
"View live" in message.message and page.url in message.message
for message in response.context["m... | wagtail/admin/tests/pages/test_edit_page.py | 105 | wagtail | {
"docstring": "\n Create a page under the site root, check the flash message has a valid\n \"View live\" button.\n ",
"language": "en",
"n_whitespaces": 39,
"n_words": 17,
"vocab_size": 15
} | 23 | Python | 19 | d10f15e55806c6944827d801cd9c2d53f5da4186 | test_edit_page.py | 71,575 | 9 | 63 | test_create_accessible | https://github.com/wagtail/wagtail.git | Reformat with black | 110 | 0 | 15,690 | 12 | |
2 | 12 | def q_sample(self, x_start, t, noise=None):
if noise is None:
# noise = th.randn_like(x_start)
noise = paddle.randn(x_start.shape, x_start.dtype)
assert noise.shape == x_start.shape
return (_extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_star... | modules/image/text_to_image/disco_diffusion_cnclip_vitb16/reverse_diffusion/model/gaussian_diffusion.py | 109 | PaddleHub | {
"docstring": "\n Diffuse the data for a given number of diffusion steps.\n\n In other words, sample from q(x_t | x_0).\n\n :param x_start: the initial data batch.\n :param t: the number of diffusion steps (minus 1). Here, 0 means one step.\n :param noise: if specified, the split-o... | 33 | Python | 26 | f4d6e64cdc132ae868699a0ba442f4ab1d304a14 | gaussian_diffusion.py | 49,786 | 6 | 73 | q_sample | https://github.com/PaddlePaddle/PaddleHub.git | add disco_diffusion_cnclip_vitb16 module | 98 | 0 | 9,909 | 11 | |
7 | 19 | def parse_query_string(query_string, operator=None, zero_terms=MATCH_NONE):
filters, query_string = separate_filters_from_query(query_string)
is_phrase = False
tokens = []
for part in query_string.split('"'):
part = part.strip()
if part:
if is_phrase:
t... | wagtail/search/utils.py | 193 | wagtail | {
"docstring": "\n This takes a query string typed in by a user and extracts the following:\n\n - Quoted terms (for phrase search)\n - Filters\n\n For example, the following query:\n\n `hello \"this is a phrase\" live:true` would be parsed into:\n\n filters: {'live': 'true'}\n tokens: And([Pl... | 57 | Python | 38 | d10f15e55806c6944827d801cd9c2d53f5da4186 | utils.py | 75,890 | 22 | 115 | parse_query_string | https://github.com/wagtail/wagtail.git | Reformat with black | 231 | 0 | 16,438 | 19 | |
1 | 20 | def test_memory_usage_completed_flows(tctx):
gc.collect()
flow_count = flows_tracked()
server = Placeholder(Server)
assert (
Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)
>> DataReceived(tctx.client, b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\... | test/mitmproxy/proxy/layers/http/test_http.py | 179 | mitmproxy | {
"docstring": "Make sure that flows are not kept in memory after they are completed.",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 12
} | 48 | Python | 32 | 035b3bf37d9785fef45e81eb9c0c47fc53ab24d2 | test_http.py | 251,123 | 15 | 105 | test_memory_usage_completed_flows | https://github.com/mitmproxy/mitmproxy.git | drop HTTP streams that are completed, fix #4456 | 149 | 0 | 73,601 | 17 | |
1 | 3 | def test_bad_csrf_cookie_length(self):
self._check_bad_or_missing_cookie(16 * "a", "CSRF cookie has incorrect length.")
| tests/csrf_tests/tests.py | 32 | django | {
"docstring": "\n If the CSRF cookie has an incorrect length in a POST request, the\n middleware rejects the incoming request.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 16
} | 10 | Python | 10 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 202,430 | 2 | 16 | test_bad_csrf_cookie_length | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 24 | 0 | 50,129 | 9 | |
1 | 19 | def test_dynamic_path(self):
doc = Document.objects.create(
title="does not matter",
created=timezone.make_aware(datetime.datetime(2020, 6, 25, 7, 36, 51, 153)),
mime_type="application/pdf",
pk=2,
checksum="2",
storage_path=Storage... | src/documents/tests/test_file_handling.py | 127 | paperless-ngx | {
"docstring": "\n GIVEN:\n - A document with a defined storage path\n WHEN:\n - the filename is generated for the document\n THEN:\n - the generated filename uses the defined storage path for the document\n ",
"language": "en",
"n_whitespaces": 93,
"... | 22 | Python | 22 | 69ef26dab04d51e7e102dcb33cd98ddc6ad975fd | test_file_handling.py | 319,622 | 10 | 81 | test_dynamic_path | https://github.com/paperless-ngx/paperless-ngx.git | Feature: Dynamic document storage pathes (#916)
* Added devcontainer
* Add feature storage pathes
* Exclude tests and add versioning
* Check escaping
* Check escaping
* Check quoting
* Echo
* Escape
* Escape :
* Double escape \
* Escaping
* Remove if
* Escape colon
* Missing \
... | 116 | 0 | 116,979 | 13 | |
4 | 19 | def appell_poly(n, seq, v, f, K, x=None, polys=False):
if n < 0:
raise ValueError(
"Cannot generate Appell sequence polynomial of order %s" % n)
poly = DMP(dup_appell(int(n), seq, v, f, K), K)
if x is not None:
poly = Poly.new(poly, x)
else:
poly = PurePoly.new(p... | sympy/polys/appellseqs.py | 151 | @public | sympy | {
"docstring": "Generates the nth polynomial in `x` of the Appell sequence with\n parameters `seq`, `v` and `f`.\n\n Parameters\n ==========\n\n n : int\n Order of the polynomial.\n seq : iterable\n v : Expr\n f : callable\n K : Domain\n Domain in which to perform computations an... | 53 | Python | 43 | e875bdb804b0285e4a9bd8de0158436e792c03cb | appellseqs.py | 199,617 | 10 | 97 | appell_poly | https://github.com/sympy/sympy.git | Initial definition of Appell sequences | 102 | 1 | 49,295 | 14 |
2 | 8 | def config_for_enable_caching_device(rnn_cell):
default_enable_caching_device = (
tf.compat.v1.executing_eagerly_outside_functions()
)
if rnn_cell._enable_caching_device != default_enable_caching_device:
return {"enable_caching_device": rnn_cell._enable_caching_device}
return {}
| keras/layers/rnn/rnn_utils.py | 64 | keras | {
"docstring": "Return the dict config for RNN cell wrt to enable_caching_device field.\n\n Since enable_caching_device is a internal implementation detail for speed up\n the RNN variable read when running on the multi remote worker setting, we\n don't want this config to be serialized constantly in the JSON... | 16 | Python | 15 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | rnn_utils.py | 274,086 | 7 | 37 | config_for_enable_caching_device | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 45 | 0 | 81,176 | 11 | |
1 | 2 | def size(self):
return self["size"]
| packages/python/plotly/plotly/graph_objs/bar/marker/_pattern.py | 22 | plotly.py | {
"docstring": "\n Sets the size of unit squares of the pattern fill in pixels,\n which corresponds to the interval of repetition of the pattern.\n\n The 'size' property is a number and may be specified as:\n - An int or float in the interval [0, inf]\n - A tuple, list, or one-d... | 4 | Python | 4 | 43e3a4011080911901176aab919c0ecf5046ddd3 | _pattern.py | 228,787 | 2 | 11 | size | https://github.com/plotly/plotly.py.git | switch to black .22 | 18 | 0 | 60,460 | 7 | |
4 | 18 | def _cmp_op(self, other, op_name):
lhs_dtype_class = self._get_dtype_cmp_class(self._dtype)
rhs_dtype_class = self._get_dtype_cmp_class(other._dtype)
res_dtype = get_dtype(bool)
# In HDK comparison with NULL always results in NULL,
# but in pandas it is True for 'ne' com... | modin/experimental/core/execution/native/implementations/hdk_on_native/expr.py | 192 | modin | {
"docstring": "\n Build a comparison expression.\n\n Parameters\n ----------\n other : BaseExpr\n A value to compare with.\n op_name : str\n The comparison operation name.\n\n Returns\n -------\n BaseExpr\n The resulting compari... | 99 | Python | 70 | e5b1888cd932909e49194d58035da34b210b91c4 | expr.py | 154,585 | 16 | 106 | _cmp_op | https://github.com/modin-project/modin.git | FEAT-#4946: Replace OmniSci with HDK (#4947)
Co-authored-by: Iaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: Andrey Pavlenko <andrey.a.pavlenko@gmail.com> | 310 | 0 | 36,095 | 15 | |
1 | 8 | def mock_update_empty_fixture(mock_update):
mock_update.return_value = None
yield mock_update
@pytest.mark.parametrize(
"data,options",
[(MOCK_CONFIG, {})],
)
@pytest.mark.usefixtures("mock_update", "mock_config") | tests/components/google_travel_time/test_sensor.py | 75 | @pytest.mark.parametrize(
"data,options",
[(MOCK_CONFIG, {})],
)
@pytest.mark.usefixtures("mock_update", "mock_config") | core | {
"docstring": "Mock an update to the sensor with an empty response.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 14 | Python | 14 | beb30a1ff199596163c655e8ae745a0f1649b78a | test_sensor.py | 292,225 | 3 | 13 | mock_update_empty_fixture | https://github.com/home-assistant/core.git | Add google_travel_time sensor tests (#66568)
Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io> | 26 | 1 | 91,325 | 9 |
1 | 3 | async def count_real_users(self) -> int:
| synapse/storage/databases/main/registration.py | 17 | synapse | {
"docstring": "Counts all users without a special user_type registered on the homeserver.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 5 | Python | 5 | 1783156dbcf4164692e66275d1c29857c434995b | registration.py | 248,017 | 4 | 22 | count_real_users | https://github.com/matrix-org/synapse.git | Add some type hints to datastore (#12423)
* Add some type hints to datastore
* newsfile
* change `Collection` to `List`
* refactor return type of `select_users_txn`
* correct type hint in `stream.py`
* Remove `Optional` in `select_users_txn`
* remove not needed return type in `__init__`
* Revert c... | 12 | 0 | 72,048 | 6 | |
15 | 34 | def sign(e, x):
if not isinstance(e, Basic):
raise TypeError("e should be an instance of Basic")
if e.is_positive:
return 1
elif e.is_negative:
return -1
elif e.is_zero:
return 0
elif not e.has(x):
from sympy.simplify import logcombine
e = logco... | sympy/series/gruntz.py | 339 | @debug
@timeit
@cacheit | sympy | {
"docstring": "\n Returns a sign of an expression e(x) for x->oo.\n\n ::\n\n e > 0 for x sufficiently large ... 1\n e == 0 for x sufficiently large ... 0\n e < 0 for x sufficiently large ... -1\n\n The result of this function is currently undefined if e changes sign\n arbitrarily... | 121 | Python | 73 | f757f3daae6e11ea0cfb7dadc133274d8d74315f | gruntz.py | 196,818 | 35 | 209 | sign | https://github.com/sympy/sympy.git | Reordered imports 2 | 330 | 1 | 48,196 | 13 |
4 | 24 | def statistics(self, refresh=False, approximate=False):
# Prepare array with arguments for capi function
smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double()
stats_args = [
self._ptr,
c_int(approximate),
byref(smin),
by... | django/contrib/gis/gdal/raster/band.py | 241 | django | {
"docstring": "\n Compute statistics on the pixel values of this band.\n\n The return value is a tuple with the following structure:\n (minimum, maximum, mean, standard deviation).\n\n If approximate=True, the statistics may be computed based on overviews\n or a subset of image til... | 98 | Python | 77 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | band.py | 204,002 | 25 | 156 | statistics | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 369 | 0 | 50,606 | 12 | |
6 | 23 | def logical_or(self, other, context=None):
if context is None:
context = getcontext()
other = _convert_other(other, raiseit=True)
if not self._islogical() or not other._islogical():
return context._raise_error(InvalidOperation)
# fill to context.prec
... | python3.10.4/Lib/_pydecimal.py | 197 | XX-Net | {
"docstring": "Applies an 'or' operation between self and other's digits.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | 54 | Python | 45 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | _pydecimal.py | 219,615 | 9 | 122 | logical_or | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 139 | 0 | 55,652 | 14 | |
1 | 21 | def test_localize_pk_shortcut(self):
holder = Holder.objects.create(pk=123456789, dummy=42)
inner = Inner.objects.create(pk=987654321, holder=holder, dummy=42, readonly="")
response = self.client.get(
reverse("admin:admin_inlines_holder_change", args=(holder.id,))
)
... | tests/admin_inlines/tests.py | 153 | django | {
"docstring": "\n The \"View on Site\" link is correct for locales that use thousand\n separators.\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 13,
"vocab_size": 13
} | 28 | Python | 24 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,245 | 11 | 97 | test_localize_pk_shortcut | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 117 | 0 | 51,910 | 13 | |
1 | 5 | def convert_field_to_list_or_connection(field, registry=None):
model = field.related_model
| netbox/netbox/graphql/__init__.py | 26 | netbox | {
"docstring": "\n From graphene_django.converter.py we need to monkey-patch this to return\n our ObjectListField with filtering support instead of DjangoListField\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 17,
"vocab_size": 16
} | 6 | Python | 6 | 99cf1b16718ca8bc037f546c41a9258bcc89b495 | __init__.py | 265,857 | 4 | 22 | convert_field_to_list_or_connection | https://github.com/netbox-community/netbox.git | 8245 add graphql filtering at all levels (#10618)
* 8245 monkey-patch graphene-django to support filtering at all levels
* 8245 fix tests
* 8245 fix tests | 12 | 0 | 78,216 | 7 | |
3 | 23 | def integration_reduction(facets, index, a, b, expr, dims, degree):
expr = _sympify(expr)
if expr.is_zero:
return expr
value = S.Zero
x0 = facets[index].points[0]
m = len(facets)
gens = (x, y)
inner_product = diff(expr, gens[0]) * x0[0] + diff(expr, gens[1]) * x0[1]
if in... | sympy/integrals/intpoly.py | 208 | sympy | {
"docstring": "Helper method for main_integrate. Returns the value of the input\n expression evaluated over the polytope facet referenced by a given index.\n\n Parameters\n ===========\n\n facets :\n List of facets of the polytope.\n index :\n Index referencing the facet to integrate the... | 68 | Python | 43 | 498015021131af4dbb07eb110e5badaba8250c7b | intpoly.py | 196,330 | 14 | 145 | integration_reduction | https://github.com/sympy/sympy.git | Updated import locations | 153 | 0 | 47,830 | 11 | |
9 | 32 | def forward_test(self, aug_batch_imgs, aug_batch_data_samples, **kwargs):
num_augs = len(aug_batch_data_samples)
batch_size = len(aug_batch_data_samples[0])
aug_batch_img_metas = []
for aug_index in range(num_augs):
batch_img_metas = []
for batch_index i... | mmdet/models/detectors/base.py | 394 | mmdetection | {
"docstring": "\n Args:\n aug_batch_imgs (List[Tensor]): the outer list indicates test-time\n augmentations, the Tensor should have a shape NxCxHxW.\n We only support batch size = 1 when do the augtest.\n aug_batch_data_samples (List[List[:obj:`GeneralData`]... | 151 | Python | 105 | 9c5b3331ac8edbfa328922fbab45c382380da540 | base.py | 244,367 | 36 | 247 | forward_test | https://github.com/open-mmlab/mmdetection.git | Simplify api of one-stage detector | 710 | 0 | 70,356 | 15 | |
4 | 17 | def _move_model_to_meta(model, loaded_state_dict_keys, start_prefix):
# meta device was added in pt=1.9
require_version_core("torch>=1.9")
# dematerialize param storage for keys that are going to be replaced by state_dict, by
# putting those on the meta device
for k in loaded_state_dict_keys:... | src/transformers/modeling_utils.py | 152 | transformers | {
"docstring": "\n Moves `loaded_state_dict_keys` in model to meta device which frees up the memory taken by those params.\n\n `start_prefix` is used for models which insert their name into model keys, e.g. `bert` in\n `bert.pooler.dense.weight`\n\n ",
"language": "en",
"n_whitespaces": 45,
"n_words... | 114 | Python | 82 | 5da33f872913255d64717efe745a053975bbc28e | modeling_utils.py | 37,154 | 11 | 90 | _move_model_to_meta | https://github.com/huggingface/transformers.git | [modeling utils] revamp `from_pretrained(..., low_cpu_mem_usage=True)` + tests (#16657)
* add low_cpu_mem_usage tests
* wip: revamping
* wip
* install /usr/bin/time
* wip
* cleanup
* cleanup
* cleanup
* cleanup
* cleanup
* fix assert
* put the wrapper back
* cleanup; switch to bert-... | 268 | 0 | 6,745 | 17 | |
7 | 31 | def _get_source_sum(source_hash, file_path, saltenv):
ret = dict()
schemes = ("salt", "http", "https", "ftp", "swift", "s3", "file")
invalid_hash_msg = (
"Source hash '{}' format is invalid. It must be in "
"the format <hash type>=<hash>".format(source_hash)
)
source_hash = str(... | salt/modules/win_pkg.py | 350 | salt | {
"docstring": "\n Extract the hash sum, whether it is in a remote hash file, or just a string.\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 16,
"vocab_size": 14
} | 136 | Python | 93 | f2a783643de61cac1ff3288b40241e5ce6e1ddc8 | win_pkg.py | 215,965 | 31 | 201 | _get_source_sum | https://github.com/saltstack/salt.git | Update to latest ``pyupgrade`` hook. Stop skipping it on CI.
Signed-off-by: Pedro Algarvio <palgarvio@vmware.com> | 379 | 0 | 54,287 | 16 | |
4 | 24 | def generate_rgbas_array(self, color, opacity):
colors = list(tuplify(color))
opacities = list(tuplify(opacity))
rgbas = np.array(
[color_to_rgba(c, o) for c, o in zip(*make_even(colors, opacities))],
)
sheen_factor = self.get_sheen_factor()
if sheen... | manim/mobject/types/vectorized_mobject.py | 193 | manim | {
"docstring": "\n First arg can be either a color, or a tuple/list of colors.\n Likewise, opacity can either be a float, or a tuple of floats.\n If self.sheen_factor is not zero, and only\n one color was passed in, a second slightly light color\n will automatically be added for the... | 51 | Python | 42 | d8dc0b462d973f0c1ddd62e557d2da89e45f6265 | vectorized_mobject.py | 189,410 | 13 | 125 | generate_rgbas_array | https://github.com/ManimCommunity/manim.git | Cleanup `simple_functions.py` (#2437)
* Remove fdiv
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* actually remove fdiv
* Use lru cache and scipy's func
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci... | 162 | 0 | 46,046 | 15 | |
1 | 2 | def getExtraIncludeDirectories(self):
# Virtual method, pylint: disable=no-self-use
return None
| nuitka/plugins/PluginBase.py | 17 | Nuitka | {
"docstring": "Decide which extra directories to use for C includes in compilation.\n\n Returns:\n List of directories or None by default\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 19,
"vocab_size": 18
} | 9 | Python | 9 | 5251e9561d7d1527fb99068e7b3e33592394cc16 | PluginBase.py | 178,812 | 2 | 8 | getExtraIncludeDirectories | https://github.com/Nuitka/Nuitka.git | Plugins: Add interface for adding include directories for C | 30 | 0 | 42,830 | 6 | |
1 | 6 | def list_datasets() -> List[str]:
return sorted(_get_dataset_configs().keys())
| ludwig/datasets/__init__.py | 38 | ludwig | {
"docstring": "Returns a list of the names of all available datasets.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 6 | Python | 6 | e4fc06f986e03919d9aef3ab55c05fee5a6b9d3a | __init__.py | 8,063 | 3 | 21 | list_datasets | https://github.com/ludwig-ai/ludwig.git | Config-first Datasets API (ludwig.datasets refactor) (#2479)
* Adds README and stub for reading dataset configs.
* Adds __init__.py for configs, moves circular import into function scope in ludwig/datasets/__init__.py
* Print config files in datasets folder.
* First pass at automatic archive extraction.
* ... | 12 | 0 | 1,318 | 11 | |
1 | 11 | def test_cable_cannot_terminate_to_an_existing_connection(self):
# Try to create a cable with the same interface terminations
cable = Cable(a_terminations=[self.interface2], b_terminations=[self.interface1])
with self.assertRaises(ValidationError):
cable.clean()
| netbox/dcim/tests/test_models.py | 68 | netbox | {
"docstring": "\n Either side of a cable cannot be terminated when that side already has a connection\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 15,
"vocab_size": 13
} | 20 | Python | 18 | 3a461d02793e6f9d41c2b1a92647e691de1abaac | test_models.py | 264,887 | 4 | 39 | test_cable_cannot_terminate_to_an_existing_connection | https://github.com/netbox-community/netbox.git | Update Cable instantiations to match new signature | 59 | 0 | 77,898 | 11 | |
5 | 15 | def _get_pyqt_webengine_qt_version() -> Optional[str]:
try:
import importlib.metadata as importlib_metadata # type: ignore[import]
except ImportError:
try:
import importlib_metadata # type: ignore[no-redef]
except ImportError:
log.misc.debug("Neither import... | qutebrowser/utils/version.py | 144 | @dataclasses.dataclass | qutebrowser | {
"docstring": "Get the version of the PyQtWebEngine-Qt package.\n\n With PyQtWebEngine 5.15.3, the QtWebEngine binary got split into its own\n PyQtWebEngine-Qt PyPI package:\n\n https://www.riverbankcomputing.com/pipermail/pyqt/2021-February/043591.html\n https://www.riverbankcomputing.com/pipermail/pyqt... | 45 | Python | 32 | 4094e15bcbe71311685cb8c57abb6bfb4deadbdc | version.py | 320,660 | 30 | 73 | _get_pyqt_webengine_qt_version | https://github.com/qutebrowser/qutebrowser.git | version: Always prefer builtin importlib.metadata
If we have a builtin importlib.metadata (Python 3.8+) and the importlib_metadata
backport installed, we preferred the backport. However, the version.py tests do
the opposite: They only mock the builtin if it is available. This did lead to
failing tests if the backport ... | 151 | 1 | 117,258 | 14 |
3 | 32 | def trustworthiness(X, X_embedded, *, n_neighbors=5, metric="euclidean"):
r
n_samples = X.shape[0]
if n_neighbors >= n_samples / 2:
raise ValueError(
f"n_neighbors ({n_neighbors}) should be less than n_samples / 2"
f" ({n_samples / 2})"
)
dist_X = pairwise_distanc... | sklearn/manifold/_t_sne.py | 352 | scikit-learn | {
"docstring": "Expresses to what extent the local structure is retained.\n\n The trustworthiness is within [0, 1]. It is defined as\n\n .. math::\n\n T(k) = 1 - \\frac{2}{nk (2n - 3k - 1)} \\sum^n_{i=1}\n \\sum_{j \\in \\mathcal{N}_{i}^{k}} \\max(0, (r(i, j) - k))\n\n where for each sample... | 173 | Python | 115 | ade90145c9c660a1a7baf2315185995899b0f356 | _t_sne.py | 259,640 | 84 | 228 | trustworthiness | https://github.com/scikit-learn/scikit-learn.git | FIX Raise error when n_neighbors >= n_samples / 2 in manifold.trustworthiness (#23033)
Co-authored-by: Shao Yang Hong <hongsy2006@gmail.com>
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com> | 322 | 0 | 75,842 | 16 | |
1 | 5 | def writelines(self, seq):
return _compression.BaseStream.writelines(self, seq)
| python3.10.4/Lib/bz2.py | 31 | XX-Net | {
"docstring": "Write a sequence of byte strings to the file.\n\n Returns the number of uncompressed bytes written.\n seq can be any iterable yielding byte strings.\n\n Line separators are not added between the written byte strings.\n ",
"language": "en",
"n_whitespaces": 62,
"n_word... | 6 | Python | 6 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | bz2.py | 221,197 | 2 | 19 | writelines | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 20 | 0 | 56,267 | 8 | |
1 | 3 | def test_generic_errors(self, constructor):
| pandas/tests/indexes/interval/test_constructors.py | 15 | pandas | {
"docstring": "\n override the base class implementation since errors are handled\n differently; checks unnecessary since caught at the Interval level\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 16
} | 3 | Python | 3 | 76923d7b58d8f25329e779a40b87e2b6959f9cea | test_constructors.py | 170,653 | 2 | 9 | test_generic_errors | https://github.com/pandas-dev/pandas.git | issue 48855 enable pylint unnecessary-pass (#49418)
issue 48855 enable unnecessary-pass | 10 | 0 | 40,592 | 6 | |
1 | 6 | def get_actual_gle_dict(name):
return dict(
frappe.db.sql(
,
name,
)
)
| erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py | 33 | erpnext | {
"docstring": "\n\t\tselect account, sum(debit-credit) as diff\n\t\tfrom `tabGL Entry`\n\t\twhere voucher_type = 'Asset Capitalization' and voucher_no = %s\n\t\tgroup by account\n\t\thaving diff != 0\n\t",
"language": "en",
"n_whitespaces": 19,
"n_words": 24,
"vocab_size": 22
} | 9 | Python | 8 | 58d430fe3ee62e93ad8d16a08bb42156a25b7d41 | test_asset_capitalization.py | 69,222 | 13 | 20 | get_actual_gle_dict | https://github.com/frappe/erpnext.git | feat: Asset Capitalization
- manual selection of entry type
- GLE cleanup with smaller functions
- GLE considering periodical inventory
- test cases | 2 | 0 | 14,997 | 10 | |
1 | 1 | def doctor_output_no_config():
return
| tests/conftest.py | 13 | thumbor | {
"docstring": "\nThumbor doctor will analyze your install and verify if everything is working as expected.\n\nVerifying libraries support...\n\n✅ pycurl is installed correctly.\n✅ cairosvg is installed correctly.\n\nVerifying thumbor compiled extensions...\n\n✅ _alpha\n✅ _bounding_box\n✅ _brightness\n✅ _colorize\n✅ ... | 3 | Python | 3 | 0e845259cd3d49b39889ae15df19922af0ef7269 | conftest.py | 191,181 | 38 | 6 | doctor_output_no_config | https://github.com/thumbor/thumbor.git | Remove snapshottest to reduce number of dependencies (#1433)
Having an extra package that can be replaced with something already
included makes packaging easier. For instance, in Debian, one would have
to either be fortunate to find an existing package or go over the
trouble of creating such package and all its dep... | 6 | 0 | 46,464 | 6 | |
5 | 18 | def draw(G, pos=None, ax=None, **kwds):
import matplotlib.pyplot as plt
if ax is None:
cf = plt.gcf()
else:
cf = ax.get_figure()
cf.set_facecolor("w")
if ax is None:
if cf.axes:
ax = cf.gca()
else:
ax = cf.add_axes((0, 0, 1, 1))
if "... | networkx/drawing/nx_pylab.py | 206 | networkx | {
"docstring": "Draw the graph G with Matplotlib.\n\n Draw the graph as a simple representation with no node\n labels or edge labels and using the full Matplotlib figure area\n and no axis labels by default. See draw_networkx() for more\n full-featured drawing that allows title, axis labels etc.\n\n P... | 54 | Python | 39 | 7f3ec2c5906b709733a5c26285032bf24134bcf0 | nx_pylab.py | 177,150 | 18 | 125 | draw | https://github.com/networkx/networkx.git | See matplotlb 3.6rc1 failure (#5937)
* See matplotlb 3.6rc1 failure
* replace use of private class method to allow mpl v3.6 to work.
* ensure ax exists before calling colorbar
* Undo matplotlib pin
Co-authored-by: Dan Schult <dschult@colgate.edu> | 144 | 0 | 42,290 | 14 | |
1 | 11 | def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
import warnings
warnings.warn(
"adjacency_matrix will return a scipy.sparse array instead of a matrix in Networkx 3.0.",
FutureWarning,
stacklevel=2,
)
# TODO: Change to `to_scipy_sparse_array` for network... | networkx/linalg/graphmatrix.py | 81 | networkx | {
"docstring": "Returns adjacency matrix of G.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph\n\n nodelist : list, optional\n The rows and columns are ordered according to the nodes in nodelist.\n If nodelist is None, then the ordering is produced by G.nodes().\n\n dtype :... | 37 | Python | 35 | 5dfd57af2a141a013ae3753e160180b82bec9469 | graphmatrix.py | 176,190 | 8 | 52 | adjacency_matrix | https://github.com/networkx/networkx.git | Use scipy.sparse array datastructure (#5139)
* Step 1: use sparse arrays in nx.to_scipy_sparse_matrix.
Seems like a reasonable place to start.
nx.to_scipy_sparse_matrix is one of the primary interfaces to
scipy.sparse from within NetworkX.
* 1: Use np.outer instead of mult col/row vectors
Fix two instances ... | 76 | 0 | 41,756 | 8 | |
1 | 18 | def test_cancellation_while_holding_read_lock(self):
rwlock = ReadWriteLock()
key = "key"
# 1. A reader takes the lock and blocks.
reader_d, _, _ = self._start_blocking_reader(rwlock, key, "read completed")
# 2. A writer waits for the reader to complete.
writer... | tests/util/test_rwlock.py | 152 | synapse | {
"docstring": "Test cancellation while holding a read lock.\n\n A waiting writer should be given the lock when the reader holding the lock is\n cancelled.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 23,
"vocab_size": 19
} | 76 | Python | 55 | 605d161d7d585847fd1bb98d14d5281daeac8e86 | test_rwlock.py | 247,584 | 12 | 88 | test_cancellation_while_holding_read_lock | https://github.com/matrix-org/synapse.git | Add cancellation support to `ReadWriteLock` (#12120)
Also convert `ReadWriteLock` to use async context managers.
Signed-off-by: Sean Quah <seanq@element.io> | 192 | 0 | 71,759 | 9 | |
1 | 5 | def is_re(obj) -> bool:
return isinstance(obj, Pattern)
| pandas/core/dtypes/inference.py | 26 | pandas | {
"docstring": "\n Check if the object is a regex pattern instance.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n bool\n Whether `obj` is a regex pattern.\n\n Examples\n --------\n >>> is_re(re.compile(\".*\"))\n True\n >>> is_re(\"foo\")\n ... | 7 | Python | 7 | bce995817caf00ab5e82cb4cf1b540f1530cf4ea | inference.py | 172,101 | 21 | 15 | is_re | https://github.com/pandas-dev/pandas.git | Fix some dosctring RT02 error (#50197) | 13 | 0 | 40,755 | 7 | |
12 | 25 | def partial_fit(self, X, y, classes=None, sample_weight=None):
first_time = not hasattr(self, "estimators_")
if first_time:
self._validate_params()
y = self._validate_data(X="no_validation", y=y, multi_output=True)
if y.ndim == 1:
raise ValueError(
... | sklearn/multioutput.py | 332 | scikit-learn | {
"docstring": "Incrementally fit a separate model for each class output.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n y : {array-like, sparse matrix} of shape (n_samples, n_outputs)\n Multi-outpu... | 107 | Python | 77 | d942600e1f1979c431c24f59933a95155789f324 | multioutput.py | 260,558 | 30 | 214 | partial_fit | https://github.com/scikit-learn/scikit-learn.git | MAINT add parameter_constraints for MultiOutputClassifier and MultiOutputRegressor (#23902)
Co-authored-by: jeremiedbb <jeremiedbb@yahoo.fr> | 421 | 0 | 76,339 | 13 | |
1 | 8 | def print_help(self):
help_text = f
console.print(text=help_text, menu="Stocks - Due Diligence")
| gamestonk_terminal/stocks/due_diligence/dd_controller.py | 47 | OpenBBTerminal | {
"docstring": "Print help\n[param]Ticker: [/param]{self.ticker}[cmds]\n\n[src][Finviz][/src]\n analyst analyst prices and ratings of the company\n[src][FMP][/src]\n rating rating over time (daily)\n[src][Finnhub][/src]\n rot number of analysts ratings over time (monthly)\n[src][Busine... | 10 | Python | 10 | 82747072c511beb1b2672846ae2ee4aec53eb562 | dd_controller.py | 281,541 | 22 | 22 | print_help | https://github.com/OpenBB-finance/OpenBBTerminal.git | 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... | 31 | 0 | 83,839 | 9 | |
5 | 13 | def get_preprocess_function(self, field, value, export_format):
# Try to find a field specific function and return it
format_dict = self.custom_field_preprocess.get(field, {})
if export_format in format_dict:
return format_dict[export_format]
# Otherwise check for ... | wagtail/admin/views/mixins.py | 105 | wagtail | {
"docstring": "Returns the preprocessing function for a given field name, field value, and export format",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | 60 | Python | 40 | d10f15e55806c6944827d801cd9c2d53f5da4186 | mixins.py | 72,424 | 8 | 67 | get_preprocess_function | https://github.com/wagtail/wagtail.git | Reformat with black | 153 | 0 | 15,891 | 10 | |
3 | 11 | def get_corrected_cpu(cpu_count): # formerlly get_cpu_capacity
from django.conf import settings
settings_abscpu = getattr(settings, 'SYSTEM_TASK_ABS_CPU', None)
env_abscpu = os.getenv('SYSTEM_TASK_ABS_CPU', None)
if env_abscpu is not None:
return convert_cpu_str_to_decimal_cpu(env_abscpu... | awx/main/utils/common.py | 94 | awx | {
"docstring": "Some environments will do a correction to the reported CPU number\n because the given OpenShift value is a lie\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 19,
"vocab_size": 17
} | 37 | Python | 27 | 799968460d4794bcd9959f57a2b97846b9a00bb7 | common.py | 80,659 | 9 | 56 | get_corrected_cpu | https://github.com/ansible/awx.git | Fixup conversion of memory and cpu settings to support k8s resource request format (#11725)
fix memory and cpu settings to suport k8s resource request format
* fix conversion of memory setting to bytes
This setting has not been getting set by default, and needed some fixing
up to be compatible with setting the ... | 74 | 0 | 17,088 | 10 | |
1 | 3 | def clear(self):
raise NotImplementedError
| python/ray/air/execution/resources/resource_manager.py | 16 | ray | {
"docstring": "Reset internal state and clear all resources.\n\n Calling this method will reset the resource manager to its initialization state.\n All resources will be removed.\n\n Clearing the state will remove tracked resources from the manager, but there are\n no guarantees about the... | 4 | Python | 4 | edb17fd2069844f12237c85ba6607afae536401d | resource_manager.py | 138,043 | 2 | 8 | clear | 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
-... | 18 | 0 | 31,286 | 6 | |
2 | 4 | def _supports_universal_builds():
# As an approximation, we assume that if we are running on 10.4 or above,
# then we are running with an Xcode environment that supports universal
# builds, in particular -isysroot and -arch arguments to the compiler. This
# is in support of allowing 10.4 universal ... | python3.10.4/Lib/_osx_support.py | 46 | XX-Net | {
"docstring": "Returns True if universal builds are supported on this system",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 67 | Python | 51 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | _osx_support.py | 219,598 | 3 | 25 | _supports_universal_builds | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 88 | 0 | 55,636 | 10 | |
7 | 18 | def symmetric_poly(n, *gens, **args):
# TODO: use an explicit keyword argument
gens = _analyze_gens(gens)
if n < 0 or n > len(gens) or not gens:
raise ValueError("Cannot generate symmetric polynomial of order %s for %s" % (n, gens))
elif not n:
poly = S.One
else:
poly =... | sympy/polys/specialpolys.py | 174 | @public | sympy | {
"docstring": "Generates symmetric polynomial of order `n`.\n\n Returns a Poly object when ``polys=True``, otherwise\n (default) returns an expression.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 17,
"vocab_size": 17
} | 64 | Python | 52 | 337e5c51b1ae7e202b7d7c62107fab6d5ea58d93 | specialpolys.py | 195,838 | 12 | 103 | symmetric_poly | https://github.com/sympy/sympy.git | Removed even more Python 2-support | 122 | 1 | 47,432 | 18 |
1 | 23 | def test_ensure_print_span_characteristics_wont_fail():
nlp = English()
spans_key = "sc"
pred = Doc(nlp.vocab, words=["Welcome", "to", "the", "Bank", "of", "China", "."])
pred.spans[spans_key] = [Span(pred, 3, 6, "ORG"), Span(pred, 5, 6, "GPE")]
ref = Doc(nlp.vocab, words=["Welcome", "to", "th... | spacy/tests/test_cli.py | 309 | @pytest.mark.parametrize("threshold", [70, 80, 85, 90, 95]) | spaCy | {
"docstring": "Test if interface between two methods aren't destroyed if refactored",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 75 | Python | 51 | 1d34aa2b3dd1ba0931dcb1863dfbeba6ae5b912d | test_cli.py | 111,324 | 14 | 172 | test_ensure_print_span_characteristics_wont_fail | https://github.com/explosion/spaCy.git | Add spacy-span-analyzer to debug data (#10668)
* Rename to spans_key for consistency
* Implement spans length in debug data
* Implement how span bounds and spans are obtained
In this commit, I implemented how span boundaries (the tokens) around a
given span and spans are obtained. I've put them in the compil... | 120 | 1 | 24,375 | 11 |
4 | 14 | def find_path_to_setup_from_repo_root(location, repo_root):
# type: (str, str) -> Optional[str]
# find setup.py
orig_location = location
while not os.path.exists(os.path.join(location, 'setup.py')):
last_location = location
location = os.path.dirname(location)
if location ==... | .venv/lib/python3.8/site-packages/pip/_internal/vcs/versioncontrol.py | 145 | transferlearning | {
"docstring": "\n Find the path to `setup.py` by searching up the filesystem from `location`.\n Return the path to `setup.py` relative to `repo_root`.\n Return None if `setup.py` is in `repo_root` or cannot be found.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 31,
"vocab_size": 23
} | 68 | Python | 51 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | versioncontrol.py | 61,395 | 15 | 86 | find_path_to_setup_from_repo_root | https://github.com/jindongwang/transferlearning.git | upd; format | 217 | 0 | 12,543 | 13 | |
1 | 2 | def isomin(self):
return self["isomin"]
| packages/python/plotly/plotly/graph_objs/_isosurface.py | 22 | plotly.py | {
"docstring": "\n Sets the minimum boundary for iso-surface plot.\n\n The 'isomin' property is a number and may be specified as:\n - An int or float\n\n Returns\n -------\n int|float\n ",
"language": "en",
"n_whitespaces": 78,
"n_words": 26,
"vocab_size": 26... | 4 | Python | 4 | 43e3a4011080911901176aab919c0ecf5046ddd3 | _isosurface.py | 227,305 | 2 | 11 | isomin | https://github.com/plotly/plotly.py.git | switch to black .22 | 18 | 0 | 58,978 | 7 | |
7 | 4 | def _configure_matplotlib(cls):
rcParams["keymap.fullscreen"] = [k for k in rcParams["keymap.fullscreen"] if k != "f"]
rcParams["keymap.save"] = [k for k in rcParams["keymap.save"] if k != "s"]
rcParams["keymap.home"] = [k for k in rcParams["keymap.home"] if k != "r"]
rcParams["... | scripts/train.py | 123 | faceswap | {
"docstring": " Remove `F`, 'S' and 'R' from their default bindings and stop Matplotlib from stealing\n focus ",
"language": "en",
"n_whitespaces": 23,
"n_words": 15,
"vocab_size": 13
} | 38 | Python | 17 | c8122bc499afba4fcb99030e42e08bfb8d3a75e1 | train.py | 101,053 | 5 | 69 | _configure_matplotlib | https://github.com/deepfakes/faceswap.git | bugfix: Stop preview window from stealing focus | 73 | 0 | 20,490 | 10 | |
4 | 20 | def _per_replica_aggregate_batch(strategy, batch_outs, model, mode):
if strategy is not None and mode == ModeKeys.PREDICT:
total_batch_outs = []
for i in range(len(model.outputs)):
num_replicas = strategy.num_replicas_in_sync
nested_outs = batch_outs[
i *... | keras/distribute/distributed_training_utils_v1.py | 125 | keras | {
"docstring": "Aggregates the per-replica batch-level outputs from a distributed step.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | 44 | Python | 34 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | distributed_training_utils_v1.py | 270,352 | 13 | 80 | _per_replica_aggregate_batch | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 159 | 0 | 80,449 | 16 | |
1 | 16 | def test_get_bad_image(self):
# Get
response = self.client.get(
reverse(
"wagtailimages:generate_url", args=(self.image.id + 1, "fill-800x600")
)
)
# Check response
self.assertEqual(response.status_code, 404)
self.assertEq... | wagtail/images/tests/test_admin_views.py | 137 | wagtail | {
"docstring": "\n This tests that the view gives a 404 response if a user attempts to use it with an image which doesn't exist\n ",
"language": "en",
"n_whitespaces": 37,
"n_words": 22,
"vocab_size": 21
} | 36 | Python | 30 | d10f15e55806c6944827d801cd9c2d53f5da4186 | test_admin_views.py | 75,173 | 16 | 79 | test_get_bad_image | https://github.com/wagtail/wagtail.git | Reformat with black | 225 | 0 | 16,373 | 15 | |
4 | 18 | def to_dict(self, is_png=False) -> MaskAlignmentsFileDict:
assert self._mask is not None
affine_matrix = self.affine_matrix.tolist() if is_png else self.affine_matrix
retval = MaskAlignmentsFileDict(mask=self._mask,
affine_matrix=affine_matrix,
... | lib/align/detected_face.py | 149 | faceswap | {
"docstring": " Convert the mask to a dictionary for saving to an alignments file\n\n Parameters\n ----------\n is_png: bool\n ``True`` if the dictionary is being created for storage in a png header otherwise\n ``False``. Default: ``False``\n\n Returns\n -----... | 42 | Python | 37 | 5e73437be47f2410439a3c6716de96354e6a0c94 | detected_face.py | 101,226 | 24 | 97 | to_dict | https://github.com/deepfakes/faceswap.git | lib.align updates:
- alignments.py
- Add typed dicts for imported alignments
- Explicitly check for presence of thumb value in alignments dict
- linting
- detected_face.py
- Typing
- Linting
- Legacy support for pre-aligned face
- Update dependencies to new property names | 241 | 0 | 20,646 | 12 | |
3 | 13 | def getgeneratorlocals(generator):
if not isgenerator(generator):
raise TypeError("{!r} is not a Python generator".format(generator))
frame = getattr(generator, "gi_frame", None)
if frame is not None:
return generator.gi_frame.f_locals
else:
return {}
# -----------------... | python3.10.4/Lib/inspect.py | 115 | XX-Net | {
"docstring": "\n Get the mapping of generator local variables to their current values.\n\n A dict is returned, with the keys the local variable names and values the\n bound values.",
"language": "en",
"n_whitespaces": 36,
"n_words": 27,
"vocab_size": 22
} | 43 | Python | 33 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | inspect.py | 218,447 | 8 | 50 | getgeneratorlocals | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 74 | 0 | 55,315 | 12 | |
1 | 8 | async def setup(self) -> None:
await self._update_gauges()
self._clock.looping_call(
run_as_background_process,
5 * 60 * 1000,
desc="common_usage_metrics_update_gauges",
func=self._update_gauges,
)
| synapse/metrics/common_usage_metrics.py | 65 | synapse | {
"docstring": "Keep the gauges for common usage metrics up to date.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 17 | Python | 16 | 898fef2789c9b1a20ef53c7d588f536f51f0fe2f | common_usage_metrics.py | 249,451 | 9 | 39 | setup | https://github.com/matrix-org/synapse.git | Share some metrics between the Prometheus exporter and the phone home stats (#13671) | 89 | 0 | 72,923 | 9 | |
2 | 23 | def query_trial(request):
trial_id = request.GET.get("trial_id")
trials = TrialRecord.objects.filter(trial_id=trial_id).order_by("-start_time")
if len(trials) == 0:
resp = "Unkonwn trial id %s.\n" % trials
else:
trial = trials[0]
result = {
"trial_id": trial.tria... | python/ray/tune/automlboard/frontend/query.py | 192 | ray | {
"docstring": "Rest API to query the trial info, with the given trial_id.\n\n The url pattern should be like this:\n\n curl http://<server>:<port>/query_trial?trial_id=<trial_id>\n\n The response may be:\n\n {\n \"app_url\": \"None\",\n \"trial_status\": \"TERMINATED\",\n \"params\":... | 46 | Python | 38 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | query.py | 132,073 | 17 | 111 | query_trial | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 165 | 0 | 29,666 | 12 | |
1 | 31 | def test_transaction_outcome_accepted(self):
manager = EventManager(
make_event(
transaction="wait",
contexts={
"trace": {
"parent_span_id": "bce14471e0e9654d",
"op": "foobar",
... | tests/sentry/event_manager/test_event_manager.py | 244 | sentry | {
"docstring": "\n Without metrics extraction, we count the number of accepted transaction\n events in the TRANSACTION data category. This maintains compatibility\n with Sentry installations that do not have a metrics pipeline.\n ",
"language": "en",
"n_whitespaces": 58,
"n_words": 2... | 43 | Python | 39 | abcccb3fe46fb8479687b77e8bce07dc5df13c90 | test_event_manager.py | 88,863 | 27 | 140 | test_transaction_outcome_accepted | https://github.com/getsentry/sentry.git | fix(event_manager): Emit TRANSACTION outcomes if metrics are disabled (#41607)
In #40507 we started to count transaction metrics in the `transaction`
data category and transaction events in the `transaction_indexed` data
category. That PR missed that metrics extraction can be disabled, in
which case the old behavio... | 408 | 0 | 18,459 | 16 | |
5 | 19 | def set_weights(self, weights):
params = self.weights
if len(params) != len(weights):
raise ValueError(
f"You called `set_weights(weights)` on optimizer {self._name} "
f"with a weight list of length {str(len(weights))}, "
f"but the op... | keras/optimizers/optimizer_v2/optimizer_v2.py | 241 | keras | {
"docstring": "Set the weights of the optimizer.\n\n The weights of an optimizer are its state (ie, variables).\n This function takes the weight values associated with this\n optimizer as a list of Numpy arrays. The first value is always the\n iterations count of the optimizer, followed b... | 80 | Python | 63 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | optimizer_v2.py | 275,511 | 22 | 103 | set_weights | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 339 | 0 | 81,406 | 17 | |
4 | 17 | def delete(self) -> None:
try:
if hasattr(self.object, 'close'):
self.object.close()
self._logger.info(self.item.arguments)
if self.item.arguments.get('identity'):
self._logger.success(
f'{colored(se... | daemon/stores/partial.py | 214 | jina | {
"docstring": "Terminates the object in the store & stops the server",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 8
} | 37 | Python | 33 | 933415bfa1f9eb89f935037014dfed816eb9815d | partial.py | 9,815 | 19 | 105 | delete | 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 ... | 275 | 0 | 1,707 | 20 | |
2 | 9 | def markInputline(self, markerString=">!<"):
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | .venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py | 88 | transferlearning | {
"docstring": "Extracts the exception line from the input string, and marks\n the location of the exception with a special symbol.\n ",
"language": "en",
"n_whitespaces": 36,
"n_words": 19,
"vocab_size": 15
} | 20 | Python | 17 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | pyparsing.py | 63,453 | 7 | 53 | markInputline | https://github.com/jindongwang/transferlearning.git | upd; format | 97 | 0 | 13,311 | 13 | |
15 | 12 | def convert_indexed_to_array(expr, first_indices=None):
r
result, indices = _convert_indexed_to_array(expr)
if any(isinstance(i, (int, Integer)) for i in indices):
result = ArrayElement(result, indices)
indices = []
if not first_indices:
return result
| sympy/tensor/array/expressions/conv_indexed_to_array.py | 87 | sympy | {
"docstring": "\n Parse indexed expression into a form useful for code generation.\n\n Examples\n ========\n\n >>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array\n >>> from sympy import MatrixSymbol, Sum, symbols\n\n >>> i, j, k, d = symbols(\"i j k d\")\n... | 28 | Python | 23 | 0aabd1d7b8c3cb521f713ea925a0bf019ba1f3ca | conv_indexed_to_array.py | 196,010 | 62 | 191 | convert_indexed_to_array | https://github.com/sympy/sympy.git | Extend conversion function of indexed expression to arrays to support broadcasting and addition of different indices | 60 | 0 | 47,511 | 10 | |
7 | 22 | def is_symbolic_tensor(tensor):
if isinstance(tensor, tf.Tensor):
return hasattr(tensor, "graph")
elif is_extension_type(tensor):
component_tensors = tf.nest.flatten(tensor, expand_composites=True)
return any(hasattr(t, "graph") for t in component_tensors)
elif isinstance(tensor... | keras/utils/tf_utils.py | 205 | @keras_export("keras.__internal__.utils.register_symbolic_tensor_type", v1=[]) | keras | {
"docstring": "Returns whether a tensor is symbolic (from a TF graph) or an eager tensor.\n\n A Variable can be seen as either: it is considered symbolic\n when we are in a graph scope, and eager when we are in an eager scope.\n\n Args:\n tensor: A tensor instance to test.\n\n Returns:\n True f... | 90 | Python | 68 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | tf_utils.py | 277,089 | 16 | 113 | is_symbolic_tensor | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 220 | 1 | 81,861 | 13 |
10 | 36 | def _on_size(self, event):
_log.debug("%s - _on_size()", type(self))
sz = self.GetParent().GetSizer()
if sz:
si = sz.GetItem(self)
if sz and si and not si.Proportion and not si.Flag & wx.EXPAND:
# managed by a sizer, but with a fixed size
siz... | lib/matplotlib/backends/backend_wx.py | 344 | matplotlib | {
"docstring": "\n Called when wxEventSize is generated.\n\n In this application we attempt to resize to fit the window, so it\n is better to take the performance hit and redraw the whole window.\n ",
"language": "en",
"n_whitespaces": 59,
"n_words": 30,
"vocab_size": 25
} | 149 | Python | 101 | 4e21912d2938b0e8812c4d1f7cd902c080062ff2 | backend_wx.py | 108,945 | 24 | 207 | _on_size | https://github.com/matplotlib/matplotlib.git | Make it easier to improve UI event metadata.
Currently, UI events (MouseEvent, KeyEvent, etc.) are generated by
letting the GUI-specific backends massage the native event objects into
a list of args/kwargs and then call
`FigureCanvasBase.motion_notify_event`/`.key_press_event`/etc. This
makes it a bit tricky to impro... | 426 | 0 | 23,396 | 12 | |
1 | 26 | def test_subdag_pools_no_possible_conflict(self):
dag = DAG('parent', default_args=default_args)
subdag = DAG('parent.child', default_args=default_args)
session = airflow.settings.Session()
pool_1 = airflow.models.Pool(pool='test_pool_1', slots=1)
pool_10 = airflow.mode... | tests/operators/test_subdag_operator.py | 250 | airflow | {
"docstring": "\n Subdags and subdag tasks with no pool overlap, should not to query\n pools\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 13,
"vocab_size": 13
} | 41 | Python | 34 | 49e336ae0302b386a2f47269a6d13988382d975f | test_subdag_operator.py | 47,649 | 16 | 149 | test_subdag_pools_no_possible_conflict | https://github.com/apache/airflow.git | Replace usage of `DummyOperator` with `EmptyOperator` (#22974)
* Replace usage of `DummyOperator` with `EmptyOperator` | 153 | 0 | 9,190 | 10 | |
24 | 35 | def tree_all_pairs_lowest_common_ancestor(G, root=None, pairs=None):
r
if len(G) == 0:
raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
elif None in G:
raise nx.NetworkXError("None is not a valid node.")
# Index pairs of interest for efficient lookup from either side... | networkx/algorithms/lowest_common_ancestors.py | 573 | @not_implemented_for("undirected")
@not_implemented_for("multigraph") | networkx | {
"docstring": "Yield the lowest common ancestor for sets of pairs in a tree.\n\n Parameters\n ----------\n G : NetworkX directed graph (must be a tree)\n\n root : node, optional (default: None)\n The root of the subtree to operate on.\n If None, assume the entire graph has exactly one sourc... | 314 | Python | 173 | abaa68779ccb4cce8d1a5ecade622ab96d01edeb | lowest_common_ancestors.py | 176,977 | 102 | 345 | tree_all_pairs_lowest_common_ancestor | https://github.com/networkx/networkx.git | Add examples to lowest common ancestors algorithms (#5531)
* Add examples to lowest common ancestors documentation
* Fix output style of examples
* Fix output style of example
* Update pre-commit
* Update networkx/algorithms/lowest_common_ancestors.py
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu... | 808 | 1 | 42,205 | 18 |
1 | 11 | def view_transformation(E, R, V, roll):
u, v, w = _view_axes(E, R, V, roll)
M = _view_transformation_uvw(u, v, w, E)
return M
| lib/mpl_toolkits/mplot3d/proj3d.py | 59 | matplotlib | {
"docstring": "\n Return the view transformation matrix.\n\n Parameters\n ----------\n E : 3-element numpy array\n The coordinates of the eye/camera.\n R : 3-element numpy array\n The coordinates of the center of the view box.\n V : 3-element numpy array\n Unit vector in the di... | 21 | Python | 16 | 4896ec1a2cfb8c454e385632d8df213c915ced52 | proj3d.py | 109,756 | 4 | 42 | view_transformation | https://github.com/matplotlib/matplotlib.git | Add pan and zoom toolbar handling to 3D Axes (Replaces PR#22614) (#23449)
* ENH: Add pan and zoom toolbar handling to 3D Axes
1) This moves the pan logic that was already in the mouse move handler
into the "drag_pan" method to make it available from the toolbar.
2) This expands upon the panning logic to enable ... | 33 | 0 | 23,737 | 8 | |
4 | 19 | def _get_missing_alignments(self) -> Generator[str, None, None]:
self.output_message = "Frames missing from alignments file"
exclude_filetypes = set(["yaml", "yml", "p", "json", "txt"])
for frame in tqdm(cast(Dict[str, str], self._items),
desc=self.output_messa... | tools/alignments/jobs.py | 169 | faceswap | {
"docstring": " yield each frame that does not exist in alignments file\n\n Yields\n ------\n str\n The frame name of any frames missing alignments\n ",
"language": "en",
"n_whitespaces": 61,
"n_words": 21,
"vocab_size": 19
} | 44 | Python | 38 | e2a77e7c6e84e81f642cb22f528e25e3f2d2dbc1 | jobs.py | 101,717 | 18 | 103 | _get_missing_alignments | https://github.com/deepfakes/faceswap.git | Alignments Tool - Typing, Documentation + Re-org | 193 | 0 | 21,121 | 13 | |
1 | 3 | def rebalance_partitions(cls, partitions):
return partitions
| modin/core/dataframe/pandas/partitioning/partition_manager.py | 18 | modin | {
"docstring": "\n Return the provided array of partitions without rebalancing it.\n\n Parameters\n ----------\n partitions : np.ndarray\n The 2-d array of partitions to rebalance.\n\n Returns\n -------\n np.ndarray\n The same 2-d array.\n ... | 5 | Python | 5 | 8d1004fdbdaa05700613c8e6287641a732acf606 | partition_manager.py | 153,177 | 2 | 10 | rebalance_partitions | https://github.com/modin-project/modin.git | FIX-#3675: Expand virtual partitioning utility (#3886)
Co-authored-by: mvashishtha <mahesh@ponder.io>
Co-authored-by: jeffreykennethli <jkli@ponder.io>
Co-authored-by: Anatoly Myachev <anatoly.myachev@intel.com>
Co-authored-by: Vasily Litvinov <vasilij.n.litvinov@intel.com>
Co-authored-by: Alexey Prutskov <alexey.... | 19 | 0 | 35,280 | 6 | |
2 | 8 | def _handle_deprecations(self) -> None:
if self._args.distributed:
deprecation_warning("`-d`, `--distributed`",
"Please use `-D`, `--distribution-strategy`")
logger.warning("Setting 'distribution-strategy' to 'mirrored'")
setattr(self.... | scripts/train.py | 79 | faceswap | {
"docstring": " Handle the update of deprecated arguments and output warnings. ",
"language": "en",
"n_whitespaces": 10,
"n_words": 9,
"vocab_size": 9
} | 21 | Python | 21 | 2ea05623bd684b2d1dd75679ad00441a5c751e7e | train.py | 101,076 | 8 | 43 | _handle_deprecations | https://github.com/deepfakes/faceswap.git | Update Distibution Strategies:
- Add Central Storage Stategy
- Deprecate 'distributed' cli argument | 110 | 0 | 20,513 | 10 | |
3 | 33 | def to_qa_preds(self, top_preds, no_ans_gaps, baskets):
ret = []
# Iterate over each set of document level prediction
for pred_d, no_ans_gap, basket in zip(top_preds, no_ans_gaps, baskets):
# Unpack document offsets, clear text and id
token_offsets = basket.raw... | haystack/modeling/model/prediction_head.py | 238 | haystack | {
"docstring": "\n Groups Span objects together in a QAPred object\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 8,
"vocab_size": 8
} | 105 | Python | 84 | a59bca366174d9c692fa19750c24d65f47660ef7 | prediction_head.py | 256,248 | 23 | 152 | to_qa_preds | https://github.com/deepset-ai/haystack.git | Apply black formatting (#2115)
* Testing black on ui/
* Applying black on docstores
* Add latest docstring and tutorial changes
* Create a single GH action for Black and docs to reduce commit noise to the minimum, slightly refactor the OpenAPI action too
* Remove comments
* Relax constraints on pydoc-ma... | 418 | 0 | 74,828 | 12 | |
2 | 9 | def _deconstruct_messages(snuba_messages):
return [
(json.loads(msg.payload.value.decode("utf-8")), msg.payload.headers)
for msg in snuba_messages
]
| tests/sentry/sentry_metrics/test_batch.py | 59 | sentry | {
"docstring": "\n Convert a list of messages returned by `reconstruct_messages` into python\n primitives, to run assertions on:\n\n assert _deconstruct_messages(batch.reconstruct_messages(...)) == [ ... ]\n\n This is slightly nicer to work with than:\n\n assert batch.reconstruct_messages(...) ... | 11 | Python | 11 | f31b57cbc5ec359c8ef9c6459d3d9d8ffcd6e8d9 | test_batch.py | 93,937 | 5 | 36 | _deconstruct_messages | https://github.com/getsentry/sentry.git | ref(metrics_indexer): Improve typing, introduce more dataclasses, fix org_id namespacing bug in metadata [INGEST-1380] (#37170) | 34 | 0 | 19,028 | 13 | |
3 | 9 | def from_key_val_list(value):
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError("cannot encode objects that are not 2-tuples")
return OrderedDict(value)
| pipenv/patched/pip/_vendor/requests/utils.py | 63 | pipenv | {
"docstring": "Take an object and test to see if it can be represented as a\n dictionary. Unless it can not be represented as such, return an\n OrderedDict, e.g.,\n\n ::\n\n >>> from_key_val_list([('key', 'val')])\n OrderedDict([('key', 'val')])\n >>> from_key_val_list('string')\n ... | 24 | Python | 22 | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | utils.py | 22,139 | 6 | 39 | from_key_val_list | https://github.com/pypa/pipenv.git | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 50 | 0 | 4,211 | 10 | |
2 | 10 | def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, BloomModel):
module.gradient_checkpointing = value
BLOOM_START_DOCSTRING = r
BLOOM_INPUTS_DOCSTRING = r
@add_start_docstrings(
"The bare Bloom Model transformer outputting raw hidden-states without any specifi... | src/transformers/models/bloom/modeling_bloom.py | 64 | @add_start_docstrings(
"The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.",
BLOOM_START_DOCSTRING,
) | transformers | {
"docstring": "\n\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)\n\n This model is also a PyTorch [torch.nn.Module](https://pytorch.org/d... | 33 | Python | 30 | ca2a55e9dfb245527b5e1c954fec6ffbb7aef07b | modeling_bloom.py | 31,156 | 3 | 24 | _set_gradient_checkpointing | https://github.com/huggingface/transformers.git | BLOOM (#17474)
* adding template
* update model
* model update
* update conf for debug model
* update conversion
* update conversion script
* update conversion script
* fix missing keys check
* add tests to test the tokenizer in the local machine
* Change variable name
* add tests on xnl... | 52 | 1 | 5,691 | 9 |
3 | 15 | def __getitem__(self, name): # -> EntryPoint:
if isinstance(name, int):
warnings.warn(
"Accessing entry points by index is deprecated. "
"Cast to tuple if needed.",
DeprecationWarning,
stacklevel=2,
)
r... | python3.10.4/Lib/importlib/metadata/__init__.py | 108 | XX-Net | {
"docstring": "\n Get the EntryPoint in self matching name.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | 35 | Python | 33 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | __init__.py | 218,271 | 13 | 64 | __getitem__ | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 179 | 0 | 55,236 | 14 | |
1 | 7 | def isgeneratorfunction(obj):
return _inspect.isgeneratorfunction(
tf.__internal__.decorator.unwrap(obj)[1]
)
| keras/utils/tf_inspect.py | 42 | keras | {
"docstring": "TFDecorator-aware replacement for inspect.isgeneratorfunction.",
"language": "en",
"n_whitespaces": 3,
"n_words": 4,
"vocab_size": 4
} | 6 | Python | 6 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | tf_inspect.py | 277,066 | 4 | 25 | isgeneratorfunction | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 22 | 0 | 81,843 | 12 | |
4 | 31 | def _update_from_feed(self, feed_entry, last_update, last_update_successful):
self._title = feed_entry.title
# Convert distance if not metric system.
if self._unit_system == CONF_UNIT_SYSTEM_IMPERIAL:
self._distance = round(
DistanceConverter.convert(
... | homeassistant/components/geonetnz_volcano/sensor.py | 228 | core | {
"docstring": "Update the internal state from the provided feed entry.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | 70 | Python | 52 | 503434e538af4b708f01cee9ca20bfa8426cec94 | sensor.py | 288,948 | 21 | 150 | _update_from_feed | https://github.com/home-assistant/core.git | Use DistanceConverter in components (#80182)
* Use DistanceConverter in components
* Adjust for METRIC_SYSTEM | 276 | 0 | 88,097 | 13 | |
7 | 17 | def test_checking_core_page_fields_are_indexed(self):
# first confirm that errors show as EventPage (in test models) has no Page.search_fields
errors = [error for error in checks.run_checks() if error.id == 'wagtailsearch.W001']
# should only ever get this warning on the sub-classes o... | wagtail/search/tests/test_indexed_class.py | 185 | wagtail | {
"docstring": "Run checks to ensure that when core page fields are missing we get a warning",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 15
} | 103 | Python | 70 | d964675ee8fcb7ea58681ac8869733a86d58e4ec | test_indexed_class.py | 70,443 | 11 | 113 | test_checking_core_page_fields_are_indexed | https://github.com/wagtail/wagtail.git | add check for correct search_fields on pages
- fixes #4940 | 233 | 0 | 15,509 | 12 | |
1 | 20 | def test_mixed_string_bytes_categoricals():
# data as unicode
X = np.array([["b"], ["a"]], dtype="U")
# predefined categories as bytes
categories = [np.array(["b", "a"], dtype="S")]
ohe = OneHotEncoder(categories=categories, sparse_output=False)
msg = re.escape(
"In column 0, the p... | sklearn/preprocessing/tests/test_encoders.py | 175 | @pytest.mark.parametrize("missing_value", [np.nan, None]) | scikit-learn | {
"docstring": "Check that this mixture of predefined categories and X raises an error.\n\n Categories defined as bytes can not easily be compared to data that is\n a string.\n ",
"language": "en",
"n_whitespaces": 36,
"n_words": 27,
"vocab_size": 26
} | 54 | Python | 44 | ecb9a70e82d4ee352e2958c555536a395b53d2bd | test_encoders.py | 261,789 | 10 | 82 | test_mixed_string_bytes_categoricals | https://github.com/scikit-learn/scikit-learn.git | FIX Ensure dtype of categories is `object` for strings in `OneHotEncoder` (#25174)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> | 101 | 1 | 76,996 | 11 |
1 | 5 | def execute():
frappe.reload_doc("HR", "doctype", "Leave Allocation")
frappe.reload_doc("HR", "doctype", "Leave Ledger Entry")
frappe.db.sql(
)
frappe.db.sql(
)
| erpnext/patches/v13_0/set_company_in_leave_ledger_entry.py | 78 | erpnext | {
"docstring": "update `tabLeave Ledger Entry` as lle set company = (select company from `tabEmployee` where employee = lle.employee)update `tabLeave Allocation` as la set company = (select company from `tabEmployee` where employee = la.employee)",
"language": "en",
"n_whitespaces": 31,
"n_words": 32,
"vocab_... | 15 | Python | 10 | 494bd9ef78313436f0424b918f200dab8fc7c20b | set_company_in_leave_ledger_entry.py | 66,793 | 9 | 40 | execute | https://github.com/frappe/erpnext.git | style: format code with black | 8 | 0 | 14,336 | 8 | |
2 | 11 | def collocations(self, num=20, window_size=2):
collocation_strings = [
w1 + " " + w2 for w1, w2 in self.collocation_list(num, window_size)
]
print(tokenwrap(collocation_strings, separator="; "))
| nltk/text.py | 76 | nltk | {
"docstring": "\n Print collocations derived from the text, ignoring stopwords.\n\n >>> from nltk.book import text4\n >>> text4.collocations() # doctest: +NORMALIZE_WHITESPACE\n United States; fellow citizens; years ago; four years; Federal\n Government; General Gov... | 23 | Python | 20 | 8a4cf5d94eb94b6427c5d1d7907ba07b119932c5 | text.py | 42,549 | 5 | 47 | collocations | 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... | 62 | 0 | 7,611 | 11 | |
3 | 10 | def get_held_invoices(party_type, party):
held_invoices = None
if party_type == "Supplier":
held_invoices = frappe.db.sql(
"select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
as_dict=1,
)
held_invoices = set(d["name"] for d in held_invoices)
return he... | erpnext/accounts/utils.py | 78 | erpnext | {
"docstring": "\n\tReturns a list of names Purchase Invoices for the given party that are on hold\n\t",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 15
} | 38 | Python | 32 | 494bd9ef78313436f0424b918f200dab8fc7c20b | utils.py | 65,407 | 9 | 46 | get_held_invoices | https://github.com/frappe/erpnext.git | style: format code with black | 29 | 0 | 13,888 | 12 | |
2 | 4 | def is_reserved(self):
return (self.network_address.is_reserved and
self.broadcast_address.is_reserved)
| python3.10.4/Lib/ipaddress.py | 34 | XX-Net | {
"docstring": "Test if the address is otherwise IETF reserved.\n\n Returns:\n A boolean, True if the address is within one of the\n reserved IPv6 Network ranges.\n\n ",
"language": "en",
"n_whitespaces": 60,
"n_words": 24,
"vocab_size": 19
} | 6 | Python | 6 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | ipaddress.py | 218,555 | 3 | 20 | is_reserved | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 35 | 0 | 55,386 | 9 | |
2 | 13 | def reshape(self, *newshape):
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
if new_total_size != self._loop_size:
raise ValueError("Invalid reshape parameters " + str(newshape))
# there is no `.func` as this class does not subtype `Basic`:
return type... | sympy/tensor/array/dense_ndim_array.py | 90 | sympy | {
"docstring": "\n Returns MutableDenseNDimArray instance with new shape. Elements number\n must be suitable to new shape. The only argument of method sets\n new shape.\n\n Examples\n ========\n\n >>> from sympy import MutableDenseNDimArray\n >>> a = MutableDens... | 35 | Python | 33 | 645539ed9a65eec4a7bfc4571bdf2135cfb68cfb | dense_ndim_array.py | 199,144 | 5 | 55 | reshape | https://github.com/sympy/sympy.git | Fix bug in error message (cast tuple to str)
```python
from sympy.abc import x, y, z
from sympy import Array
a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
a2.reshape(1)
```
Out:
```text
TypeError: can only concatenate str (not "tuple") to str
```
T... | 81 | 0 | 49,163 | 12 | |
2 | 19 | def _looks_like_red_hat_scheme() -> bool:
from distutils.command.install import install
from distutils.dist import Distribution
cmd: Any = install(Distribution())
cmd.finalize_options()
return (
cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local"
and cmd.prefix == f... | pipenv/patched/notpip/_internal/locations/__init__.py | 137 | @functools.lru_cache(maxsize=None) | pipenv | {
"docstring": "Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.\n\n Red Hat's ``00251-change-user-install-location.patch`` changes the install\n command's ``prefix`` and ``exec_prefix`` to append ``\"/local\"``. This is\n (fortunately?) done quite unconditionally, so we create a default command\n ... | 28 | Python | 25 | 7e33fcae4384563b4c927fd44318c29dd524a097 | __init__.py | 19,466 | 16 | 52 | _looks_like_red_hat_scheme | https://github.com/pypa/pipenv.git | Vendor in pip 21.2.4 release (from pip 21.2.2 prior). (#5009)
* Vendor in pip 21.2.4 release (from pip 21.2.2 prior).
* Add news fragment for pip 21.2.4 vendor update.
* Add potentially missing LICENSE files | 62 | 1 | 2,983 | 13 |
2 | 5 | def __call__(self, name=None):
if name is not None:
return self._setResultsName(name)
else:
return self.copy()
| .venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py | 52 | transferlearning | {
"docstring": "\n Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.\n\n If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be\n passed as ``True``.\n\n If ``name` is omitted, same as calling :class:`copy`.\n\n Example::\n\n ... | 13 | Python | 12 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | pyparsing.py | 63,355 | 5 | 31 | __call__ | https://github.com/jindongwang/transferlearning.git | upd; format | 56 | 0 | 13,264 | 10 | |
1 | 10 | def _num_elements(losses):
with backend.name_scope("num_elements") as scope:
return tf.cast(tf.size(losses, name=scope), dtype=losses.dtype)
| keras/utils/losses_utils.py | 66 | keras | {
"docstring": "Computes the number of elements in `losses` tensor.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 10 | Python | 10 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | losses_utils.py | 276,975 | 3 | 38 | _num_elements | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 23 | 0 | 81,809 | 12 | |
1 | 4 | def get_input_for_correctness_test(self, **kwargs):
return get_correctness_test_inputs(**kwargs)
| keras/distribute/keras_correctness_test_base.py | 27 | keras | {
"docstring": "Generates inputs that are dictionaries.\n\n We only provide a default implementation of this method here. If you need\n more customized way of providing input to your model, overwrite this method.\n\n Args:\n **kwargs: key word arguments about how to create the input dict... | 5 | Python | 5 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras_correctness_test_base.py | 270,387 | 2 | 15 | get_input_for_correctness_test | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 19 | 0 | 80,460 | 8 | |
5 | 15 | def __new__(cls, freq=None):
if isinstance(freq, PeriodDtype):
return freq
elif freq is None:
# empty constructor for pickle compat
# -10_000 corresponds to PeriodDtypeCode.UNDEFINED
u = PeriodDtypeBase.__new__(cls, -10_000)
u._freq =... | pandas/core/dtypes/dtypes.py | 169 | pandas | {
"docstring": "\n Parameters\n ----------\n freq : frequency\n ",
"language": "en",
"n_whitespaces": 34,
"n_words": 5,
"vocab_size": 5
} | 59 | Python | 37 | c7010a7adec1c47a4642fa068544699fc8e1ea6a | dtypes.py | 171,304 | 17 | 106 | __new__ | https://github.com/pandas-dev/pandas.git | STYLE enable pylint's redefined-outer-name (#49671)
* fix warning for pandas/core/dtypes/cast.py, pandas/core/dtypes/dtypes.py, pandas/core/indexes/base.py
* fix warning for pandas/core/dtypes/cast.py, pandas/core/dtypes/dtypes.py, pandas/core/indexes/base.py
* fix warning for pandas/core/dtypes/cast.py, pandas/... | 244 | 0 | 40,660 | 12 | |
4 | 21 | def actor_table(self, actor_id):
self._check_connected()
if actor_id is not None:
actor_id = ray.ActorID(hex_to_binary(actor_id))
actor_info = self.global_state_accessor.get_actor_info(actor_id)
if actor_info is None:
return {}
el... | python/ray/state.py | 202 | ray | {
"docstring": "Fetch and parse the actor table information for a single actor ID.\n\n Args:\n actor_id: A hex string of the actor ID to fetch information about.\n If this is None, then the actor table is fetched.\n\n Returns:\n Information from the actor table.\n ... | 48 | Python | 30 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | state.py | 131,062 | 19 | 124 | actor_table | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 273 | 0 | 29,463 | 15 | |
1 | 2 | def test_ragged_tensor_output(self):
| keras/engine/compile_utils_test.py | 13 | keras | {
"docstring": "Ensure that ragged tensors can be passed as targets and predictions.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 2 | Python | 2 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | compile_utils_test.py | 271,076 | 15 | 192 | test_ragged_tensor_output | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 9 | 0 | 80,686 | 6 | |
1 | 22 | def test_xml_element(self):
el = Element("tag")
el.set("key", "value")
el.text = "text"
childA = Element("childA")
childB = Element("childB")
el.append(childA)
el.append(childB)
upper = transform(str.upper)
newelem: Element = validate(xml_element(... | tests/test_api_validate.py | 407 | streamlink | {
"docstring": "\n ValidationError(XmlElementSchema):\n Unable to validate XML tag\n Context(equality):\n 'tag' does not equal 'invalid'\n \n ValidationError(XmlElementSchema):\n Unable to validate XML text\n Context(equal... | 90 | Python | 52 | 3d44da082b3ba202b9d0557bfd8ce747a1d7960c | test_api_validate.py | 187,159 | 44 | 235 | test_xml_element | https://github.com/streamlink/streamlink.git | 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
... | 283 | 0 | 45,718 | 15 | |
1 | 5 | def require_fsdp(test_case):
return unittest.skipUnless(is_torch_version(">=", "1.12.0"), "test requires torch version >= 1.12.0")(test_case)
| src/accelerate/test_utils/testing.py | 44 | accelerate | {
"docstring": "\n Decorator marking a test that requires FSDP installed. These tests are skipped when FSDP isn't installed\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 16,
"vocab_size": 15
} | 11 | Python | 11 | 0c6bdc2c237ac071be99ac6f93ddfbc8bbcb8441 | testing.py | 337,934 | 2 | 23 | require_fsdp | https://github.com/huggingface/accelerate.git | enhancements and fixes for FSDP and DeepSpeed (#532)
* checkpointing enhancements and fixes for FSDP and DeepSpeed
* resolving comments
1. Adding deprecation args and warnings in launcher for FSDP
2. Handling old configs to work with new launcher args wrt FSDP.
3. Reverting changes to public methods in `checkp... | 17 | 0 | 121,141 | 11 | |
1 | 4 | def cur_num_workers(self):
# Factor like this for convenient re-use.
return self._cur_num_workers(self.node_data_dict)
| python/ray/autoscaler/batching_node_provider.py | 28 | ray | {
"docstring": "Returns dict mapping node type to the number of nodes of that type.",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 12
} | 11 | Python | 11 | c51b0c9a5664e5c6df3d92f9093b56e61b48f514 | batching_node_provider.py | 136,556 | 2 | 15 | cur_num_workers | https://github.com/ray-project/ray.git | [autoscaler][kuberay] Batching node provider (#29933)
Implements the abstract subclass of NodeProvider proposed in
https://docs.google.com/document/d/1JyQINBFirZw7YenA_14zize0R3hIII1_fnfQytIXTPo/
The goal is to simplify the autoscaler's interactions with external cluster managers like the KubeRay operator.
A fo... | 32 | 0 | 30,939 | 8 | |
2 | 3 | def generate_lscolors(self) -> str:
| kittens/tui/dircolors.py | 16 | kitty | {
"docstring": " Output the database in the format used by the LS_COLORS environment variable. ",
"language": "en",
"n_whitespaces": 13,
"n_words": 12,
"vocab_size": 10
} | 4 | Python | 4 | 4a3ed628092fac5b2552c8554c0482c569d14323 | dircolors.py | 102,926 | 4 | 29 | generate_lscolors | https://github.com/kovidgoyal/kitty.git | Refactor: More f-string for kittens | 11 | 0 | 21,582 | 6 | |
3 | 7 | def get_keras_custom_objects():
# pylint:disable=no-name-in-module,import-outside-toplevel
if get_backend() == "amd" or get_tf_version() < 2.8:
from keras.utils import get_custom_objects
else:
from keras.utils.generic_utils import get_custom_objects
return get_custom_objects()
| lib/utils.py | 68 | faceswap | {
"docstring": " Wrapper to obtain keras.utils.get_custom_objects from correct location depending on\n backend used and tensorflow version. ",
"language": "en",
"n_whitespaces": 18,
"n_words": 14,
"vocab_size": 14
} | 23 | Python | 20 | c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf | utils.py | 100,363 | 6 | 40 | get_keras_custom_objects | https://github.com/deepfakes/faceswap.git | 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 -... | 52 | 0 | 19,852 | 9 | |
3 | 19 | def __call__(self, data_tuple):
# Metaupdate Step.
print("Meta-Update Step")
samples = data_tuple[0]
adapt_metrics_dict = data_tuple[1]
self.postprocess_metrics(
adapt_metrics_dict, prefix="MAMLIter{}".format(self.step_counter)
)
# MAML Meta-... | rllib/agents/mbmpo/mbmpo.py | 126 | ray | {
"docstring": "Args:\n data_tuple (tuple): 1st element is samples collected from MAML\n Inner adaptation steps and 2nd element is accumulated metrics\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 19,
"vocab_size": 17
} | 37 | Python | 30 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | mbmpo.py | 133,770 | 34 | 242 | __call__ | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 143 | 0 | 30,102 | 13 | |
6 | 20 | def hmean(a, axis=0, dtype=None, *, weights=None):
if not isinstance(a, np.ndarray):
a = np.array(a, dtype=dtype)
elif dtype:
# Must change the default dtype allowing array type
if isinstance(a, np.ma.MaskedArray):
a = np.ma.asarray(a, dtype=dtype)
else:
... | scipy/stats/_stats_py.py | 265 | scipy | {
"docstring": "Calculate the harmonic mean along the specified axis.\n\n That is: n / (1/x1 + 1/x2 + ... + 1/xn)\n\n Parameters\n ----------\n a : array_like\n Input array, masked array or object that can be converted to an array.\n axis : int or None, optional\n Axis along which the ha... | 93 | Python | 66 | a1546047bc146bf3189fa905c3415475b0e47931 | _stats_py.py | 241,810 | 16 | 155 | hmean | https://github.com/scipy/scipy.git | ENH: stats: add weights in harmonic mean (#15347)
Co-authored-by: Pamphile Roy <roy.pamphile@gmail.com> | 231 | 0 | 69,705 | 15 | |
3 | 12 | def ordinal(value):
try:
value = int(value)
except (TypeError, ValueError):
return value
if value % 100 in (11, 12, 13):
# Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th).
value = pgettext("ordinal 11, 12, 13", "{}th").format(value)
else:
... | django/contrib/humanize/templatetags/humanize.py | 278 | @register.filter(is_safe=True) | django | {
"docstring": "\n Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',\n 3 is '3rd', etc. Works for any integer.\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 23,
"vocab_size": 21
} | 212 | Python | 94 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | humanize.py | 204,149 | 22 | 143 | ordinal | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 501 | 1 | 50,649 | 13 |
1 | 11 | def get_granger_causality(dependent_series, independent_series, lags):
granger_set = pd.concat([dependent_series, independent_series], axis=1)
granger = grangercausalitytests(granger_set, [lags], verbose=False)
return granger
| openbb_terminal/econometrics/econometrics_model.py | 63 | OpenBBTerminal | {
"docstring": "Calculate granger tests\n\n Parameters\n ----------\n dependent_series: Series\n The series you want to test Granger Causality for.\n independent_series: Series\n The series that you want to test whether it Granger-causes time_series_y\n lags : int\n The amount of l... | 16 | Python | 14 | 9e1a58e2dbedec4e4a9f9c2e32ddf091776c606b | econometrics_model.py | 285,200 | 4 | 42 | get_granger_causality | https://github.com/OpenBB-finance/OpenBBTerminal.git | Here we merge all API Refactor related branches (#2236)
* Update api.py
* Updated forex menu
* refactor ycrv command
* refactor ycrv command black
* refactor ecocal command
* Minh changes
* Adding space to test pushing
* title fix ecocal df
* get economic calendar annotation
* fix investingc... | 28 | 0 | 85,240 | 9 | |
1 | 14 | def fetch_buffered_group_stats(group):
from sentry import buffer
from sentry.models import Group
result = buffer.get(Group, ["times_seen"], {"pk": group.id})
group.times_seen_pending = result["times_seen"]
@instrumented_task(
name="sentry.tasks.post_process.post_process_group",
time_limi... | src/sentry/tasks/post_process.py | 101 | @instrumented_task(
name="sentry.tasks.post_process.post_process_group",
time_limit=120,
soft_time_limit=110,
) | sentry | {
"docstring": "\n Fetches buffered increments to `times_seen` for this group and adds them to the current\n `times_seen`.\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 15,
"vocab_size": 14
} | 24 | Python | 21 | 09726d7fc95e53bb516e328fc1811fc9a0704cac | post_process.py | 96,154 | 5 | 44 | fetch_buffered_group_stats | https://github.com/getsentry/sentry.git | fix(post_process): Fetch buffered `times_seen` values and add them to `Group.times_seen` (#31624)
In `post_process_group` we process issue alert rules and also ignored groups. Both of these can have
conditions that read from the `times_seen` value on the `Group`.
The problem here is that updates to `times_seen` ar... | 46 | 1 | 19,285 | 11 |
3 | 21 | def mixin_base_ppr_parser(parser):
mixin_essential_parser(parser)
gp = add_arg_group(parser, title='Base Deployment')
gp.add_argument(
'--extra-search-paths',
type=str,
default=[],
nargs='*',
help='Extra search paths to be used when loading modules and finding... | jina/parsers/orchestrate/base.py | 202 | jina | {
"docstring": "Mixing in arguments required by pod/deployment/runtime module into the given parser.\n :param parser: the parser instance to which we add arguments\n \n The polling strategy of the Deployment and its endpoints (when `shards>1`).\n Can be defined for all endpoints of a Deployment or by endp... | 80 | Python | 64 | a3b71c7208b3cd48aa7bc978c3343a074947e3d9 | base.py | 12,207 | 41 | 123 | mixin_base_ppr_parser | https://github.com/jina-ai/jina.git | fix(parsers): clearify flow args (#4701) | 253 | 0 | 2,215 | 13 | |
4 | 9 | def preprocess(self, x):
if self.type == "value":
return x
elif self.type == "index":
return [self.choices.index(choice) for choice in x]
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Pl... | gradio/inputs.py | 96 | gradio | {
"docstring": "\n Parameters:\n x (List[str]): list of selected choices\n Returns:\n (Union[List[str], List[int]]): list of selected choices as strings or indices within choice list\n ",
"language": "en",
"n_whitespaces": 57,
"n_words": 21,
"vocab_size": 16
} | 35 | Python | 31 | cc0cff893f9d7d472788adc2510c123967b384fe | inputs.py | 179,244 | 11 | 55 | preprocess | https://github.com/gradio-app/gradio.git | Format The Codebase
- black formatting
- isort formatting | 152 | 0 | 42,924 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.