id int64 20 338k | vocab_size int64 2 671 | ast_levels int64 4 32 | nloc int64 1 451 | n_ast_nodes int64 12 5.6k | n_identifiers int64 1 186 | n_ast_errors int64 0 10 | n_words int64 2 2.17k | n_whitespaces int64 2 13.8k | fun_name stringlengths 2 73 | commit_message stringlengths 51 15.3k | url stringlengths 31 59 | code stringlengths 51 31k | ast_errors stringlengths 0 1.46k | token_counts int64 6 3.32k | file_name stringlengths 5 56 | language stringclasses 1
value | path stringlengths 7 134 | commit_id stringlengths 40 40 | repo stringlengths 3 28 | complexity int64 1 153 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
59,848 | 12 | 9 | 2 | 87 | 11 | 0 | 12 | 23 | set_login_api_ready_event | Add login with a browser to `prefect cloud login` (#7334) | https://github.com/PrefectHQ/prefect.git | def set_login_api_ready_event():
login_api.extra["ready-event"].set()
login_api = FastAPI(on_startup=[set_login_api_ready_event])
login_api.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
| 14 | cloud.py | Python | src/prefect/cli/cloud.py | 1a6dee5e9eb71e6e6d1d3492002e9cd674ab9f9b | prefect | 1 | |
42,591 | 94 | 22 | 47 | 598 | 25 | 0 | 166 | 1,053 | parse_tag | Support both iso639-3 codes and BCP-47 language tags (#3060)
* Add support for iso639-3 language codes
* Add support for retired language codes
* Move langnames.py to the top-level
* Add langcode() function
* Add iso639retired dictionary
* Improve wrapper functions
* Add module docstring with doctest... | https://github.com/nltk/nltk.git | def parse_tag(self, tag):
subtags = tag.split("-")
lang = {}
labels = ["language", "extlang", "script", "region", "variant", "variant"]
while subtags and labels:
subtag = subtags.pop(0)
found = False
while labels:
label = label... | 318 | bcp47.py | Python | nltk/corpus/reader/bcp47.py | f019fbedb3d2b6a2e6b58ec1b38db612b106568b | nltk | 15 | |
258,357 | 6 | 10 | 6 | 38 | 7 | 0 | 6 | 20 | get_prompt_templates | feat: Expand LLM support with PromptModel, PromptNode, and PromptTemplate (#3667)
Co-authored-by: ZanSara <sarazanzo94@gmail.com> | https://github.com/deepset-ai/haystack.git | def get_prompt_templates(cls) -> List[PromptTemplate]:
return list(cls.prompt_templates.values())
| 22 | prompt_node.py | Python | haystack/nodes/prompt/prompt_node.py | 9ebf164cfdfb320503b7161493420c1b0ec577a3 | haystack | 1 | |
203,186 | 9 | 11 | 6 | 49 | 7 | 0 | 9 | 63 | make_token | Fixed #30360 -- Added support for secret key rotation.
Thanks Florian Apolloner for the implementation idea.
Co-authored-by: Andreas Pelme <andreas@pelme.se>
Co-authored-by: Carlton Gibson <carlton.gibson@noumenal.es>
Co-authored-by: Vuyisile Ndlovu <terrameijar@gmail.com> | https://github.com/django/django.git | def make_token(self, user):
return self._make_token_with_timestamp(
user,
self._num_seconds(self._now()),
self.secret,
)
| 31 | tokens.py | Python | django/contrib/auth/tokens.py | 0dcd549bbe36c060f536ec270d34d9e7d4b8e6c7 | django | 1 | |
97,562 | 22 | 13 | 9 | 112 | 13 | 0 | 26 | 113 | update_repo_data | fix(tests): Fix flaky tests for GitLab updates (#33022)
See API-2585
Prev PR: #33000
In a previous PR I'd suggested we make a change to the naming scheme of repositories coming from GitLab, but as it turns out, we enforce unique constraints on Repositories (with OrganizationId and Name), meaning it doesn't even ... | https://github.com/getsentry/sentry.git | def update_repo_data(self, repo, event):
project = event["project"]
url_from_event = project["web_url"]
path_from_event = project["path_with_namespace"]
if repo.url != url_from_event or repo.config.get("path") != path_from_event:
repo.update(
url=u... | 68 | webhooks.py | Python | src/sentry/integrations/gitlab/webhooks.py | 8c2edeae7d3b6d134654cda749050e794b5edc61 | sentry | 3 | |
259,139 | 24 | 10 | 13 | 109 | 17 | 0 | 29 | 140 | predict | MNT Refactor KMeans and MiniBatchKMeans to inherit from a common base class (#22723)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Julien Jerphanion <git@jjerphan.xyz> | https://github.com/scikit-learn/scikit-learn.git | def predict(self, X, sample_weight=None):
check_is_fitted(self)
X = self._check_test_data(X)
x_squared_norms = row_norms(X, squared=True)
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
labels, _ = _labels_inertia_threadpool_limit(
X,
... | 73 | _kmeans.py | Python | sklearn/cluster/_kmeans.py | 6ab950ec081044a1f32c2d082772635bb56144d8 | scikit-learn | 1 | |
134,409 | 39 | 15 | 14 | 187 | 28 | 0 | 48 | 229 | test_ddppo_compilation | [RLlib] AlgorithmConfig: Next steps (volume 01); Algos, RolloutWorker, PolicyMap, WorkerSet use AlgorithmConfig objects under the hood. (#29395) | https://github.com/ray-project/ray.git | def test_ddppo_compilation(self):
config = ddppo.DDPPOConfig().resources(num_gpus_per_worker=0)
num_iterations = 2
for _ in framework_iterator(config, frameworks="torch"):
algo = config.build(env="CartPole-v0")
for i in range(num_iterations):
re... | 112 | test_ddppo.py | Python | rllib/algorithms/ddppo/tests/test_ddppo.py | 182744bbd151c166b8028355eae12a5da63fb3cc | ray | 4 | |
26,493 | 9 | 9 | 3 | 33 | 4 | 0 | 11 | 16 | test_validate_subscription_query_invalid | Add Webhook payload via graphql subscriptions (#9394)
* Add PoC of webhook subscriptions
* add async webhooks subscription payloads feature
* remove unneeded file
* add translations subscription handling, fixes after review
* remove todo
* add descriptions
* add descriptions, move subsrciption_payloa... | https://github.com/saleor/saleor.git | def test_validate_subscription_query_invalid():
result = validate_subscription_query("invalid_query")
assert result is False
TEST_VALID_SUBSCRIPTION_QUERY_WITH_FRAGMENT =
| 14 | test_create_deliveries_for_subscription.py | Python | saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py | aca6418d6c36956bc1ab530e6ef7e146ec9df90c | saleor | 1 | |
314,946 | 11 | 12 | 4 | 65 | 9 | 0 | 12 | 44 | rgbw_color | Bump blebox_uniapi to 2.0.0 and adapt integration (#73834) | https://github.com/home-assistant/core.git | def rgbw_color(self):
if (rgbw_hex := self._feature.rgbw_hex) is None:
return None
return tuple(blebox_uniapi.light.Light.rgb_hex_to_rgb_list(rgbw_hex)[0:4])
| 40 | light.py | Python | homeassistant/components/blebox/light.py | b5af96e4bb201c9bb43515ea11283bdc8c4212b4 | core | 2 | |
122,245 | 57 | 12 | 15 | 193 | 17 | 0 | 76 | 121 | dtype | implement bint arrays (opaque dtypes), add padding rules
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> | https://github.com/google/jax.git | def dtype(x, *, canonicalize=False):
if x is None:
raise ValueError(f"Invalid argument to dtype: {x}.")
elif isinstance(x, type) and x in python_scalar_dtypes:
dt = python_scalar_dtypes[x]
elif type(x) in python_scalar_dtypes:
dt = python_scalar_dtypes[type(x)]
elif jax.core.is_opaque_dtype(getat... | 112 | dtypes.py | Python | jax/_src/dtypes.py | 6d2aaac2454117d54997243714c1a009827707ca | jax | 8 | |
33,052 | 34 | 13 | 12 | 186 | 19 | 0 | 48 | 148 | to_numpy_array | Update feature extractor methods to enable type cast before normalize (#18499)
* Update methods to optionally rescale
This is necessary to allow for casting our images / videos to numpy arrays within the feature extractors' call. We want to do this to make sure the behaviour is as expected when flags like are False... | https://github.com/huggingface/transformers.git | def to_numpy_array(self, image, rescale=None, channel_first=True):
self._ensure_format_supported(image)
if isinstance(image, PIL.Image.Image):
image = np.array(image)
if is_torch_tensor(image):
image = image.numpy()
rescale = isinstance(image.flat[0], ... | 123 | image_utils.py | Python | src/transformers/image_utils.py | 49e44b216b2559e34e945d5dcdbbe2238859e29b | transformers | 7 | |
60,149 | 29 | 11 | 21 | 91 | 14 | 0 | 37 | 115 | _get_cluster_uid | Add `PREFECT_KUBERNETES_CLUSTER_UID` to allow bypass of `kube-system` namespace read (#7864)
Co-authored-by: Peyton <44583861+peytonrunyan@users.noreply.github.com> | https://github.com/PrefectHQ/prefect.git | def _get_cluster_uid(self) -> str:
# Default to an environment variable
env_cluster_uid = os.environ.get("PREFECT_KUBERNETES_CLUSTER_UID")
if env_cluster_uid:
return env_cluster_uid
# Read the UID from the cluster namespace
with self.get_client() as client:
... | 49 | kubernetes.py | Python | src/prefect/infrastructure/kubernetes.py | 9ab65f6480a31ba022d9846fdfbfca1d17da8164 | prefect | 2 | |
101,231 | 10 | 7 | 4 | 35 | 5 | 0 | 11 | 32 | affine_matrix | 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 | https://github.com/deepfakes/faceswap.git | def affine_matrix(self) -> np.ndarray:
assert self._affine_matrix is not None
return self._affine_matrix
| 21 | detected_face.py | Python | lib/align/detected_face.py | 5e73437be47f2410439a3c6716de96354e6a0c94 | faceswap | 1 | |
119,979 | 9 | 9 | 3 | 48 | 8 | 0 | 10 | 38 | bcoo_dot_general | [sparse] Update docstrings for bcoo primitives.
PiperOrigin-RevId: 438685829 | https://github.com/google/jax.git | def bcoo_dot_general(lhs, rhs, *, dimension_numbers):
return _bcoo_dot_general(*lhs._bufs, rhs, dimension_numbers=dimension_numbers,
lhs_spinfo=lhs._info)
| 32 | bcoo.py | Python | jax/experimental/sparse/bcoo.py | 3184dd65a222354bffa2466d9a375162f5649132 | jax | 1 | |
146,202 | 4 | 8 | 2 | 24 | 4 | 0 | 4 | 18 | __len__ | [serve] Implement Serve Application object (#22917)
The concept of a Serve Application, a data structure containing all information needed to deploy Serve on a Ray cluster, has surfaced during recent design discussions. This change introduces a formal Application data structure and refactors existing code to use it. | https://github.com/ray-project/ray.git | def __len__(self):
return len(self._deployments)
| 13 | application.py | Python | python/ray/serve/application.py | 1100c982223757f697a410a0d0c3d8bf3ff9c805 | ray | 1 | |
180,540 | 9 | 8 | 20 | 34 | 3 | 0 | 9 | 18 | update | Add gr.update to blocks guide (#1649)
* Add gr.update to guide
* Add to docs page and add step-by-step guide
* Fix documentation tests
* PR reviews
* Use code snippet
* Make section title plural
* Blocks utils in their own section | https://github.com/gradio-app/gradio.git | def update(**kwargs) -> dict:
kwargs["__type__"] = "generic_update"
return kwargs
| 17 | blocks.py | Python | gradio/blocks.py | de4458361b359e2333d8d265cb3c57b91bec513b | gradio | 1 | |
160,534 | 7 | 7 | 34 | 48 | 14 | 2 | 7 | 10 | traverse | ENH: Support character string arrays
TST: added test for issue #18684
ENH: f2py opens files with correct encoding, fixes #635
TST: added test for issue #6308
TST: added test for issue #4519
TST: added test for issue #3425
ENH: Implement user-defined hooks support for post-processing f2py data structure. Implement... | https://github.com/numpy/numpy.git | def traverse(obj, visit, parents=[], result=None, *args, **kwargs):
| '''Traverse f2py data structurethe following visit | 238 | crackfortran.py | Python | numpy/f2py/crackfortran.py | d4e11c7a2eb64861275facb076d47ccd135fa28c | numpy | 11 |
100,575 | 21 | 11 | 14 | 79 | 11 | 0 | 22 | 65 | _get_free_vram | Refactor lib.gpu_stats (#1218)
* inital gpu_stats refactor
* Add dummy CPU Backend
* Update Sphinx documentation | https://github.com/deepfakes/faceswap.git | def _get_free_vram(self) -> List[float]:
vram = [pynvml.nvmlDeviceGetMemoryInfo(handle).free / (1024 * 1024)
for handle in self._handles]
self._log("debug", f"GPU VRAM free: {vram}")
return vram
| 46 | nvidia.py | Python | lib/gpu_stats/nvidia.py | bdbbad4d310fb606b6f412aa81e9f57ccd994e97 | faceswap | 2 | |
147,590 | 8 | 6 | 7 | 31 | 6 | 1 | 8 | 21 | __getstate__ | [RLlib] AlphaStar polishing (fix logger.info bug). (#22281) | https://github.com/ray-project/ray.git | def __getstate__(self) -> Dict[str, Any]:
return {}
@ExperimentalAPI | @ExperimentalAPI | 16 | league_builder.py | Python | rllib/agents/alpha_star/league_builder.py | 0bb82f29b65dca348acf5aa516d21ef3f176a3e1 | ray | 1 |
140,529 | 8 | 9 | 3 | 36 | 7 | 0 | 9 | 18 | create_gloo_context | Clean up docstyle in python modules and add LINT rule (#25272) | https://github.com/ray-project/ray.git | def create_gloo_context(rank, world_size):
context = pygloo.rendezvous.Context(rank, world_size)
return context
| 22 | gloo_util.py | Python | python/ray/util/collective/collective_group/gloo_util.py | 905258dbc19753c81039f993477e7ab027960729 | ray | 1 | |
111,759 | 4 | 6 | 2 | 16 | 2 | 0 | 4 | 18 | configure_architecture_optimizers | Lightning implementation for retiarii oneshot nas (#4479) | https://github.com/microsoft/nni.git | def configure_architecture_optimizers(self):
return None
| 8 | base_lightning.py | Python | nni/retiarii/oneshot/pytorch/base_lightning.py | 8b2eb425274cdb4537fbce4a315aec12a378d6db | nni | 1 | |
19,662 | 32 | 15 | 14 | 137 | 13 | 0 | 47 | 196 | safe_import | Issue 4993 Add standard pre commit hooks and apply linting. (#4994)
* Add .pre-commit-config.yaml to the project and exclude tests (for now). This does not include the MyPy linting that pip does but does include everything else. | https://github.com/pypa/pipenv.git | def safe_import(self, name):
# type: (str) -> ModuleType
module = None
if name not in self._modules:
self._modules[name] = importlib.import_module(name)
module = self._modules[name]
if not module:
dist = next(
iter(dist for dist in... | 86 | environment.py | Python | pipenv/environment.py | 9a3b3ce70621af6f9adaa9eeac9cf83fa149319c | pipenv | 6 | |
266,096 | 39 | 13 | 17 | 149 | 21 | 0 | 51 | 293 | _instantiate_components | #10694: Emit post_save signal when creating/updating device components in bulk (#10900)
* Emit post_save signal when creating/updating device components in bulk
* Fix post_save for bulk_update() | https://github.com/netbox-community/netbox.git | def _instantiate_components(self, queryset, bulk_create=True):
components = [obj.instantiate(device=self) for obj in queryset]
if components and bulk_create:
model = components[0]._meta.model
model.objects.bulk_create(components)
# Manually send the post_save... | 97 | devices.py | Python | netbox/dcim/models/devices.py | a57c937aaa565222c21ae8629103070bd5f43c45 | netbox | 7 | |
104,392 | 4 | 7 | 2 | 22 | 3 | 0 | 4 | 18 | num_columns | Update docs to new frontend/UI (#3690)
* WIP: update docs to new UI
* make style
* Rm unused
* inject_arrow_table_documentation __annotations__
* hasattr(arrow_table_method, "__annotations__")
* Update task_template.rst
* Codeblock PT-TF-SPLIT
* Convert loading scripts
* Convert docs to mdx
... | https://github.com/huggingface/datasets.git | def num_columns(self):
return self.table.num_columns
| 12 | table.py | Python | src/datasets/table.py | e35be138148333078284b942ccc9ed7b1d826f97 | datasets | 1 | |
297,903 | 71 | 19 | 26 | 175 | 21 | 0 | 89 | 657 | _devices | String formatting and max line length - Part 3 (#84394) | https://github.com/home-assistant/core.git | def _devices(self, device_type):
try:
for structure in self.nest.structures:
if structure.name not in self.local_structure:
_LOGGER.debug(
"Ignoring structure %s, not in %s",
structure.name,
... | 107 | __init__.py | Python | homeassistant/components/nest/legacy/__init__.py | baef267f335b95ec30cf8791f74e199a104e8148 | core | 6 | |
271,500 | 20 | 13 | 10 | 103 | 13 | 0 | 42 | 112 | clear_previously_created_nodes | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def clear_previously_created_nodes(layer, created_nodes):
for node in layer._inbound_nodes:
prev_layers = node.inbound_layers
for prev_layer in tf.nest.flatten(prev_layers):
prev_layer._outbound_nodes = [
n for n in prev_layer._outbound_nodes if n not in created_node... | 68 | sequential.py | Python | keras/engine/sequential.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 7 | |
120,508 | 31 | 9 | 6 | 78 | 12 | 1 | 31 | 65 | polar_unitary | Change implementation of jax.scipy.linalg.polar() and jax._src.scipy.eigh to use the QDWH decomposition from jax._src.lax.qdwh.
Remove jax._src.lax.polar.
PiperOrigin-RevId: 448241206 | https://github.com/google/jax.git | def polar_unitary(a, *, method="qdwh", eps=None, max_iterations=None):
# TODO(phawkins): delete this function after 2022/8/11.
warnings.warn("jax.scipy.linalg.polar_unitary is deprecated. Call "
"jax.scipy.linalg.polar instead.",
DeprecationWarning)
unitary, _ = polar(a, method,... | @jit | 45 | linalg.py | Python | jax/_src/scipy/linalg.py | 7ba36fc1784a7a286aa13ab7c098f84ff64336f1 | jax | 1 |
157,209 | 54 | 15 | 30 | 335 | 15 | 0 | 93 | 371 | sorted_columns | Remove statistics-based set_index logic from read_parquet (#9661) | https://github.com/dask/dask.git | def sorted_columns(statistics, columns=None):
if not statistics:
return []
out = []
for i, c in enumerate(statistics[0]["columns"]):
if columns and c["name"] not in columns:
continue
if not all(
"min" in s["columns"][i] and "max" in s["columns"][i] for s... | 196 | core.py | Python | dask/dataframe/io/parquet/core.py | 945435bfebc223f9a0ca013fc8163801e789caab | dask | 12 | |
5,820 | 28 | 18 | 21 | 163 | 15 | 0 | 44 | 239 | get_number_of_posts | PR - Fix `extract_text_from_element()`and `find_element*()` to `find_element()` (#6438)
* Updated getUserData() and find_element*
Signed-off-by: elulcao <elulcao@icloud.com>
Thanks @breuerfelix for reviewing, 🚀
People in this thread please let me know if something is not OK, IG changed a lot these days. 🤗 @her | https://github.com/InstaPy/InstaPy.git | def get_number_of_posts(browser):
try:
num_of_posts = getUserData(
"graphql.user.edge_owner_to_timeline_media.count", browser
)
except WebDriverException:
try:
num_of_posts_txt = browser.find_element(
By.XPATH, read_xpath(get_number_of_posts._... | 95 | util.py | Python | instapy/util.py | 2a157d452611d37cf50ccb7d56ff1a06e9790ecb | InstaPy | 3 | |
131,786 | 78 | 14 | 61 | 521 | 35 | 0 | 130 | 799 | testRequestResourcesRaceConditionWithResourceDemands | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | https://github.com/ray-project/ray.git | def testRequestResourcesRaceConditionWithResourceDemands(self):
config = copy.deepcopy(MULTI_WORKER_CLUSTER)
config["available_node_types"].update(
{
"empty_node": {
"node_config": {},
"resources": {"CPU": 2, "GPU": 1},
... | 310 | test_resource_demand_scheduler.py | Python | python/ray/tests/test_resource_demand_scheduler.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 3 | |
181,658 | 19 | 12 | 11 | 92 | 17 | 0 | 20 | 89 | test_k_fold_cv | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | https://github.com/EpistasisLab/tpot.git | def test_k_fold_cv():
boston = load_boston()
clf = make_pipeline(
OneHotEncoder(
categorical_features='auto',
sparse=False,
minimum_fraction=0.05
),
LinearRegression()
)
cross_val_score(clf, boston.data, boston.target, cv=KFold(n_splits=1... | 60 | one_hot_encoder_tests.py | Python | tests/one_hot_encoder_tests.py | 388616b6247ca4ea8de4e2f340d6206aee523541 | tpot | 1 | |
151,282 | 11 | 10 | 5 | 43 | 4 | 0 | 13 | 56 | get_trade_duration | improve typing, improve docstrings, ensure global tests pass | https://github.com/freqtrade/freqtrade.git | def get_trade_duration(self):
if self._last_trade_tick is None:
return 0
else:
return self._current_tick - self._last_trade_tick
| 25 | BaseEnvironment.py | Python | freqtrade/freqai/RL/BaseEnvironment.py | 77c360b264c9dee489081c2761cc3be4ba0b01d1 | freqtrade | 2 | |
31,755 | 14 | 8 | 4 | 45 | 6 | 0 | 19 | 54 | project_group_token | Adding GroupViT Models (#17313)
* add group vit and fixed test (except slow)
* passing slow test
* addressed some comments
* fixed test
* fixed style
* fixed copy
* fixed segmentation output
* fixed test
* fixed relative path
* fixed copy
* add ignore non auto configured
* fixed docstr... | https://github.com/huggingface/transformers.git | def project_group_token(self, group_tokens):
# [B, num_output_groups, C] <- [B, num_group_tokens, C]
projected_group_tokens = self.mlp_inter(group_tokens)
projected_group_tokens = self.norm_post_tokens(projected_group_tokens)
return projected_group_tokens
| 26 | modeling_groupvit.py | Python | src/transformers/models/groupvit/modeling_groupvit.py | 6c8f4c9a938a09749ea1b19a5fa2a8dd27e99a29 | transformers | 1 | |
84,160 | 21 | 11 | 12 | 128 | 15 | 0 | 25 | 88 | test_removed_file_download | tests: Refactor away result.json() calls with helpers.
Signed-off-by: Zixuan James Li <p359101898@gmail.com> | https://github.com/zulip/zulip.git | def test_removed_file_download(self) -> None:
self.login("hamlet")
fp = StringIO("zulip!")
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
response_dict = self.assert_json_success(result)
destroy_uploads()
response = ... | 71 | test_upload.py | Python | zerver/tests/test_upload.py | a142fbff85302c5e3acb2e204eca2e9c75dbc74b | zulip | 1 | |
266,774 | 39 | 17 | 15 | 232 | 31 | 0 | 51 | 217 | delegate | ansible-test - Code cleanup and refactoring. (#77169)
* Remove unnecessary PyCharm ignores.
* Ignore intentional undefined attribute usage.
* Add missing type hints. Fix existing type hints.
* Fix docstrings and comments.
* Use function to register completion handler.
* Pass strings to display functions.
* Fix C... | https://github.com/ansible/ansible.git | def delegate(args, host_state, exclude, require): # type: (CommonConfig, HostState, t.List[str], t.List[str]) -> None
assert isinstance(args, EnvironmentConfig)
with delegation_context(args, host_state):
if isinstance(args, TestConfig):
args.metadata.ci_provider = get_ci_provider().co... | 146 | delegation.py | Python | test/lib/ansible_test/_internal/delegation.py | a06fa496d3f837cca3c437ab6e9858525633d147 | ansible | 3 | |
108,967 | 65 | 16 | 25 | 399 | 31 | 0 | 94 | 508 | set_aspect | Add equalxy, equalyz, equalxz aspect ratios
Update docstrings | https://github.com/matplotlib/matplotlib.git | def set_aspect(self, aspect, adjustable=None, anchor=None, share=False):
_api.check_in_list(('auto', 'equal', 'equalxy', 'equalyz', 'equalxz'),
aspect=aspect)
super().set_aspect(
aspect='auto', adjustable=adjustable, anchor=anchor, share=share)
if... | 255 | axes3d.py | Python | lib/mpl_toolkits/mplot3d/axes3d.py | 31d13198ecf6969b1b693c28a02b0805f3f20420 | matplotlib | 8 | |
155,478 | 43 | 17 | 23 | 305 | 12 | 0 | 86 | 392 | slice_shift | REFACTOR-#3948: Use `__constructor__` in `DataFrame` and `Series` classes (#5485)
Signed-off-by: Anatoly Myachev <anatoly.myachev@intel.com> | https://github.com/modin-project/modin.git | def slice_shift(self, periods=1, axis=0): # noqa: PR01, RT01, D200
if periods == 0:
return self.copy()
if axis == "index" or axis == 0:
if abs(periods) >= len(self.index):
return self.__constructor__(columns=self.columns)
else:
... | 194 | dataframe.py | Python | modin/pandas/dataframe.py | b541b6c18e6fb4515e998b9b4f88528490cf69c6 | modin | 10 | |
87,444 | 48 | 12 | 11 | 143 | 25 | 1 | 53 | 113 | derive_missing_codemappings | feat(code-mappings): Add task to derive missing code mappings (#40528)
Add task to derive and save missing code mappings.
Fixes WOR-2236 | https://github.com/getsentry/sentry.git | def derive_missing_codemappings(dry_run=False) -> None:
organizations = Organization.objects.filter(status=OrganizationStatus.ACTIVE)
for _, organization in enumerate(
RangeQuerySetWrapper(organizations, step=1000, result_value_getter=lambda item: item.id)
):
if not features.has("organi... | @instrumented_task( # type: ignore
name="sentry.tasks.derive_code_mappings.derive_code_mappings",
queue="derive_code_mappings",
max_retries=0, # if we don't backfill it this time, we'll get it the next time
) | 70 | derive_code_mappings.py | Python | src/sentry/tasks/derive_code_mappings.py | c1b7994345096b15efff054341ce569dea57e76b | sentry | 3 |
287,933 | 5 | 6 | 21 | 17 | 2 | 0 | 5 | 12 | _async_update_data | Enable the move firmware effect on multizone lights (#78918)
Co-authored-by: J. Nick Koston <nick@koston.org> | https://github.com/home-assistant/core.git | async def _async_update_data(self) -> None:
| 152 | coordinator.py | Python | homeassistant/components/lifx/coordinator.py | 691028dfb4947f28c5a30e6e2d135404ac0a0a60 | core | 8 | |
13,866 | 23 | 11 | 7 | 69 | 7 | 0 | 24 | 108 | close | feat: dynamic batching (#5410)
Co-authored-by: Johannes Messner <messnerjo@gmail.com>
Co-authored-by: Alaeddine Abdessalem <alaeddine-13@live.fr> | https://github.com/jina-ai/jina.git | async def close(self):
if not self._is_closed:
# debug print amount of requests to be processed.
self._flush_trigger.set()
if self._flush_task:
await self._flush_task
self._cancel_timer_if_pending()
self._is_closed = True
| 38 | batch_queue.py | Python | jina/serve/runtimes/worker/batch_queue.py | 46d7973043e2e599149812cc6fc7671b935c13f8 | jina | 3 | |
21,784 | 8 | 7 | 3 | 28 | 6 | 0 | 8 | 22 | is_bare | Update tomlkit==0.9.2
Used:
python -m invoke vendoring.update --package=tomlkit | https://github.com/pypa/pipenv.git | def is_bare(self) -> bool:
return self.t == KeyType.Bare
| 16 | items.py | Python | pipenv/vendor/tomlkit/items.py | 8faa74cdc9da20cfdcc69f5ec29b91112c95b4c9 | pipenv | 1 | |
291,386 | 10 | 7 | 3 | 38 | 6 | 0 | 10 | 24 | async_get_triggers | Fix homekit controller triggers not attaching when integration is setup after startup (#82717)
fixes https://github.com/home-assistant/core/issues/78852 | https://github.com/home-assistant/core.git | def async_get_triggers(self) -> Generator[tuple[str, str], None, None]:
yield from self._triggers
| 25 | device_trigger.py | Python | homeassistant/components/homekit_controller/device_trigger.py | 05f89efd2c0f0d954897b2e1d43ec2a8505cb33a | core | 1 | |
20 | 7 | 6 | 17 | 26 | 4 | 1 | 7 | 20 | get_protobuf_schema | MOVE GetAllRequestsMessage and GetAllRequestsResponseMessage to the proper message file | https://github.com/OpenMined/PySyft.git | def get_protobuf_schema() -> GeneratedProtocolMessageType:
return GetAllRequestsMessage_PB
@serializable() | @serializable() | 9 | object_request_messages.py | Python | packages/syft/src/syft/core/node/common/node_service/object_request/object_request_messages.py | 05edf746cf5742b562996cf1a319b404152960e5 | PySyft | 1 |
241,753 | 106 | 11 | 72 | 644 | 30 | 1 | 249 | 763 | test_fx_validator_integration | Add `LightningModule.lr_scheduler_step` (#10249)
Co-authored-by: Carlos Mocholi <carlossmocholi@gmail.com> | https://github.com/Lightning-AI/lightning.git | def test_fx_validator_integration(tmpdir):
not_supported = {
None: "`self.trainer` reference is not registered",
"on_before_accelerator_backend_setup": "You can't",
"setup": "You can't",
"configure_sharded_model": "You can't",
"on_configure_sharded_model": "You can't",
... | @RunIf(min_gpus=2) | 322 | test_logger_connector.py | Python | tests/trainer/logging_/test_logger_connector.py | 82c8875f33addb0becd7761c95e9674ccc98c7ee | lightning | 2 |
140,584 | 20 | 17 | 11 | 108 | 13 | 1 | 25 | 105 | unbatch | Clean up docstyle in python modules and add LINT rule (#25272) | https://github.com/ray-project/ray.git | def unbatch(batches_struct):
flat_batches = tree.flatten(batches_struct)
out = []
for batch_pos in range(len(flat_batches[0])):
out.append(
tree.unflatten_as(
batches_struct,
[flat_batches[i][batch_pos] for i in range(len(flat_batches))],
... | @DeveloperAPI | 66 | space_utils.py | Python | rllib/utils/spaces/space_utils.py | 905258dbc19753c81039f993477e7ab027960729 | ray | 3 |
286,314 | 10 | 10 | 2 | 39 | 6 | 0 | 11 | 20 | text_adjustment_len | [SDK] Allow silencing verbose output in commands that use stocks/load (#3180)
* remove verbose on load
* Revert implementation of the verbosity setting in stocks controller
* Edit docstrings to comply with pydocstyle linting rules
* Fix typos in variable names and help text
* Add verbosity setting to forex... | https://github.com/OpenBB-finance/OpenBBTerminal.git | def text_adjustment_len(self, text):
# return compat.strlen(self.ansi_regx.sub("", text), encoding=self.encoding)
return len(self.ansi_regx.sub("", text))
| 22 | helper_funcs.py | Python | openbb_terminal/helper_funcs.py | 47549cbd9f52a436c06b040fda5b88a7d2bf700a | OpenBBTerminal | 1 | |
301,831 | 21 | 14 | 10 | 79 | 10 | 0 | 23 | 121 | async_sync_entities_all | Sync entities when enabling/disabling Google Assistant (#72791) | https://github.com/home-assistant/core.git | async def async_sync_entities_all(self):
if not self._store.agent_user_ids:
return 204
res = await gather(
*(
self.async_sync_entities(agent_user_id)
for agent_user_id in self._store.agent_user_ids
)
)
return m... | 48 | helpers.py | Python | homeassistant/components/google_assistant/helpers.py | 6d74149f22e7211173412682d999b500ccbeff42 | core | 3 | |
46,224 | 60 | 15 | 35 | 361 | 47 | 0 | 91 | 502 | test_deactivate_stale_dags | Reduce DB load incurred by Stale DAG deactivation (#21399)
Deactivating stale DAGs periodically in bulk
By moving this logic into the DagFileProcessorManager and running it across all processed file periodically, we can prevent the use of un-indexed queries.
The basic logic is that we can look at the last proces... | https://github.com/apache/airflow.git | def test_deactivate_stale_dags(self):
manager = DagFileProcessorManager(
dag_directory='directory',
max_runs=1,
processor_timeout=timedelta(minutes=10),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode... | 226 | test_manager.py | Python | tests/dag_processing/test_manager.py | f309ea78f7d8b62383bc41eac217681a0916382b | airflow | 1 | |
6,278 | 7 | 7 | 2 | 35 | 6 | 0 | 8 | 14 | sparsemax_loss | Removes dependency on entmax from PyPI, adds entmax source to utils (#1778)
* Removes dependency on entmax from PyPi, add entmax source code into utils instead.
* Removes build status and image from README
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
... | https://github.com/ludwig-ai/ludwig.git | def sparsemax_loss(X, target, k=None):
return SparsemaxLossFunction.apply(X, target, k)
| 23 | losses.py | Python | ludwig/utils/entmax/losses.py | 20a8a6fdb516e543d4598c852063ba0fb407f3ba | ludwig | 1 | |
247,607 | 6 | 7 | 10 | 34 | 4 | 0 | 6 | 27 | test_can_create_as_private_room_after_rejection | Add type hints to some tests/handlers files. (#12224) | https://github.com/matrix-org/synapse.git | def test_can_create_as_private_room_after_rejection(self) -> None:
self.test_denied_without_publication_permission()
self.test_allowed_when_creating_private_room()
| 18 | test_directory.py | Python | tests/handlers/test_directory.py | 5dd949bee6158a8b651db9f2ae417a62c8184bfd | synapse | 1 | |
100,709 | 62 | 14 | 36 | 297 | 24 | 0 | 90 | 372 | _total_stats | Bugfixes:
- Stats graph - Handle NaNs in data
- logger - de-elevate matplotlib font messages | https://github.com/deepfakes/faceswap.git | def _total_stats(self) -> dict:
logger.debug("Compiling Totals")
elapsed = 0
examples = 0
iterations = 0
batchset = set()
total_summaries = len(self._per_session_stats)
for idx, summary in enumerate(self._per_session_stats):
if idx == 0:
... | 172 | stats.py | Python | lib/gui/analysis/stats.py | afec52309326304f4323029039e49bfcf928ef43 | faceswap | 6 | |
175,317 | 20 | 10 | 9 | 104 | 17 | 0 | 25 | 64 | global_enum | bpo-40066: [Enum] update str() and format() output (GH-30582)
Undo rejected PEP-663 changes:
- restore `repr()` to its 3.10 status
- restore `str()` to its 3.10 status
New changes:
- `IntEnum` and `IntFlag` now leave `__str__` as the original `int.__str__` so that str() and format() return the same result
... | https://github.com/python/cpython.git | def global_enum(cls, update_str=False):
if issubclass(cls, Flag):
cls.__repr__ = global_flag_repr
else:
cls.__repr__ = global_enum_repr
if not issubclass(cls, ReprEnum) or update_str:
cls.__str__ = global_str
sys.modules[cls.__module__].__dict__.update(cls.__members__)
r... | 65 | enum.py | Python | Lib/enum.py | acf7403f9baea3ae1119fc6b4a3298522188bf96 | cpython | 4 | |
292,545 | 8 | 6 | 2 | 26 | 5 | 0 | 8 | 15 | device_info | Expose Samsung wrapper as async (#67042)
Co-authored-by: epenet <epenet@users.noreply.github.com> | https://github.com/home-assistant/core.git | async def async_device_info(self) -> dict[str, Any] | None:
| 15 | bridge.py | Python | homeassistant/components/samsungtv/bridge.py | a60c37cdb8cc9d0b9bad1dedb92b6068cd9d1244 | core | 1 | |
39,443 | 12 | 11 | 4 | 64 | 9 | 0 | 12 | 28 | lexicographers_mutual_information | Add new item similarity metrics for SAR (#1754)
* Add mutual information similarity in SAR
* Add lexicographers mutual information similarity for SAR
* Add cosine similarity for SAR
* Add inclusion index for SAR
* Typos
* Change SARSingleNode to SAR
* Convert item similarity matrix to np.array
* U... | https://github.com/microsoft/recommenders.git | def lexicographers_mutual_information(cooccurrence):
with np.errstate(invalid="ignore", divide="ignore"):
result = cooccurrence * mutual_information(cooccurrence)
return np.array(result)
| 35 | python_utils.py | Python | recommenders/utils/python_utils.py | 1d7341e93d1f03387699fb3c6ae0b6c0e464296f | recommenders | 1 | |
156,002 | 84 | 12 | 9 | 184 | 23 | 0 | 127 | 178 | slice_with_int_dask_array | absolufy-imports - No relative - PEP8 (#8796)
Conversation in https://github.com/dask/distributed/issues/5889 | https://github.com/dask/dask.git | def slice_with_int_dask_array(x, idx, offset, x_size, axis):
from dask.array.utils import asarray_safe, meta_from_array
idx = asarray_safe(idx, like=meta_from_array(x))
# Needed when idx is unsigned
idx = idx.astype(np.int64)
# Normalize negative indices
idx = np.where(idx < 0, idx + x_s... | 118 | chunk.py | Python | dask/array/chunk.py | cccb9d8d8e33a891396b1275c2448c352ef40c27 | dask | 3 | |
260,773 | 42 | 14 | 15 | 165 | 14 | 0 | 70 | 167 | _compute_n_patches | MAINT Parameter validation for `PatchExtractor` (#24215)
Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr> | https://github.com/scikit-learn/scikit-learn.git | def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None):
n_h = i_h - p_h + 1
n_w = i_w - p_w + 1
all_patches = n_h * n_w
if max_patches:
if isinstance(max_patches, (Integral)) and max_patches < all_patches:
return max_patches
elif isinstance(max_patches, (Integral)... | 106 | image.py | Python | sklearn/feature_extraction/image.py | 5e9fa423011ac793c1e0ec2725486c2a33beae42 | scikit-learn | 8 | |
37,505 | 7 | 10 | 2 | 37 | 5 | 0 | 7 | 13 | require_librosa | Update all require decorators to use skipUnless when possible (#16999) | https://github.com/huggingface/transformers.git | def require_librosa(test_case):
return unittest.skipUnless(is_librosa_available(), "test requires librosa")(test_case)
| 20 | testing_utils.py | Python | src/transformers/testing_utils.py | 57e6464ac9a31156f1c93e59107323e6ec01309e | transformers | 1 | |
166,197 | 8 | 10 | 4 | 41 | 5 | 0 | 8 | 40 | __dlpack__ | ENH: Implement DataFrame interchange protocol (#46141) | https://github.com/pandas-dev/pandas.git | def __dlpack__(self):
if _NUMPY_HAS_DLPACK:
return self._x.__dlpack__()
raise NotImplementedError("__dlpack__")
| 22 | buffer.py | Python | pandas/core/exchange/buffer.py | 90140f055892a46f473bd26affab88a7f171e394 | pandas | 2 | |
40,643 | 37 | 11 | 14 | 231 | 14 | 0 | 54 | 153 | _handle_wrapping | Refactor figure setup and subplot metadata tracking into Subplots class
Squashed commit of the following:
commit e6f99078d46947eab678b9dd0303657a3129f9fc
Author: Michael Waskom <mwaskom@nyu.edu>
Date: Sun Aug 1 17:56:49 2021 -0400
Address a couple TODOs
commit c48ba3af8095973b7dca9554934a695751f58726
Author: ... | https://github.com/mwaskom/seaborn.git | def _handle_wrapping(self) -> None:
self.wrap = wrap = self.facet_spec.get("wrap") or self.pair_spec.get("wrap")
if not wrap:
return
wrap_dim = "row" if self.subplot_spec["nrows"] > 1 else "col"
flow_dim = {"row": "col", "col": "row"}[wrap_dim]
n_subplots = ... | 125 | subplots.py | Python | seaborn/_core/subplots.py | c16180493bd44fd76092fdd9ea0060bac91e47fe | seaborn | 5 | |
145,083 | 9 | 8 | 3 | 34 | 5 | 0 | 9 | 23 | _is_read_stage | [data] Stage fusion optimizations, off by default (#22373)
This PR adds the following stage fusion optimizations (off by default). In a later PR, I plan to enable this by default for DatasetPipelines.
- Stage fusion: Whether to fuse compatible OneToOne stages.
- Read stage fusion: Whether to fuse read stages into do... | https://github.com/ray-project/ray.git | def _is_read_stage(self) -> bool:
return self._has_read_stage() and not self._stages
| 19 | plan.py | Python | python/ray/data/impl/plan.py | 786c5759dee02b57c8e10b39f1c1bed07f05eb5a | ray | 2 | |
150,869 | 49 | 10 | 10 | 169 | 20 | 0 | 67 | 180 | _handle_analyzed_df_message | Refactoring, minor improvements, data provider improvements | https://github.com/freqtrade/freqtrade.git | def _handle_analyzed_df_message(self, type, data):
key, value = data["key"], data["value"]
pair, timeframe, candle_type = key
# Skip any pairs that we don't have in the pairlist?
# leader_pairlist = self._freqtrade.pairlists._whitelist
# if pair not in leader_pairlist:
... | 98 | rpc.py | Python | freqtrade/rpc/rpc.py | 2b5f0678772bea0abaf4abe93efc55de43ea3e0e | freqtrade | 2 | |
249,634 | 20 | 12 | 8 | 128 | 14 | 0 | 26 | 54 | make_request | Indicate what endpoint came back with a JSON response we were unable to parse (#14097)
**Before:**
```
WARNING - POST-11 - Unable to parse JSON: Expecting value: line 1 column 1 (char 0) (b'')
```
**After:**
```
WARNING - POST-11 - Unable to parse JSON from POST /_matrix/client/v3/join/%21ZlmJtelqFroDRJYZaq:hs... | https://github.com/matrix-org/synapse.git | def make_request(content):
request = Mock(spec=["method", "uri", "content"])
if isinstance(content, dict):
content = json.dumps(content).encode("utf8")
request.method = bytes("STUB_METHOD", "ascii")
request.uri = bytes("/test_stub_uri", "ascii")
request.content = BytesIO(content)
... | 71 | test_servlet.py | Python | tests/http/test_servlet.py | 1bf2832714abdfc5e10395e8e76aecc591ad265f | synapse | 2 | |
20,237 | 6 | 8 | 3 | 30 | 5 | 0 | 6 | 20 | site_data_path | check point progress on only bringing in pip==22.0.4 (#4966)
* vendor in pip==22.0.4
* updating vendor packaging version
* update pipdeptree to fix pipenv graph with new version of pip.
* Vendoring of pip-shims 0.7.0
* Vendoring of requirementslib 1.6.3
* Update pip index safety restrictions patch for p... | https://github.com/pypa/pipenv.git | def site_data_path(self) -> Path:
return self._first_item_as_path_if_multipath(self.site_data_dir)
| 17 | unix.py | Python | pipenv/patched/notpip/_vendor/platformdirs/unix.py | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | pipenv | 1 | |
224,014 | 10 | 9 | 2 | 34 | 4 | 0 | 10 | 24 | static_pages | Remove spaces at the ends of docstrings, normalize quotes | https://github.com/mkdocs/mkdocs.git | def static_pages(self):
return [file for file in self if file.is_static_page()]
| 20 | files.py | Python | mkdocs/structure/files.py | e7f07cc82ab2be920ab426ba07456d8b2592714d | mkdocs | 3 | |
195,279 | 13 | 10 | 4 | 60 | 10 | 0 | 15 | 43 | _reshape_tensor | Patch 8322 (#4709)
* add dafetymix teacher
* safety_mix teacher
* safety_mix teacher pos and neg teachers
* add tests for teacher
* add license info
* improvement
* add task list
* add task list and lint
* add init.py
* adding some patch to director
* seeker changes
* th
* 3
* ji... | https://github.com/facebookresearch/ParlAI.git | def _reshape_tensor(self, new_len, tensor, indices):
reshaped_tensor = torch.zeros(new_len, device=tensor.device, dtype=tensor.dtype)
reshaped_tensor[indices] = tensor
return reshaped_tensor
| 40 | director_bb2.py | Python | projects/fits/agents/director_bb2.py | b1acb681207559da56a787ba96e16f0e23697d92 | ParlAI | 1 | |
268,987 | 17 | 9 | 5 | 98 | 10 | 0 | 21 | 26 | binary_matches | Added util metric method for binary_matches. Decoupled from public metric binarry_acc | https://github.com/keras-team/keras.git | 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) | 66 | metrics_utils.py | Python | keras/utils/metrics_utils.py | 119cd4655d01570a70c70879dff4461ea46161bf | keras | 1 | |
265,023 | 34 | 16 | 13 | 159 | 22 | 0 | 39 | 198 | draw_terminations | Update SVG trace rendering to support multiple terminations per cable end | https://github.com/netbox-community/netbox.git | def draw_terminations(self, terminations):
x = self.width / 2 - len(terminations) * TERMINATION_WIDTH / 2
for i, term in enumerate(terminations):
t = self._draw_box(
x=x + i * TERMINATION_WIDTH,
width=TERMINATION_WIDTH,
color=self._get... | 104 | cables.py | Python | netbox/dcim/svg/cables.py | bab6fb0de24d568371c8a55bcb22768b2d60f515 | netbox | 2 | |
210,756 | 44 | 13 | 23 | 318 | 36 | 0 | 58 | 260 | predict | Develop branch: add fight action for pphuman (#6160)
* add fight for PP-Human
* add short_size and target_size for fight recognition
* add short_size and target_size for fight_infer
* modify code according to the reviews
* add the wrong deleted lines`
* Update pipeline.py
* Update infer_cfg.yml
* ... | https://github.com/PaddlePaddle/PaddleDetection.git | def predict(self, input):
input_names = self.predictor.get_input_names()
input_tensor = self.predictor.get_input_handle(input_names[0])
output_names = self.predictor.get_output_names()
output_tensor = self.predictor.get_output_handle(output_names[0])
# preprocess
... | 193 | video_action_infer.py | Python | deploy/python/video_action_infer.py | 67f16ed9cac254612ddb141fcd8a14db3dbfd6d6 | PaddleDetection | 2 | |
248,620 | 19 | 9 | 7 | 82 | 13 | 0 | 20 | 55 | test_left_room | Add more tests for room upgrades (#13074)
Signed-off-by: Sean Quah <seanq@element.io> | https://github.com/matrix-org/synapse.git | def test_left_room(self) -> None:
# Remove the user from the room.
self.helper.leave(self.room_id, self.creator, tok=self.creator_token)
channel = self._upgrade_room(self.creator_token)
self.assertEqual(403, channel.code, channel.result)
| 52 | test_upgrade_room.py | Python | tests/rest/client/test_upgrade_room.py | 99d3931974e65865d1102ee79d7b7e2b017a3180 | synapse | 1 | |
308,789 | 30 | 13 | 14 | 100 | 8 | 0 | 35 | 141 | test_secure_device_pin_config | Enable local fulfillment google assistant (#63218)
Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io> | https://github.com/home-assistant/core.git | async def test_secure_device_pin_config(hass):
secure_pin = "TEST"
secure_config = GOOGLE_ASSISTANT_SCHEMA(
{
"project_id": "1234",
"service_account": {
"private_key": "-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKYscIlwm7soD... | 51 | test_http.py | Python | tests/components/google_assistant/test_http.py | 25fe213f222f8f49a8126130a8e507fa15e63c83 | core | 1 | |
100,406 | 129 | 17 | 38 | 534 | 43 | 0 | 182 | 654 | conda_installer | 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 -... | https://github.com/deepfakes/faceswap.git | def conda_installer(self, package, channel=None, verbose=False, conda_only=False):
# Packages with special characters need to be enclosed in double quotes
success = True
condaexe = ["conda", "install", "-y"]
if not verbose or self.env.updater:
condaexe.append("-q")
... | 298 | setup.py | Python | setup.py | c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf | faceswap | 14 | |
271,587 | 4 | 6 | 3 | 22 | 4 | 0 | 4 | 7 | reduce_per_replica | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def reduce_per_replica(values, strategy, reduction="first"):
| 25 | training.py | Python | keras/engine/training.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 1 | |
321,496 | 12 | 9 | 3 | 58 | 10 | 0 | 12 | 33 | test_empty_message | Fix missed enum scope changes
For some reason, QtMsgType was not included and missing.
(cherry picked from commit 6afa00c465327a118dbcff46fa85b6df53037263)
For completiondelegate.py, we accessed the enum members via self instead of
properly using the class.
(cherry picked from commit d37cc4ac73545c6a2615456a3487536c2... | https://github.com/qutebrowser/qutebrowser.git | def test_empty_message(self, caplog):
log.qt_message_handler(QtCore.QtMsgType.QtDebugMsg, self.Context(), "")
assert caplog.messages == ["Logged empty message!"]
| 34 | test_log.py | Python | tests/unit/utils/test_log.py | 76f9262defc0217289443467927cab7c211aff73 | qutebrowser | 1 | |
118,573 | 65 | 12 | 25 | 189 | 23 | 0 | 87 | 359 | serialize_final_report_to_files | Rename and refactor `Report` machinery (#4141)
This refactor renames (almost) everything related to the outdated "report" concept with more precise concepts that we use throughout our code, primarily "script run", "session", and "app". | https://github.com/streamlit/streamlit.git | def serialize_final_report_to_files(self):
LOGGER.debug("Serializing final report")
messages = [
copy.deepcopy(msg)
for msg in self._master_queue
if _should_save_report_msg(msg)
]
manifest = self._build_manifest(
status=StaticMan... | 113 | session_data.py | Python | lib/streamlit/session_data.py | 704eab3478cf69847825b23dabf15813a8ac9fa2 | streamlit | 4 | |
85,884 | 77 | 12 | 54 | 425 | 42 | 0 | 107 | 667 | test_sends_issue_notification | chore(notification): Pass User ID into notification analytics (#38924)
We pass in the actor_id to notification analytics events but we should
also include a user_id if the recipient is a user | https://github.com/getsentry/sentry.git | def test_sends_issue_notification(self, record_analytics):
action_data = {
"id": "sentry.mail.actions.NotifyEmailAction",
"targetType": "Member",
"targetIdentifier": str(self.user.id),
}
Rule.objects.create(
project=self.project,
... | 254 | test_notifications.py | Python | tests/sentry/notifications/test_notifications.py | afbf9a3334ce9cad1a62fced372d7fcee40a3133 | sentry | 1 | |
313,646 | 29 | 10 | 5 | 91 | 15 | 0 | 30 | 49 | test_no_recursive_secrets | Significantly improve yaml load times when the C loader is available (#73337) | https://github.com/home-assistant/core.git | def test_no_recursive_secrets(caplog, try_both_loaders):
files = {YAML_CONFIG_FILE: "key: !secret a", yaml.SECRET_YAML: "a: 1\nb: !secret a"}
with patch_yaml_files(files), pytest.raises(HomeAssistantError) as e:
load_yaml_config_file(YAML_CONFIG_FILE)
assert e.value.args == ("Secrets not suppo... | 51 | test_init.py | Python | tests/util/yaml/test_init.py | dca4d3cd61d7f872621ee4021450cc6a0fbd930e | core | 1 | |
271,435 | 43 | 16 | 14 | 133 | 12 | 0 | 53 | 207 | dtype | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def dtype(self):
type_spec = self._type_spec
if not hasattr(type_spec, "dtype"):
raise AttributeError(
f"KerasTensor wraps TypeSpec {type(type_spec).__qualname__}, "
"which does not have a dtype."
)
if not isinstance(type_spec.dtyp... | 53 | keras_tensor.py | Python | keras/engine/keras_tensor.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 3 | |
5,880 | 88 | 11 | 46 | 393 | 41 | 0 | 117 | 366 | test_visualization_compare_classifiers_changing_k_output_pdf | Use tempfile to automatically garbage collect data and modeling artifacts in ludwig integration tests. (#1642)
* Use tmpdir to automatically garbage collect data and modeling artifacts in ludwig integration tests. | https://github.com/ludwig-ai/ludwig.git | def test_visualization_compare_classifiers_changing_k_output_pdf(csv_filename):
input_features = [category_feature(vocab_size=10)]
output_features = [category_feature(vocab_size=2, reduce_input="sum")]
# Generate test data
rel_path = generate_data(input_features, output_features, csv_filename)
... | 238 | test_visualization.py | Python | tests/integration_tests/test_visualization.py | 4fb8f63181f5153b4f6778c6ef8dad61022c4f3f | ludwig | 2 | |
42,468 | 56 | 16 | 11 | 159 | 18 | 0 | 84 | 174 | sentence_ribes | Update black to 22.3.0
The most recent release of Click (8.1.0) was breaking Black. See psf/black#2964 | https://github.com/nltk/nltk.git | def sentence_ribes(references, hypothesis, alpha=0.25, beta=0.10):
best_ribes = -1.0
# Calculates RIBES for each reference and returns the best score.
for reference in references:
# Collects the *worder* from the ranked correlation alignments.
worder = word_rank_alignment(reference, hyp... | 108 | ribes_score.py | Python | nltk/translate/ribes_score.py | 0fac0c0f8e4618c2bdd3d2137d5fb8a80f581246 | nltk | 3 | |
159,094 | 13 | 9 | 6 | 70 | 9 | 0 | 15 | 33 | test_cli_missing_log_level_env_var_used | Configurable logging for libraries (#10614)
* Make library level logging to be configurable
Fixes https://github.com/RasaHQ/rasa/issues/10203
* Create log level documentation under cheatsheet in Rasa docs
* Add log docs to `rasa shell --debug` (and others) | https://github.com/RasaHQ/rasa.git | def test_cli_missing_log_level_env_var_used():
configure_logging_and_warnings()
rasa_logger = logging.getLogger("rasa")
rasa_logger.level == logging.WARNING
matplotlib_logger = logging.getLogger("matplotlib")
matplotlib_logger.level == logging.INFO
| 38 | test_common.py | Python | tests/utils/test_common.py | f00148b089d326c952880a0e5e6bd4b2dcb98ce5 | rasa | 1 | |
64,092 | 15 | 10 | 6 | 70 | 9 | 0 | 19 | 13 | get_indexed_packed_items_table | fix: Linter and minor code refactor
- Create an indexed map of stale packed items table to avoid loops to check if packed item row exists
- Reset packed items if row deletion takes place
- Renamed functions to self-explain them
- Split long function
- Reduce function calls inside function (makes it harder to follow th... | https://github.com/frappe/erpnext.git | def get_indexed_packed_items_table(doc):
indexed_table = {}
for packed_item in doc.get("packed_items"):
key = (packed_item.parent_item, packed_item.item_code, packed_item.parent_detail_docname)
indexed_table[key] = packed_item
return indexed_table
| 43 | packed_item.py | Python | erpnext/stock/doctype/packed_item/packed_item.py | 4c677eafe958a448074b3efc859334c9a088be2c | erpnext | 2 | |
309,832 | 79 | 14 | 39 | 391 | 37 | 0 | 106 | 403 | async_handle_message | Suppress Alexa state reports when not authorized (#64064) | https://github.com/home-assistant/core.git | async def async_handle_message(hass, config, request, context=None, enabled=True):
assert request[API_DIRECTIVE][API_HEADER]["payloadVersion"] == "3"
if context is None:
context = ha.Context()
directive = AlexaDirective(request)
try:
if not enabled:
raise AlexaBridgeU... | 241 | smart_home.py | Python | homeassistant/components/alexa/smart_home.py | e6899416e13214df63ccc5edc035039e318613fe | core | 8 | |
42,549 | 20 | 11 | 5 | 76 | 11 | 0 | 23 | 62 | collocations | 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... | https://github.com/nltk/nltk.git | 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="; "))
| 47 | text.py | Python | nltk/text.py | 8a4cf5d94eb94b6427c5d1d7907ba07b119932c5 | nltk | 2 | |
309,256 | 50 | 15 | 28 | 151 | 12 | 0 | 57 | 329 | test_check_loop_async_integration_non_strict | Warn on`time.sleep` in event loop (#63766)
Co-authored-by: Martin Hjelmare <marhje52@gmail.com> | https://github.com/home-assistant/core.git | async def test_check_loop_async_integration_non_strict(caplog):
with patch(
"homeassistant.util.async_.extract_stack",
return_value=[
Mock(
filename="/home/paulus/homeassistant/core.py",
lineno="23",
line="do_something()",
... | 84 | test_async.py | Python | tests/util/test_async.py | dc58bc375ae203e3d394225f9c3a5a14d43cb2f3 | core | 1 | |
310,240 | 19 | 12 | 7 | 90 | 14 | 0 | 20 | 49 | test_device_diagnostics_error | Add zwave_js device diagnostics (#64504)
* Add zwave_js device diagnostics
* Add diagnostics as a dependency in manifest
* Add failure scenario test
* fix device diagnostics helper and remove dependency
* tweak | https://github.com/home-assistant/core.git | async def test_device_diagnostics_error(hass, integration):
dev_reg = async_get(hass)
device = dev_reg.async_get_or_create(
config_entry_id=integration.entry_id, identifiers={("test", "test")}
)
with pytest.raises(ValueError):
await async_get_device_diagnostics(hass, integration, de... | 53 | test_diagnostics.py | Python | tests/components/zwave_js/test_diagnostics.py | 11d0dcf7ac4ddc2638f403ef0ee6b796ac5bbceb | core | 1 | |
134,330 | 89 | 12 | 25 | 273 | 31 | 1 | 135 | 320 | disconnect | Try fixing the issue. (#29657)
Looks like we are using PyOpenSSL < 22.0 which can cause issues with the newer version of cryptography module that causes AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' . Check boto/botocore#2744
urllib3/urllib3#2680
for more details.
The problem was tha... | https://github.com/ray-project/ray.git | def disconnect(exiting_interpreter=False):
# Reset the list of cached remote functions and actors so that if more
# remote functions or actors are defined and then connect is called again,
# the remote functions will be exported. This is mostly relevant for the
# tests.
worker = global_worker
... | @contextmanager | 151 | worker.py | Python | python/ray/_private/worker.py | bf22325eb518c4a42242a88031909869da003850 | ray | 7 |
266,043 | 11 | 9 | 5 | 56 | 8 | 0 | 13 | 48 | save_object | 4347 Add JSON/YAML import support for all objects (#10367)
* 4347 initial code for json import
* 4347 initial code for json import
* Clean up form processing logic
* Consolidate import forms
* Consolidate object import/update logic
* Clean up bulk import view
Co-authored-by: jeremystretch <jstretch@n... | https://github.com/netbox-community/netbox.git | def save_object(self, obj_form, request):
instance = obj_form.save(commit=False)
instance.user = request.user
instance.save()
return instance
| 34 | views.py | Python | netbox/dcim/views.py | 93e7457e0d84ad24cba22cc5c0811777ddebf94e | netbox | 1 | |
259,101 | 107 | 16 | 31 | 421 | 34 | 0 | 161 | 434 | compute_class_weight | FIX Support extra class_weights in compute_class_weight (#22595) | https://github.com/scikit-learn/scikit-learn.git | def compute_class_weight(class_weight, *, classes, y):
# Import error caused by circular imports.
from ..preprocessing import LabelEncoder
if set(y) - set(classes):
raise ValueError("classes should include all valid labels that can be in y")
if class_weight is None or len(class_weight) == ... | 254 | class_weight.py | Python | sklearn/utils/class_weight.py | 3605c140af992b6ac52f04f1689c58509cc0b5b2 | scikit-learn | 11 | |
259,898 | 39 | 9 | 18 | 167 | 20 | 1 | 47 | 129 | test_fetch_openml_equivalence_array_dataframe | ENH improve ARFF parser using pandas (#21938)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Olivier Grisel <olivier.grisel@gmail.com>
Co-authored-by: Adrin Jalali <adrin.jalali@gmail.com> | https://github.com/scikit-learn/scikit-learn.git | def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser):
pytest.importorskip("pandas")
data_id = 61
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch_as_frame_true = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
... | @fails_if_pypy
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) | 89 | test_openml.py | Python | sklearn/datasets/tests/test_openml.py | a47d569e670fd4102af37c3165c9b1ddf6fd3005 | scikit-learn | 1 |
258,993 | 12 | 10 | 7 | 66 | 8 | 0 | 15 | 48 | tosequence | DOC Ensure that tosequence passes numpydoc validation (#22494)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> | https://github.com/scikit-learn/scikit-learn.git | def tosequence(x):
if isinstance(x, np.ndarray):
return np.asarray(x)
elif isinstance(x, Sequence):
return x
else:
return list(x)
| 40 | __init__.py | Python | sklearn/utils/__init__.py | 8abc6d890e8bb4be7abe2984b3f373585f8f3c57 | scikit-learn | 3 | |
259,648 | 93 | 17 | 35 | 371 | 19 | 0 | 141 | 422 | _check_reg_targets | ENH add D2 pinbal score and D2 absolute error score (#22118) | https://github.com/scikit-learn/scikit-learn.git | def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"):
check_consistent_length(y_true, y_pred)
y_true = check_array(y_true, ensure_2d=False, dtype=dtype)
y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype)
if y_true.ndim == 1:
y_true = y_true.reshape((-1, 1))
if ... | 234 | _regression.py | Python | sklearn/metrics/_regression.py | aeeac1c1d634dc80abc93fb30b3fe48e1d709b64 | scikit-learn | 10 | |
107,012 | 47 | 10 | 12 | 110 | 8 | 0 | 87 | 232 | _gci | Rewrite AxesStack independently of cbook.Stack.
AxesStack is fairly independent from cbook.Stack: cbook.Stack handles
the forward/back/home buttons of the navbar, and therefore additionally
maintains a movable "cursor" in the stack; AxesStack, on the other hand,
needs to keep track both of "original" order and of "gca... | https://github.com/matplotlib/matplotlib.git | def _gci(self):
# Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
# Look first for an image in the current Axes.
ax = self._axstack.current()
if ax is None:
return None
im = ax._gci()
if im is not None:
return im
# If t... | 64 | figure.py | Python | lib/matplotlib/figure.py | 8669c4636ce3b6ac6f4905c365ab41685186da56 | matplotlib | 5 | |
105,266 | 81 | 21 | 13 | 176 | 17 | 0 | 109 | 295 | _scrub_json | Support streaming cfq dataset (#4579)
* Support streaming cfq dataset
* Fix style
* Fix remaining code
* Fix tags and documentation card
* Fix task tags
* Fix task tag
* Refactor parsing to reduce RAM usage
* Add license
* Update metadata JSON
* Update dummy data
* Use less RAM by loading... | https://github.com/huggingface/datasets.git | def _scrub_json(self, content):
# Loading of json data with the standard Python library is very inefficient:
# For the 4GB dataset file it requires more than 40GB of RAM and takes 3min.
# There are more efficient libraries but in order to avoid additional
# dependencies we use a... | 99 | cfq.py | Python | datasets/cfq/cfq.py | de2f6ef2bc14022d0e9212f293b8e7b200aa7e75 | datasets | 4 | |
83,834 | 34 | 10 | 20 | 159 | 17 | 0 | 36 | 191 | test_stream_admin_remove_multiple_users_from_stream | message_flags: Short-circuit if no messages changed.
Omit sending an event, and updating the database, if there are no
matching messages. | https://github.com/zulip/zulip.git | def test_stream_admin_remove_multiple_users_from_stream(self) -> None:
target_users = [
self.example_user(name) for name in ["cordelia", "prospero", "othello", "hamlet", "ZOE"]
]
result = self.attempt_unsubscribe_of_principal(
query_count=26,
cache_co... | 101 | test_subs.py | Python | zerver/tests/test_subs.py | 803982e87254e3b1ebcb16ed795e224afceea3a3 | zulip | 2 | |
140,569 | 110 | 17 | 18 | 279 | 33 | 0 | 149 | 384 | custom_loss | Clean up docstyle in python modules and add LINT rule (#25272) | https://github.com/ray-project/ray.git | def custom_loss(self, policy_loss, loss_inputs):
# Get the next batch from our input files.
batch = self.reader.next()
# Define a secondary loss by building a graph copy with weight sharing.
obs = restore_original_dimensions(
torch.from_numpy(batch["obs"]).float().t... | 167 | custom_loss_model.py | Python | rllib/examples/models/custom_loss_model.py | 905258dbc19753c81039f993477e7ab027960729 | ray | 3 | |
106,353 | 27 | 12 | 9 | 130 | 19 | 0 | 30 | 101 | _call_downloader | [utils, etc] Kill child processes when yt-dl is killed
* derived from PR #26592, closes #26592
Authored by: Unrud | https://github.com/ytdl-org/youtube-dl.git | def _call_downloader(self, tmpfilename, info_dict):
cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
self._debug_cmd(cmd)
p = subprocess.Popen(
cmd, stderr=subprocess.PIPE)
_, stderr = process_communicate_or_kill(p)
if p.returncode ... | 81 | external.py | Python | youtube_dl/downloader/external.py | 0700fde6403aa9eec1ff02bff7323696a205900c | youtube-dl | 3 | |
39,802 | 68 | 16 | 12 | 152 | 17 | 0 | 91 | 196 | load_components | Adding prop reorder exceptions (#1866)
* Adding prop reorder exceptions
* Reworking prop order flag
* Removing unnecessary variable
* Reverting build:backends script changes
* Adding operator
* Adding default positional arg
* Updating docstring function
* Updated radioitems prop order
* Prop or... | https://github.com/plotly/dash.git | def load_components(metadata_path, namespace="default_namespace"):
# Register the component lib for index include.
ComponentRegistry.registry.add(namespace)
components = []
data = _get_metadata(metadata_path)
# Iterate over each property name (which is a path to the component)
for compon... | 87 | component_loader.py | Python | dash/development/component_loader.py | 0f1b299dce356dbec6c669731663ba7ce6ef057d | dash | 2 | |
208,214 | 31 | 13 | 11 | 189 | 15 | 0 | 39 | 128 | stamp | Fixed bug in group, chord, chain stamp() method, where the visitor overrides the
previously stamps in tasks of these objects (e.g. The tasks of the group had their
previous stamps overridden partially) | https://github.com/celery/celery.git | def stamp(self, visitor=None, **headers):
headers = headers.copy()
if visitor is not None:
headers.update(visitor.on_signature(self, **headers))
else:
headers["stamped_headers"] = [header for header in headers.keys() if header not in self.options]
_me... | 115 | canvas.py | Python | celery/canvas.py | 7d4fe22d03dabe1de2cf5009cc6ea1064b46edcb | celery | 4 | |
153,802 | 163 | 16 | 68 | 694 | 48 | 0 | 304 | 1,145 | _copartition | PERF-#4493: Use partition size caches more in Modin dataframe. (#4495)
Co-authored-by: Devin Petersohn <devin-petersohn@users.noreply.github.com>
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: mvashishtha <mahesh@ponder.io> | https://github.com/modin-project/modin.git | def _copartition(self, axis, other, how, sort, force_repartition=False):
if isinstance(other, type(self)):
other = [other]
self_index = self.axes[axis]
others_index = [o.axes[axis] for o in other]
joined_index, make_reindexer = self._join_index_objects(
... | 462 | dataframe.py | Python | modin/core/dataframe/pandas/dataframe/dataframe.py | cca9468648521e9317de1cb69cf8e6b1d5292d21 | modin | 21 | |
167,406 | 12 | 8 | 25 | 54 | 8 | 0 | 15 | 27 | validate_kwargs | TYP: Missing return annotations in util/tseries/plotting (#47510)
* TYP: Missing return annotations in util/tseries/plotting
* the more tricky parts | https://github.com/pandas-dev/pandas.git | def validate_kwargs(fname, kwargs, compat_args) -> None:
kwds = kwargs.copy()
_check_for_invalid_keys(fname, kwargs, compat_args)
_check_for_default_values(fname, kwds, compat_args)
| 35 | _validators.py | Python | pandas/util/_validators.py | 4bb1fd50a63badd38b5d96d9c4323dae7bc36d8d | pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.