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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
289,232 | 35 | 11 | 17 | 161 | 24 | 0 | 40 | 123 | test_setup_devices_exception | Update to iaqualink 0.5.0 (#80304)
* Update to iaqualink 0.5.0.
* Boolean conditional style fix
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
* Fix black formatting
* Update iaqualink tests after update to 0.5.x
* Remove debug print statements
Co-authored-by: Martin Hjelmare <marhje52@gmail.co... | https://github.com/home-assistant/core.git | async def test_setup_devices_exception(hass, config_entry, client):
config_entry.add_to_hass(hass)
system = get_aqualink_system(client, cls=IaquaSystem)
systems = {system.serial: system}
with patch(
"homeassistant.components.iaqualink.AqualinkClient.login",
return_value=None,
... | 97 | test_init.py | Python | tests/components/iaqualink/test_init.py | abec592a248607869dc1d495f956ca397dc189f4 | core | 1 | |
107,739 | 35 | 13 | 11 | 132 | 12 | 0 | 43 | 157 | set_rotation | Deprecate toplevel mpl.text.get_rotation; normalize rotations early.
get_rotation had been made a toplevel function a long time ago to be
used in TextWithDash, which has now been removed, so there isn't much
justification to have it separate. Also, note that while the toplevel
get_rotation's implementation also suppo... | https://github.com/matplotlib/matplotlib.git | def set_rotation(self, s):
if isinstance(s, numbers.Real):
self._rotation = float(s) % 360
elif cbook._str_equal(s, 'horizontal') or s is None:
self._rotation = 0.
elif cbook._str_equal(s, 'vertical'):
self._rotation = 90.
else:
ra... | 78 | text.py | Python | lib/matplotlib/text.py | 1f8f50e522f7e623279626381d650f8ff63627e3 | matplotlib | 5 | |
141,966 | 51 | 15 | 23 | 348 | 29 | 0 | 83 | 261 | test_syncer_callback_sync_period | [tune] Refactor Syncer / deprecate Sync client (#25655)
This PR includes / depends on #25709
The two concepts of Syncer and SyncClient are confusing, as is the current API for passing custom sync functions.
This PR refactors Tune's syncing behavior. The Sync client concept is hard deprecated. Instead, we offer a... | https://github.com/ray-project/ray.git | def test_syncer_callback_sync_period(ray_start_2_cpus, temp_data_dirs):
tmp_source, tmp_target = temp_data_dirs
with freeze_time() as frozen:
syncer_callback = TestSyncerCallback(
sync_period=60, local_logdir_override=tmp_target
)
trial1 = MockTrial(trial_id="a", logdi... | 210 | test_syncer_callback.py | Python | python/ray/tune/tests/test_syncer_callback.py | 6313ddc47cf9df4df8c8907997df559850a1b874 | ray | 1 | |
43,203 | 25 | 11 | 19 | 116 | 19 | 0 | 26 | 231 | test_confirm | Don't rely on current ORM structure for db clean command (#23574)
For command DB clean, by not relying on the ORM models, we will be able to use the command even when the metadatabase is not yet upgraded to the version of Airflow you have installed.
Additionally we archive all rows before deletion. | https://github.com/apache/airflow.git | def test_confirm(self, run_cleanup_mock, confirm_arg, expected):
args = self.parser.parse_args(
[
'db',
'clean',
'--clean-before-timestamp',
'2021-01-01',
*confirm_arg,
]
)
db_command... | 74 | test_db_command.py | Python | tests/cli/commands/test_db_command.py | 95bd6b71cc9f5da377e272707f7b68000d980939 | airflow | 1 | |
60,240 | 61 | 18 | 24 | 362 | 31 | 0 | 105 | 454 | configure_crop | Balanced joint maximum mean discrepancy for deep transfer learning | https://github.com/jindongwang/transferlearning.git | def configure_crop(self, context_pad):
# crop dimensions
in_ = self.inputs[0]
tpose = self.transformer.transpose[in_]
inv_tpose = [tpose[t] for t in tpose]
self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose]
#.transpose(inv_tpose)
# conte... | 233 | detector.py | Python | code/deep/BJMMD/caffe/python/caffe/detector.py | cc4d0564756ca067516f71718a3d135996525909 | transferlearning | 8 | |
258,625 | 98 | 14 | 35 | 495 | 40 | 0 | 137 | 456 | fit | ENH Replaced RandomState with Generator compatible calls (#22271) | https://github.com/scikit-learn/scikit-learn.git | def fit(self, X, y):
y = self._validate_data(X="no_validation", y=y)
if self.code_size <= 0:
raise ValueError(
"code_size should be greater than 0, got {0}".format(self.code_size)
)
_check_estimator(self.estimator)
random_state = check_r... | 318 | multiclass.py | Python | sklearn/multiclass.py | 254ea8c453cd2100ade07644648f1f00392611a6 | scikit-learn | 9 | |
269,246 | 70 | 22 | 43 | 498 | 25 | 0 | 184 | 640 | _get_data_iterator_from_dataset | fixed import random, removed keras import ,fixed grammer issues | https://github.com/keras-team/keras.git | def _get_data_iterator_from_dataset(dataset,dataset_type_spec) :
if dataset_type_spec == list:
if len(dataset) == 0:
raise ValueError('Received an empty list dataset. '
'Please provide a non-empty list of arrays.')
if _get_type_spec(dataset[0]) is np.ndarray:
expected_sh... | 270 | dataset_utils.py | Python | keras/utils/dataset_utils.py | c3a27a6642c03c6380aca22c6e3d73d0b29bb271 | keras | 14 | |
176,593 | 12 | 13 | 6 | 80 | 8 | 1 | 14 | 48 | is_strongly_connected | Added examples in connected and strongly connected functions (#5559)
* added examples
* Update networkx/algorithms/components/connected.py
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu> | https://github.com/networkx/networkx.git | def is_strongly_connected(G):
if len(G) == 0:
raise nx.NetworkXPointlessConcept(
)
return len(list(strongly_connected_components(G))[0]) == len(G)
@not_implemented_for("undirected") | @not_implemented_for("undirected") | 40 | strongly_connected.py | Python | networkx/algorithms/components/strongly_connected.py | 7cad29b3542ad867f1eb5b7b6a9087495f252749 | networkx | 2 |
27,800 | 78 | 15 | 93 | 595 | 45 | 0 | 129 | 330 | test_orderline_query | Metadata added to checkout and order lines (#10040)
* Metadata added to checkout and order lines
* CHANGELOG.md update
* Missing tests added | https://github.com/saleor/saleor.git | def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_order):
order = fulfilled_order
query =
line = order.lines.first()
metadata_key = "md key"
metadata_value = "md value"
line.store_value_in_private_metadata({metadata_key: metadata_value})
line.store_value_in_me... | 349 | test_order.py | Python | saleor/graphql/order/tests/test_order.py | a68553e1a55e3a1bd32826cdce294d27f74175e9 | saleor | 1 | |
209,520 | 34 | 9 | 6 | 58 | 6 | 0 | 40 | 115 | recap | E275 - Missing whitespace after keyword (#3711)
Co-authored-by: Alexander Aring <alex.aring@gmail.com>
Co-authored-by: Anmol Sarma <me@anmolsarma.in>
Co-authored-by: antoine.torre <torreantoine1@gmail.com>
Co-authored-by: Antoine Vacher <devel@tigre-bleu.net>
Co-authored-by: Arnaud Ebalard <arno@natisbad.org>
Co-... | https://github.com/secdev/scapy.git | def recap(self, nc):
# type: (int) -> None
assert nc >= 0
t = self._dynamic_table_cap_size > nc
self._dynamic_table_cap_size = nc
if t:
# The RFC is not clear about whether this resize should happen;
# we do it anyway
self.resize(nc)
| 33 | http2.py | Python | scapy/contrib/http2.py | 08b1f9d67c8e716fd44036a027bdc90dcb9fcfdf | scapy | 2 | |
215,674 | 202 | 20 | 160 | 1,811 | 55 | 0 | 479 | 2,383 | test_modify | Adding the ability to add, delete, purge, and modify Salt scheduler jobs when the Salt minion is not running. | https://github.com/saltstack/salt.git | def test_modify(sock_dir, job1, schedule_config_file):
current_job1 = {
"function": "salt",
"seconds": "3600",
"maxrunning": 1,
"name": "job1",
"enabled": True,
"jid_include": True,
}
new_job1 = {
"function": "salt",
"seconds": "60",
... | 1,004 | test_schedule.py | Python | tests/pytests/unit/modules/test_schedule.py | 62908a04f5166e0a26f69ff1a5296a19bad351ad | salt | 3 | |
125,720 | 79 | 15 | 42 | 543 | 29 | 0 | 172 | 425 | test_component_activities_hook | [dashboard] Update cluster_activities endpoint to use pydantic. (#26609)
Update cluster_activities endpoint to use pydantic so we have better data validation.
Make timestamp a required field.
Add pydantic to ray[default] requirements | https://github.com/ray-project/ray.git | def test_component_activities_hook(set_ray_cluster_activity_hook, call_ray_start):
external_hook = set_ray_cluster_activity_hook
response = requests.get("http://127.0.0.1:8265/api/component_activities")
response.raise_for_status()
# Validate schema of response
data = response.json()
schem... | 308 | test_snapshot.py | Python | dashboard/modules/snapshot/tests/test_snapshot.py | e8222ff600f79cc7c5cc28f43a951215c4b5460c | ray | 6 | |
86,843 | 11 | 9 | 4 | 48 | 8 | 0 | 11 | 43 | drop | feat(replays): Remove usage of the attachment cache (#39987)
closes https://github.com/getsentry/replay-backend/issues/154 | https://github.com/getsentry/sentry.git | def drop(self):
part = RecordingSegmentPart(self.prefix)
for i in range(self.num_parts):
del part[i]
| 29 | cache.py | Python | src/sentry/replays/cache.py | 5113b00cb01ae85a9b0578bed8f9eb7a1a66967a | sentry | 2 | |
2,529 | 20 | 11 | 23 | 115 | 14 | 0 | 22 | 142 | _object2proto | Changes for publishing dataset and passing actions to enclave | https://github.com/OpenMined/PySyft.git | def _object2proto(self) -> PublishDatasetMessage_PB:
return PublishDatasetMessage_PB(
msg_id=serialize(self.id),
address=serialize(self.address),
reply_to=serialize(self.reply_to),
dataset_id=self.dataset_id,
deployment_id=self.deployment_id,
... | 78 | oblv_messages.py | Python | packages/syft/src/syft/core/node/common/node_service/oblv/oblv_messages.py | 54c0a2f6738090252dc2b2863eb3c13b1bcb9e6a | PySyft | 1 | |
126,133 | 2 | 6 | 16 | 13 | 2 | 0 | 2 | 5 | test_receive_event_by_http | [workflow] http_event_provider and accompanied listener (#26010)
### Why are these changes needed?
This PR enhances workflow functionality to receive external events from a Serve based HTTP endpoint. A workflow can then consume events asynchronously as they arrive.
### Design Logic
A `workflow.wait_for_event` no... | https://github.com/ray-project/ray.git | def test_receive_event_by_http(workflow_start_regular_shared_serve):
| 92 | test_http_events.py | Python | python/ray/workflow/tests/test_http_events.py | 659d25a3a9c4794db9dbe8f428ec587470b261b0 | ray | 4 | |
288,138 | 19 | 8 | 7 | 72 | 10 | 0 | 20 | 63 | _async_ble_device_disconnected | Add ESPHome BleakClient (#78911)
Co-authored-by: Paulus Schoutsen <balloob@gmail.com> | https://github.com/home-assistant/core.git | def _async_ble_device_disconnected(self) -> None:
_LOGGER.debug("%s: BLE device disconnected", self._source)
self._is_connected = False
self.services = BleakGATTServiceCollection() # type: ignore[no-untyped-call]
self._async_call_bleak_disconnected_callback()
self._unsu... | 40 | client.py | Python | homeassistant/components/esphome/bluetooth/client.py | 7042d6d35be54865b1252c0b28a50cce1a92eabc | core | 1 | |
337,299 | 58 | 15 | 28 | 236 | 20 | 0 | 82 | 354 | recursively_apply | Convert documentation to the new front (#271)
* Main conversion
* Doc styling
* Style
* New front deploy
* Fixes
* Fixes
* Fix new docstrings
* Style | https://github.com/huggingface/accelerate.git | def recursively_apply(func, data, *args, test_type=is_torch_tensor, error_on_other_type=False, **kwargs):
if isinstance(data, (tuple, list)):
return honor_type(
data,
(
recursively_apply(
func, o, *args, test_type=test_type, error_on_other_typ... | 146 | utils.py | Python | src/accelerate/utils.py | fb5ed62c102c0323486b89805e1888495de3db15 | accelerate | 7 | |
90,708 | 7 | 9 | 24 | 26 | 3 | 0 | 7 | 26 | mixed_payload | feat(metrics): functionality for the indexer-last-seen-updater (#34865)
* update meta structure to support last_seen updater better
* use metrics to record last_seen_updater info
* actually produce headers in indexer output message | https://github.com/getsentry/sentry.git | def mixed_payload():
return bytes(
,
encoding="utf-8",
)
| 14 | test_last_seen_updater.py | Python | tests/sentry/sentry_metrics/test_last_seen_updater.py | 261437e3bbb102732344817f67762142c0d6977e | sentry | 1 | |
322,882 | 25 | 13 | 9 | 81 | 10 | 0 | 26 | 113 | available_labels | Add NLP model interpretation (#1752)
* upload NLP interpretation
* fix problems and relocate project
* remove abandoned picture
* remove abandoned picture
* fix dead link in README
* fix dead link in README
* fix code style problems
* fix CR round 1
* remove .gitkeep files
* fix code style
... | https://github.com/PaddlePaddle/PaddleNLP.git | def available_labels(self):
try:
assert self.mode == "classification"
except AssertionError:
raise NotImplementedError(
'Not supported for regression explanations.')
else:
ans = self.top_labels if self.top_labels else self.local_exp.ke... | 46 | explanation.py | Python | examples/model_interpretation/task/senti/LIME/explanation.py | 93cae49c0c572b5c1ac972759140fbe924b0374d | PaddleNLP | 3 | |
181,596 | 62 | 11 | 23 | 232 | 20 | 0 | 67 | 287 | test_driver_5 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | https://github.com/EpistasisLab/tpot.git | def test_driver_5():
# Catch FutureWarning https://github.com/scikit-learn/scikit-learn/issues/11785
if (np.__version__ >= LooseVersion("1.15.0") and
sklearn.__version__ <= LooseVersion("0.20.0")):
raise nose.SkipTest("Warning raised by scikit-learn")
args_list = [
... | 121 | driver_tests.py | Python | tests/driver_tests.py | 388616b6247ca4ea8de4e2f340d6206aee523541 | tpot | 3 | |
245,559 | 42 | 13 | 20 | 278 | 26 | 0 | 57 | 245 | get_whs_and_shapes | [Fix] replace mmcv's function and modules imported with mmengine's (#8594)
* use mmengine's load_state_dict and load_checkpoint
* from mmengine import dump
* from mmengine import FileClient dump list_from_file
* remove redundant registry
* update
* update
* update
* replace _load_checkpoint with C... | https://github.com/open-mmlab/mmdetection.git | def get_whs_and_shapes(self):
self.logger.info('Collecting bboxes from annotation...')
bbox_whs = []
img_shapes = []
prog_bar = ProgressBar(len(self.dataset))
for idx in range(len(self.dataset)):
ann = self.dataset.get_ann_info(idx)
data_info = se... | 160 | optimize_anchors.py | Python | tools/analysis_tools/optimize_anchors.py | d0695e68654ca242be54e655491aef8c959ac345 | mmdetection | 3 | |
77,101 | 40 | 13 | 31 | 176 | 25 | 0 | 49 | 196 | test_add_post_duplicate_choose_permission | Add duplicate detection to multiple image upload view
Add utility function to find an image's potential duplicates
Add logic to detect duplicates on multiple images upload view
Add template shown when a user is prompted to confirm a duplicate upload
Add client-side logic to confirm a duplicate upload
Add/update st... | https://github.com/wagtail/wagtail.git | def test_add_post_duplicate_choose_permission(self):
# Create group with access to admin and add permission.
bakers_group = Group.objects.create(name="Bakers")
access_admin_perm = Permission.objects.get(
content_type__app_label="wagtailadmin", codename="access_admin"
... | 221 | test_admin_views.py | Python | wagtail/images/tests/test_admin_views.py | c136f461bc052cef362991458e1bd1fca37a3da9 | wagtail | 1 | |
305,067 | 24 | 14 | 30 | 138 | 13 | 0 | 36 | 118 | extra_state_attributes | Awair local use config entry name + add measurement state class (#77383) | https://github.com/home-assistant/core.git | def extra_state_attributes(self) -> dict:
sensor_type = self.entity_description.key
attrs: dict = {}
if not self._air_data:
return attrs
if sensor_type in self._air_data.indices:
attrs["awair_index"] = abs(self._air_data.indices[sensor_type])
elif... | 84 | sensor.py | Python | homeassistant/components/awair/sensor.py | 79b5147b46a16b65404c74df5dd9a10ce16ea216 | core | 5 | |
186,353 | 12 | 8 | 3 | 45 | 4 | 0 | 12 | 21 | parse_includes | Various clean-ups in certbot-apache. Use f-strings. (#9132)
* Various clean-ups in certbot-apache. Use f-strings.
* Smaller tweaks | https://github.com/certbot/certbot.git | def parse_includes(apachectl):
inc_cmd = [apachectl, "-t", "-D", "DUMP_INCLUDES"]
return parse_from_subprocess(inc_cmd, r"\(.*\) (.*)")
| 25 | apache_util.py | Python | certbot-apache/certbot_apache/_internal/apache_util.py | eeca208c8f57304590ac1af80b496e61021aaa45 | certbot | 1 | |
195,097 | 20 | 10 | 5 | 50 | 7 | 0 | 23 | 66 | _get_batch_context | Added director agent and safety experiment commands. (#4602)
* Added director agent and safety.
* ran autoformat.sh | https://github.com/facebookresearch/ParlAI.git | def _get_batch_context(self, batch):
if 'full_text_vec' not in batch:
logging.warn('Batch does not have full text vec, resorting to text vec')
return batch.text_vec
return batch.full_text_vec
| 28 | director_agent.py | Python | projects/director/director_agent.py | 2ef5586ed0d644abe18cd3ff45ef9fa01981e87c | ParlAI | 2 | |
186,742 | 6 | 7 | 7 | 25 | 4 | 0 | 6 | 20 | must_staple | Must staple: check for OCSP support (#9226)
* Must staple: check for OCSP support
* Expand error message
* s/Must Staple/Must-Staple
* Broaden the term webserver
* Improve error message | https://github.com/certbot/certbot.git | def must_staple(self) -> bool:
return self.namespace.must_staple
| 14 | configuration.py | Python | certbot/certbot/configuration.py | a513b57e5e3667365f77b040e070cbec05212174 | certbot | 1 | |
139,475 | 7 | 6 | 7 | 27 | 5 | 0 | 7 | 21 | extra_learn_fetches_fn | [RLlib] Introduce new policy base classes. (#24742) | https://github.com/ray-project/ray.git | def extra_learn_fetches_fn(self) -> Dict[str, TensorType]:
return {}
| 16 | dynamic_tf_policy_v2.py | Python | rllib/policy/dynamic_tf_policy_v2.py | bc3a1d35cf6e9a5fd7eef908a8e76aefb80ce6a9 | ray | 1 | |
259,850 | 30 | 11 | 7 | 121 | 19 | 0 | 32 | 68 | test_dataframe_support | FIX DecisionBoundaryPlot should not raise spurious warning (#23318) | https://github.com/scikit-learn/scikit-learn.git | def test_dataframe_support():
pd = pytest.importorskip("pandas")
df = pd.DataFrame(X, columns=["col_x", "col_y"])
estimator = LogisticRegression().fit(df, y)
with warnings.catch_warnings():
# no warnings linked to feature names validation should be raised
warnings.simplefilter("err... | 68 | test_boundary_decision_display.py | Python | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | b0b8a39d8bb80611398e4c57895420d5cb1dfe09 | scikit-learn | 1 | |
60,423 | 41 | 13 | 6 | 90 | 12 | 0 | 45 | 80 | CheckForCopyright | Balanced joint maximum mean discrepancy for deep transfer learning | https://github.com/jindongwang/transferlearning.git | def CheckForCopyright(filename, lines, error):
# We'll check up to line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if _RE_COPYRIGHT.search(lines[line], re.I):
error(filename, 0, 'legal/copyright', 5,
'Copyright message found. '
... | 56 | cpp_lint.py | Python | code/deep/BJMMD/caffe/scripts/cpp_lint.py | cc4d0564756ca067516f71718a3d135996525909 | transferlearning | 3 | |
19,899 | 13 | 8 | 10 | 47 | 5 | 0 | 14 | 53 | installed_as_egg | 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 installed_as_egg(self) -> bool:
location = self.location
if not location:
return False
return location.endswith(".egg")
| 26 | base.py | Python | pipenv/patched/notpip/_internal/metadata/base.py | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | pipenv | 2 | |
5,874 | 70 | 12 | 32 | 326 | 37 | 0 | 90 | 257 | test_visualization_compare_performance_output_saved | 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_performance_output_saved(csv_filename):
input_features = [text_feature(encoder="parallel_cnn")]
output_features = [category_feature()]
# Generate test data
rel_path = generate_data(input_features, output_features, csv_filename)
input_features[0]["encoder"] = "par... | 200 | test_visualization.py | Python | tests/integration_tests/test_visualization.py | 4fb8f63181f5153b4f6778c6ef8dad61022c4f3f | ludwig | 2 | |
269,142 | 166 | 15 | 44 | 462 | 47 | 0 | 285 | 553 | wrap_layer_functions | Support Keras saving/loading for ShardedVariables with arbitrary partitions.
PiperOrigin-RevId: 439837516 | https://github.com/keras-team/keras.git | def wrap_layer_functions(layer, serialization_cache):
# Since Sequential models may be modified in place using model.add() or
# model.pop(), don't use saved functions.
if (isinstance(layer, keras_load.RevivedLayer) and
not isinstance(layer, sequential_lib.Sequential)):
return {
fn_name: getat... | 277 | save_impl.py | Python | keras/saving/saved_model/save_impl.py | e61cbc52fd3b0170769c120e9b8dabc8c4205322 | keras | 8 | |
178,270 | 41 | 16 | 29 | 266 | 28 | 0 | 63 | 382 | url | fix: DEV-3911: Move persistent storages to OS (#3377)
* fix: DEV-3911: Move persistent storages to OS
* Fix
* Add deps
* Back header
* Move DownloadStorageData handler
* Update all urls json
* Fix import
* add nginx config
* Fix GSC storage
Co-authored-by: Sergei Ivashchenko <triklozoid@gmai... | https://github.com/heartexlabs/label-studio.git | def url(self, name):
name = self._normalize_name(clean_name(name))
blob = self.bucket.blob(name)
blob_params = self.get_object_parameters(name)
no_signed_url = (
blob_params.get('acl', self.default_acl) == 'publicRead' or not self.querystring_auth)
if not se... | 164 | storage.py | Python | label_studio/core/storage.py | 92314e4a9c431c407533e4a064481acf3c5983ab | label-studio | 6 | |
250,580 | 13 | 10 | 6 | 55 | 5 | 0 | 14 | 64 | intercept | Flow.intercept: use an Event instead of the reply system
This is patch 3/4 of the reply-ectomy. | https://github.com/mitmproxy/mitmproxy.git | def intercept(self):
if self.intercepted:
return
self.intercepted = True
if self._resume_event is not None:
self._resume_event.clear()
| 32 | flow.py | Python | mitmproxy/flow.py | ede269fce40ec4000a4717d5f5aec7835d9931c2 | mitmproxy | 3 | |
258,441 | 17 | 12 | 17 | 89 | 11 | 0 | 17 | 71 | get_openapi_specs | bug: fix the docs rest api reference url (#3775)
* bug: fix the docs rest api reference url
* revert openapi json changes
* remove last line on json files
* Add explanation about `servers` and remove `servers` parameter from FastAPI
* generate openapi schema without empty end line | https://github.com/deepset-ai/haystack.git | def get_openapi_specs() -> dict:
app = get_app()
return get_openapi(
title=app.title,
version=app.version,
openapi_version=app.openapi_version,
description=app.description,
routes=app.routes,
servers=[{"url": "http://localhost:8000"}],
)
| 56 | utils.py | Python | rest_api/rest_api/utils.py | 86ade4817eda3142d2ddef65a0b1e29ffee770e3 | haystack | 1 | |
212,208 | 23 | 12 | 8 | 84 | 14 | 0 | 26 | 46 | _clone | Discover unstable defaults in `HasProps.__init__()` (#11959)
* Discover unstable defaults in HasProps.__init__()
* Make HasProps.__getattr__() fail properly
* More sensible implementation of HasProps._clone()
* Make InstanceDefault a generic class
* Fix recursive model definition in tests
* Fix default ... | https://github.com/bokeh/bokeh.git | def _clone(self) -> HasProps:
attrs = self.properties_with_values(include_defaults=False, include_undefined=True)
return self.__class__(**{key: val for key, val in attrs.items() if val is not Undefined})
KindRef = Any # TODO
| 49 | has_props.py | Python | bokeh/core/has_props.py | b23a3b77447ede916b31756fca997cbb1b806de7 | bokeh | 3 | |
95,638 | 26 | 10 | 10 | 117 | 16 | 0 | 29 | 111 | test_unsupported_null_response | ref(webhooks): Handle unexpected webhook responses (#31143) | https://github.com/getsentry/sentry.git | def test_unsupported_null_response(self):
responses.add(
responses.POST, "http://example.com", body="null", content_type="application/json"
)
try:
self.plugin.notify(self.notification)
except Exception as exc:
assert False, f"'self.plugin.not... | 68 | test_plugin.py | Python | tests/sentry/plugins/sentry_webhooks/test_plugin.py | 03c688897205e936302f528dc72fc391b3ef5904 | sentry | 2 | |
208,774 | 22 | 13 | 7 | 128 | 9 | 0 | 40 | 73 | find_entry_points | Added additional entrypoint script.
Added a third entrypoint to use python's minor version as well.
This can help when testing out differences of python versions. One could easily open "ipython3.10" and test it's differences with "ipython3.8". | https://github.com/ipython/ipython.git | def find_entry_points():
ep = [
'ipython%s = IPython:start_ipython',
]
major_suffix = str(sys.version_info[0])
minor_suffix = ".".join([str(sys.version_info[0]), str(sys.version_info[1])])
return [e % '' for e in ep] + [e % major_suffix for e in ep] + [e % minor_suffix for e in ... | 80 | setupbase.py | Python | setupbase.py | 1db65d02e89f31c28c221197a2ed04f3ade3b195 | ipython | 4 | |
176,920 | 53 | 12 | 20 | 276 | 27 | 0 | 91 | 179 | _hits_numpy | Make HITS numpy and scipy private functions (#5771)
* Make HITS numpy and scipy private functions
* fix examples with correct imports
* remove functions from TOC | https://github.com/networkx/networkx.git | def _hits_numpy(G, normalized=True):
import numpy as np
if len(G) == 0:
return {}, {}
adj_ary = nx.to_numpy_array(G)
# Hub matrix
H = adj_ary @ adj_ary.T
e, ev = np.linalg.eig(H)
h = ev[:, np.argmax(e)] # eigenvector corresponding to the maximum eigenvalue
# Authority matr... | 173 | hits_alg.py | Python | networkx/algorithms/link_analysis/hits_alg.py | e5f1edb82a379ceb6afcf421fa5f6b4cb43cfbaf | networkx | 3 | |
297,831 | 24 | 8 | 34 | 101 | 16 | 1 | 24 | 95 | async_start | String formatting and max line length - Part 1 (#84390)
Co-authored-by: Erik Montnemery <erik@montnemery.com> | https://github.com/home-assistant/core.git | async def async_start(self) -> None:
_LOGGER.info("Starting Home Assistant")
setattr(self.loop, "_thread_ident", threading.get_ident())
self.state = CoreState.starting
self.bus.async_fire(EVENT_CORE_CONFIG_UPDATE)
self.bus.async_fire(EVENT_HOMEASSISTANT_START)
... | async def async_start(self) -> None:
"""Finalize startup from inside the event loop.
This method is a coroutine.
"""
_LOGGER.info("Starting Home Assistant")
setattr(self.loop, "_thread_ident", threading.get_ident())
self.state = CoreState.starting
self.bus.async... | 150 | core.py | Python | homeassistant/core.py | b0cee0bc46cbd7efe0e6421da18d91595c7a25ad | core | 3 |
196,005 | 211 | 17 | 60 | 658 | 37 | 0 | 472 | 1,095 | multiset_derangements | make remap canonical; more inline comments
In addition, clean-up of multiset_derangement's rv is
done to encourage proper use of the function: if you want
to see the output you have to copy it since the derangements
are generated in place.
If you don't want this or find it a hassle, then use
generate_derangements. | https://github.com/sympy/sympy.git | def multiset_derangements(s):
from sympy.core.sorting import ordered
# create multiset dictionary of hashable elements or else
# remap elements to integers
try:
ms = multiset(s)
except TypeError:
# give each element a canonical integer value
key = dict(enumerate(ordered(... | 461 | iterables.py | Python | sympy/utilities/iterables.py | 94d6e4fc1ac2c516d328fdad20933d3d92bf52bb | sympy | 28 | |
155,525 | 221 | 16 | 68 | 962 | 68 | 0 | 366 | 834 | merge_percentiles | Replace `interpolation` with `method` and `method` with `internal_method` (#8525)
Following the change in numpy 1.22.0
Co-authored-by: James Bourbeau <jrbourbeau@users.noreply.github.com> | https://github.com/dask/dask.git | def merge_percentiles(finalq, qs, vals, method="lower", Ns=None, raise_on_nan=True):
from .utils import array_safe
if isinstance(finalq, Iterator):
finalq = list(finalq)
finalq = array_safe(finalq, like=finalq)
qs = list(map(list, qs))
vals = list(vals)
if Ns is None:
vals,... | 612 | percentile.py | Python | dask/array/percentile.py | 3c46e89aea2af010e69049cd638094fea2ddd576 | dask | 18 | |
136,218 | 13 | 9 | 8 | 71 | 11 | 0 | 13 | 34 | poll | [Dashboard] Optimize and backpressure actor_head.py (#29580)
Signed-off-by: SangBin Cho <rkooo567@gmail.com>
This optimizes the actor head CPU usage and guarantees a stable API response from the dashboard under lots of actor events published to drivers. The below script is used for testing, and I could reproduce th... | https://github.com/ray-project/ray.git | async def poll(self, timeout=None, batch_size=500) -> List[Tuple[bytes, str]]:
await self._poll(timeout=timeout)
return self._pop_actors(self._queue, batch_size=batch_size)
| 46 | gcs_pubsub.py | Python | python/ray/_private/gcs_pubsub.py | 9da53e3e5a6ec7b9bea32cd68f00f3e9468056ef | ray | 1 | |
296,364 | 5 | 6 | 2 | 17 | 2 | 0 | 5 | 12 | async_tear_down | Refactor MQTT discovery (#67966)
* Proof of concept
* remove notify platform
* remove loose test
* Add rework from #67912 (#1)
* Move notify serviceupdater to Mixins
* Move tag discovery handler to Mixins
* fix tests
* Add typing for async_load_platform_helper
* Add add entry unload support for... | https://github.com/home-assistant/core.git | async def async_tear_down(self) -> None:
| 8 | mixins.py | Python | homeassistant/components/mqtt/mixins.py | 3b2aae5045f9f08dc8f174c5d975852588e1a132 | core | 1 | |
141,872 | 10 | 12 | 8 | 50 | 7 | 0 | 11 | 32 | remote_execution_api | [tune/ci] Multinode support killing nodes in Ray client mode (#25709)
The multi node testing utility currently does not support controlling cluster state from within Ray tasks or actors., but it currently requires Ray client. This makes it impossible to properly test e.g. fault tolerance, as the driver has to be execu... | https://github.com/ray-project/ray.git | def remote_execution_api(self) -> "RemoteAPI":
self._execution_queue = Queue(actor_options={"num_cpus": 0})
stop_event = self._execution_event
| 55 | test_utils.py | Python | python/ray/autoscaler/_private/fake_multi_node/test_utils.py | b574f75a8f5a28d2f9e55696ca5c40b2e095d9f9 | ray | 1 | |
213,073 | 10 | 9 | 2 | 31 | 4 | 0 | 10 | 31 | __reduce__ | fix: Py27hash fix (#2182)
* Add third party py27hash code
* Add Py27UniStr and unit tests
* Add py27hash_fix utils and tests
* Add to_py27_compatible_template and tests
* Apply py27hash fix to wherever it is needed
* Apply py27hash fix, all tests pass except api_with_any_method_in_swagger
* apply py2... | https://github.com/aws/serverless-application-model.git | def __reduce__(self):
# pylint: disable = W0235
return super(Py27Dict, self).__reduce__()
| 17 | py27hash_fix.py | Python | samtranslator/utils/py27hash_fix.py | a5db070f446b7cfebdaa6ad2e3dcf78f6105a272 | serverless-application-model | 1 | |
177,008 | 66 | 16 | 30 | 340 | 22 | 1 | 112 | 408 | naive_all_pairs_lowest_common_ancestor | Naive lowest common ancestor implementation (#5736)
* Add naive lca methods
* Naive algorithm implementation for LCA
* Modify naive lca functions
* Correct parameters of nx.ancestors
* Update lowest_common_ancestors.py
* Parametrize tests
* Apply suggestions from code review
Co-authored-by: Dan Sc... | https://github.com/networkx/networkx.git | def naive_all_pairs_lowest_common_ancestor(G, pairs=None):
if not nx.is_directed_acyclic_graph(G):
raise nx.NetworkXError("LCA only defined on directed acyclic graphs.")
elif len(G) == 0:
raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
elif None in G:
raise ... | @not_implemented_for("undirected")
@not_implemented_for("multigraph") | 200 | lowest_common_ancestors.py | Python | networkx/algorithms/lowest_common_ancestors.py | b2f91c34a23058dd70b41784af0d87890216026a | networkx | 13 |
54,484 | 6 | 10 | 4 | 41 | 4 | 0 | 6 | 26 | assert_does_not_warn | Fix deprecated use of pytest.warn to assert warnings are not raised | https://github.com/PrefectHQ/prefect.git | def assert_does_not_warn():
with warnings.catch_warnings():
warnings.simplefilter("error")
yield
| 19 | testing.py | Python | src/prefect/utilities/testing.py | 2b2f421054df5bb301a13322f420b5bb44fcd2aa | prefect | 1 | |
183,774 | 8 | 8 | 3 | 31 | 6 | 0 | 8 | 22 | _cursor_at_right_edge | Support for bracketed paste mode (#567)
* Detecting bracketed paste, sending paste events
* Bracketed pasting support in TextInput
* Restore debugging conditional
* Handle pasting of text in text-input, improve scrolling
* Fix ordering of handling in parser for bracketed pastes
* Docstrings
* Add doc... | https://github.com/Textualize/textual.git | def _cursor_at_right_edge(self) -> bool:
return self._visible_content_to_cursor_cell_len == self.content_region.width
| 18 | text_input.py | Python | src/textual/widgets/text_input.py | fe151a7f25cfd7f1134ebafbddc7eeade1c18ccb | textual | 1 | |
69,293 | 73 | 20 | 37 | 455 | 37 | 0 | 91 | 54 | get_price_list | refactor: rewrite `Item Prices Report` queries in `QB` | https://github.com/frappe/erpnext.git | def get_price_list():
rate = {}
ip = frappe.qb.DocType("Item Price")
pl = frappe.qb.DocType("Price List")
cu = frappe.qb.DocType("Currency")
price_list = (
frappe.qb.from_(ip)
.from_(pl)
.from_(cu)
.select(
ip.item_code,
ip.buying,
ip.selling,
(IfNull(cu.symbol, ip.currency)).as_("currency... | 282 | item_prices.py | Python | erpnext/stock/report/item_prices/item_prices.py | e312d17eae2a957b71c3a11480cad1d5dd848077 | erpnext | 6 | |
132,856 | 53 | 13 | 6 | 98 | 9 | 0 | 72 | 150 | is_finished | [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 is_finished(self):
# The checks here are partly redundant but optimized for quick
# evaluation. Specifically, if there are live trials, we check
# these live trials first. Only if none of the live trials is
# live anymore do we loop over all trials for a final check.
... | 58 | trial_runner.py | Python | python/ray/tune/trial_runner.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 6 | |
260,358 | 9 | 8 | 4 | 47 | 7 | 0 | 9 | 37 | fit | MAINT Use _validate_params in FastICA (#23711)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
Co-authored-by: jeremiedbb <jeremiedbb@yahoo.fr> | https://github.com/scikit-learn/scikit-learn.git | def fit(self, X, y=None):
self._validate_params()
self._fit_transform(X, compute_sources=False)
return self
| 29 | _fastica.py | Python | sklearn/decomposition/_fastica.py | 4cc347d4d0cbbfdcbd353f08842e0668fed78c9f | scikit-learn | 1 | |
269,454 | 65 | 14 | 30 | 478 | 37 | 1 | 103 | 346 | dot | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def dot(x, y):
if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2):
x_shape = []
for i, s in zip(int_shape(x), tf.unstack(tf.shape(x))):
if i is not None:
x_shape.append(i)
else:
x_shape.append(s)
x_shape = tuple(x_shape)
... | @keras_export("keras.backend.batch_dot")
@tf.__internal__.dispatch.add_dispatch_support
@doc_controls.do_not_generate_docs | 286 | backend.py | Python | keras/backend.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 9 |
125,559 | 4 | 8 | 2 | 22 | 2 | 0 | 4 | 10 | find_gcs_addresses | [core] ray.init defaults to an existing Ray instance if there is one (#26678)
ray.init() will currently start a new Ray instance even if one is already existing, which is very confusing if you are a new user trying to go from local development to a cluster. This PR changes it so that, when no address is specified, we ... | https://github.com/ray-project/ray.git | def find_gcs_addresses():
return _find_address_from_flag("--gcs-address")
| 10 | services.py | Python | python/ray/_private/services.py | 55a0f7bb2db941d8c6ff93f55e4b3193f404ddf0 | ray | 1 | |
3,682 | 39 | 13 | 17 | 250 | 30 | 0 | 48 | 119 | test_page_token_expired_retry_succeeds | Source Google Ads: handle page token expired exception (#9812)
* dynamic date range
* raise exception if exites the cycle without error
* if range days is 1 already do not retry
* added unit tests
* added comments
* added comments
* common mock classes are moved to common module
* change read_reco... | https://github.com/airbytehq/airbyte.git | def test_page_token_expired_retry_succeeds(mock_ads_client, test_config):
stream_slice = {"start_date": "2021-01-01", "end_date": "2021-01-15"}
google_api = MockGoogleAds(credentials=test_config["credentials"], customer_id=test_config["customer_id"])
incremental_stream_config = dict(
api=googl... | 145 | test_streams.py | Python | airbyte-integrations/connectors/source-google-ads/unit_tests/test_streams.py | 359fcd801128239b39297828d39821f631ce00c0 | airbyte | 1 | |
310,597 | 13 | 10 | 5 | 42 | 5 | 0 | 13 | 45 | _async_change_light | Migrate amcrest integration to new async API (#56294) | https://github.com/home-assistant/core.git | async def _async_change_light(self) -> None:
await self._async_change_setting(
self._audio_enabled or self.is_streaming, "indicator light"
)
| 23 | camera.py | Python | homeassistant/components/amcrest/camera.py | 7781e308cd7b28c67b6cf339f9b115c7190456fe | core | 2 | |
261,218 | 14 | 11 | 4 | 68 | 8 | 0 | 15 | 31 | axis0_safe_slice | DOC Ensure that sklearn.utils.axis0_safe_slice passes numpydoc (#24561) | https://github.com/scikit-learn/scikit-learn.git | def axis0_safe_slice(X, mask, len_mask):
if len_mask != 0:
return X[safe_mask(X, mask), :]
return np.zeros(shape=(0, X.shape[1]))
| 45 | __init__.py | Python | sklearn/utils/__init__.py | 537c325f2927895449ce418b3a77750135c0ba7b | scikit-learn | 2 | |
170,649 | 7 | 6 | 3 | 25 | 6 | 0 | 7 | 14 | obj_to_write | issue 48855 enable pylint unnecessary-pass (#49418)
issue 48855 enable unnecessary-pass | https://github.com/pandas-dev/pandas.git | def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
| 16 | _json.py | Python | pandas/io/json/_json.py | 76923d7b58d8f25329e779a40b87e2b6959f9cea | pandas | 1 | |
213,001 | 131 | 21 | 57 | 973 | 33 | 0 | 258 | 945 | cut_ansi_string_into_parts | Removed old code that used Popen and instead uses the PySimpleGUI Exec API calls for an all-in-one demo. Added expansion of the Multilline and a SizeGrip so that it's obvious to user the window is resizable. | https://github.com/PySimpleGUI/PySimpleGUI.git | def cut_ansi_string_into_parts(string_with_ansi_codes):
color_codes_english = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Reset']
color_codes = ["30m", "31m", "32m", "33m", "34m", "35m", "36m", "37m", "0m"]
effect_codes_english = ['Italic', 'Underline', 'Slow Blink', 'Rapid... | 603 | Demo_Script_Launcher_ANSI_Color_Output.py | Python | DemoPrograms/Demo_Script_Launcher_ANSI_Color_Output.py | a35687ac51dac5a2a0664ca20e7dd7cba6836c7b | PySimpleGUI | 19 | |
153,298 | 62 | 12 | 19 | 244 | 16 | 0 | 90 | 298 | _read | REFACTOR-#3900: add flake8-no-implicit-concat plugin and refactor flake8 error codes (#3901)
Signed-off-by: jeffreykennethli <jkli@ponder.io> | https://github.com/modin-project/modin.git | def _read(cls, path_or_buf, **kwargs):
if cls._validate_hdf_format(path_or_buf=path_or_buf) is None:
ErrorMessage.default_to_pandas(
"File format seems to be `fixed`. For better distribution consider "
+ "saving the file in `table` format. df.to_hdf(format=`t... | 148 | hdf_dispatcher.py | Python | modin/core/io/column_stores/hdf_dispatcher.py | e5e9634357e60925a5a70e56a1d4882d269f533a | modin | 5 | |
43,494 | 74 | 12 | 97 | 1,393 | 23 | 0 | 246 | 983 | upgrade | Have consistent types between the ORM and the migration files (#24044)
We currently don't compare column types between ORM and the migration files. Some columns in the migration files have different types from the same columns in the ORM.
Here, I made effort to match the types in migration files with the
types in O... | https://github.com/apache/airflow.git | def upgrade():
conn = op.get_bind()
with op.batch_alter_table('connection', schema=None) as batch_op:
batch_op.alter_column(
'extra',
existing_type=sa.TEXT(),
type_=sa.Text(),
existing_nullable=True,
)
with op.batch_alter_table('log_templa... | 840 | 0113_2_4_0_compare_types_between_orm_and_db.py | Python | airflow/migrations/versions/0113_2_4_0_compare_types_between_orm_and_db.py | 25537acfa28eebc82a90274840e0e6fb5c91e271 | airflow | 2 | |
279,720 | 33 | 12 | 9 | 148 | 25 | 1 | 37 | 122 | _load_state | Move optimizer methods not related to distributed training to the base class.
PiperOrigin-RevId: 471880396 | https://github.com/keras-team/keras.git | def _load_state(self, dir_path):
# To avoid circular import
from keras.saving.experimental import saving_lib
file_path = tf.io.gfile.join(dir_path, saving_lib.STATE_FILENAME)
if tf.io.gfile.exists(file_path):
loaded_npz = np.load(file_path)
logging.debug(f"Loaded... | @keras_export("keras.optimizers.experimental.Optimizer", v1=[]) | 77 | optimizer.py | Python | keras/optimizers/optimizer_experimental/optimizer.py | 3ba4d8dadb4db52cf066662f5068e4f99ebd87ee | keras | 3 |
34,475 | 64 | 13 | 16 | 168 | 14 | 0 | 92 | 236 | simplify_replacements | Add model like (#14992)
* Add new model like command
* Bad doc-styler
* black and doc-styler, stop fighting!
* black and doc-styler, stop fighting!
* At last
* Clean up
* Typo
* Bad doc-styler
* Bad doc-styler
* All good maybe?
* Use constants
* Add doc and type hints
* More cleanin... | https://github.com/huggingface/transformers.git | def simplify_replacements(replacements):
if len(replacements) <= 1:
# Nothing to simplify
return replacements
# Next let's sort replacements by length as a replacement can only "imply" another replacement if it's shorter.
replacements.sort(key=lambda x: len(x[0]))
idx = 0
whil... | 101 | add_new_model_like.py | Python | src/transformers/commands/add_new_model_like.py | 81156d20cd76c1a43ed44fdbc785e237d60b6896 | transformers | 5 | |
269,031 | 50 | 16 | 12 | 128 | 12 | 0 | 67 | 138 | _set_object_by_path | Expose keras/dtensor package to public
PiperOrigin-RevId: 430366845 | https://github.com/keras-team/keras.git | def _set_object_by_path(object_to_set, path, value):
for i, attr_name in enumerate(path):
if i == len(path) - 1:
# We found the actual attribute to set
if isinstance(attr_name, int):
# This means we are trying to set an element in the array, make sure the
# instance is array like objec... | 80 | layout_map.py | Python | keras/dtensor/layout_map.py | a179ed22f002e2f4a43ae4770348a9b8e1d5a051 | keras | 5 | |
241,679 | 15 | 15 | 10 | 97 | 13 | 0 | 18 | 68 | val_batch_idx | Integrate progress tracking into the progress bar (#11213) | https://github.com/Lightning-AI/lightning.git | def val_batch_idx(self) -> int:
if self.trainer is None:
return 0
if self.trainer.state.fn == "fit":
return self.trainer.fit_loop.epoch_loop.val_loop.epoch_loop.batch_progress.current.processed
return self.trainer.validate_loop.epoch_loop.batch_progress.current.p... | 60 | base.py | Python | pytorch_lightning/callbacks/progress/base.py | 8a549a550cb10189ff1db382f546a40cd1c6c5b3 | lightning | 3 | |
100,776 | 18 | 14 | 7 | 65 | 11 | 0 | 22 | 73 | is_admin | Add Apple M1 to setup.py
add libblas to requirements | https://github.com/deepfakes/faceswap.git | def is_admin(self) -> bool:
try:
retval = os.getuid() == 0
except AttributeError:
retval = ctypes.windll.shell32.IsUserAnAdmin() != 0 # type: ignore
return retval
| 37 | setup.py | Python | setup.py | a586ef6bf3db26752fc1164835e46b6e375576ca | faceswap | 2 | |
165,785 | 8 | 7 | 6 | 28 | 5 | 0 | 8 | 22 | length | TYP: fix mid and length for Interval and Intervalarray (#46472) | https://github.com/pandas-dev/pandas.git | def length(self) -> Index:
return self.right - self.left
| 16 | interval.py | Python | pandas/core/arrays/interval.py | 6d7e004b1fc69942390d953bf21098a786c12c92 | pandas | 1 | |
292,161 | 73 | 15 | 30 | 318 | 27 | 0 | 101 | 456 | async_step_link | Ensure lutron caseta imports set the unique id (#66754) | https://github.com/home-assistant/core.git | async def async_step_link(self, user_input=None):
errors = {}
# Abort if existing entry with matching host exists.
self._async_abort_entries_match({CONF_HOST: self.data[CONF_HOST]})
self._configure_tls_assets()
if (
not self.attempted_tls_validation
... | 199 | config_flow.py | Python | homeassistant/components/lutron_caseta/config_flow.py | 64277058b5ba6fb10029553422695964204f0ebb | core | 8 | |
225,776 | 29 | 8 | 14 | 72 | 4 | 0 | 33 | 104 | test_expand_tokens_with_subtokens | add more unit tests for keyword table (#45)
Co-authored-by: Jerry Liu <jerry@robustintelligence.com> | https://github.com/jerryjliu/llama_index.git | def test_expand_tokens_with_subtokens() -> None:
response = "foo bar, baz, Hello hello wOrld bye"
keywords = extract_keywords_given_response(response)
assert keywords == {
"foo bar",
"foo",
"bar",
"baz",
"hello hello world bye",
"hello",
"world",
... | 37 | test_utils.py | Python | tests/indices/keyword_table/test_utils.py | 3c7e1ad1ea0d6feace926d9749c73c7870397714 | llama_index | 1 | |
138,395 | 80 | 16 | 32 | 234 | 31 | 0 | 107 | 518 | get_objects | [State Observability] Tasks and Objects API (#23912)
This PR implements ray list tasks and ray list objects APIs.
NOTE: You can ignore the merge conflict for now. It is because the first PR was reverted. There's a fix PR open now. | https://github.com/ray-project/ray.git | async def get_objects(self) -> dict:
replies = await asyncio.gather(
*[
self._client.get_object_info(node_id, timeout=DEFAULT_RPC_TIMEOUT)
for node_id in self._client.get_all_registered_raylet_ids()
]
)
worker_stats = []
f... | 140 | state_aggregator.py | Python | dashboard/state_aggregator.py | 30ab5458a7e4ba2351d5e1beef8c8797b5946493 | ray | 5 | |
246,122 | 4 | 6 | 9 | 16 | 3 | 0 | 4 | 11 | _setup_get_username_for_registration | Add a module callback to set username at registration (#11790)
This is in the context of mainlining the Tchap fork of Synapse. Currently in Tchap usernames are derived from the user's email address (extracted from the UIA results, more specifically the m.login.email.identity step).
This change also exports the check_... | https://github.com/matrix-org/synapse.git | def _setup_get_username_for_registration(self) -> Mock:
| 38 | test_password_providers.py | Python | tests/handlers/test_password_providers.py | 2d3bd9aa670eedd299cc03093459929adec41918 | synapse | 1 | |
288,152 | 4 | 6 | 1 | 17 | 4 | 0 | 4 | 11 | attribute_updated | Add configuration entities and device actions for Inovelli Blue Series switch to ZHA (#79106)
* Add Inovelli configutation entities to ZHA
* add device actions
* fix attribute name collision
* add device action tests
* disable remote protection per Inovelli request
* expect_reply to false
* update test for expec... | https://github.com/home-assistant/core.git | def attribute_updated(self, attrid, value):
| 10 | manufacturerspecific.py | Python | homeassistant/components/zha/core/channels/manufacturerspecific.py | 2ed48a9b28f10784a5b8fc27ddae5ae299b43deb | core | 1 | |
154,845 | 51 | 9 | 7 | 76 | 7 | 0 | 61 | 91 | get_keywords | REFACTOR-#5012: Add mypy checks for singleton files in base modin directory (#5013)
Signed-off-by: Jonathan Shi <jhshi@ponder.io> | https://github.com/modin-project/modin.git | def get_keywords() -> Dict[str, str]:
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "$Format:%d$"
git_f... | 38 | _version.py | Python | modin/_version.py | 446148dbf9b66debd0a0dbf9ce778253380d5921 | modin | 1 | |
34,282 | 42 | 15 | 19 | 186 | 15 | 0 | 57 | 262 | _run_split_on_punc | Add FastTokenizer to REALM (#15211)
* Remove BertTokenizer abstraction
* Add FastTokenizer to REALM
* Fix config archive map
* Fix copies
* Update realm.mdx
* Apply suggestions from code review | https://github.com/huggingface/transformers.git | def _run_split_on_punc(self, text, never_split=None):
if never_split is not None and text in never_split:
return [text]
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_pun... | 114 | tokenization_realm.py | Python | src/transformers/models/realm/tokenization_realm.py | 841d979190319098adc8101f9820a02ee3be4c8b | transformers | 7 | |
285,675 | 18 | 10 | 21 | 91 | 17 | 0 | 22 | 75 | copy_func | Next release : reports on steroids (#2349)
* fix gov tests
* refactor insider
* new virtual path extraction
* removed some symbol default params as they're considered critical
* little adjustments
* portfolio refactor
* merge API factory
* add helpers, stocks, crypto, forex
* minor forex change... | https://github.com/OpenBB-finance/OpenBBTerminal.git | def copy_func(f) -> Callable:
g = types.FunctionType(
f.__code__,
f.__globals__,
name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__,
)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
| 60 | api.py | Python | openbb_terminal/api.py | 72b0a9f1ee8b91ad9fd9e76d80d2ccab51ee6d21 | OpenBBTerminal | 1 | |
20,389 | 95 | 17 | 47 | 575 | 36 | 0 | 169 | 795 | format_unencoded | 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 format_unencoded(self, tokensource, outfile):
x = self.xoffset
y = self.yoffset
if not self.nowrap:
if self.encoding:
outfile.write('<?xml version="1.0" encoding="%s"?>\n' %
self.encoding)
else:
ou... | 332 | svg.py | Python | pipenv/patched/notpip/_vendor/pygments/formatters/svg.py | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | pipenv | 15 | |
279,959 | 18 | 14 | 7 | 88 | 8 | 0 | 19 | 100 | from_config | Some changes on the new optimizer:
1. Include `custom_objects` in `from_config` for deserializing custom learning rate.
2. Handle the error of seeing unrecognized variable with a better error message.
PiperOrigin-RevId: 476505974 | https://github.com/keras-team/keras.git | def from_config(cls, config, custom_objects=None):
if "learning_rate" in config:
if isinstance(config["learning_rate"], dict):
config["learning_rate"] = learning_rate_schedule.deserialize(
config["learning_rate"], custom_objects=custom_objects
... | 52 | optimizer.py | Python | keras/optimizers/optimizer_experimental/optimizer.py | 51a6050b936ec87cd684fc1a052f79785ec9aaec | keras | 3 | |
33,933 | 40 | 10 | 40 | 196 | 17 | 1 | 67 | 246 | forward | [Fix doc examples] Add missing from_pretrained (#15044)
* fix doc example - ValueError: Parameter config should be an instance of class `PretrainedConfig`
* Update src/transformers/models/segformer/modeling_segformer.py
Co-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>
* update
Co-a... | https://github.com/huggingface/transformers.git | def forward(self, pixel_values, output_attentions=None, output_hidden_states=None, return_dict=None):
r
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is ... | @add_start_docstrings(
"""
SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden
states) e.g. for ImageNet.
""",
SEGFORMER_START_DOCSTRING,
) | 127 | modeling_segformer.py | Python | src/transformers/models/segformer/modeling_segformer.py | ac224bb0797c1ee6522d814139f3eb0a8947267b | transformers | 5 |
297,740 | 42 | 11 | 25 | 319 | 18 | 0 | 88 | 197 | test_create_area | Add aliases to area registry items (#84294)
* Add aliases to area registry items
* Update test
* Fix WS API | https://github.com/home-assistant/core.git | async def test_create_area(hass, registry, update_events):
# Create area with only mandatory parameters
area = registry.async_create("mock")
assert area == area_registry.AreaEntry(
name="mock", normalized_name=ANY, aliases=set(), id=ANY, picture=None
)
assert len(registry.areas) == 1
... | 191 | test_area_registry.py | Python | tests/helpers/test_area_registry.py | 1a42bd5c4cb51ffbfcaf8d5389b80a228712ac81 | core | 1 | |
273,987 | 4 | 6 | 3 | 17 | 4 | 0 | 4 | 7 | _zero_state_tensors | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def _zero_state_tensors(state_size, batch_size, dtype):
| 23 | legacy_cells.py | Python | keras/layers/rnn/legacy_cells.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 1 | |
30,229 | 71 | 19 | 23 | 198 | 19 | 0 | 112 | 277 | create_github_url | update web code
Co-Authored-By: Peyton Creery <44987569+phcreery@users.noreply.github.com> | https://github.com/spotDL/spotify-downloader.git | def create_github_url(url):
repo_only_url = re.compile(
r"https:\/\/github\.com\/[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}\/[a-zA-Z0-9]+$"
)
re_branch = re.compile("/(tree|blob)/(.+?)/")
# Check if the given url is a url to a GitHub repo. If it is, tell the
# user to use 'git clone' to dow... | 111 | web.py | Python | spotdl/console/web.py | bbb7a02ef889134af71593102bc6f65035ab14cb | spotify-downloader | 3 | |
7,623 | 37 | 15 | 14 | 139 | 20 | 0 | 40 | 114 | load_data_for_viz | Encoder refactor V2 (#2370)
* Added base files and some initial code
* More files created, fleshing out binary feature and corresponding encoders
* Added more schema infra
* Registered all feature encoders
* Separated feature utils infra
* Added all preprocessing classes
* Filled out rest of schema c... | https://github.com/ludwig-ai/ludwig.git | def load_data_for_viz(load_type, model_file_statistics, **kwargs):
supported_load_types = dict(
load_json=load_json,
load_from_file=partial(
load_from_file, dtype=kwargs.get("dtype", int), ground_truth_split=kwargs.get("ground_truth_split", 2)
),
)
loader = supported... | 86 | visualize.py | Python | ludwig/visualize.py | 03b4ab273abd7e22a56bb550b56f3d667200abf9 | ludwig | 3 | |
78,237 | 12 | 10 | 2 | 61 | 8 | 1 | 12 | 17 | classnames | add classnames template tag for generating classnames
- use classnames template tag in shared header template
- add classname as documented variable for the shared header template | https://github.com/wagtail/wagtail.git | def classnames(*classes):
return " ".join([classname.strip() for classname in classes if classname])
@register.simple_tag(takes_context=True) | @register.simple_tag(takes_context=True) | 26 | wagtailadmin_tags.py | Python | wagtail/admin/templatetags/wagtailadmin_tags.py | e2d4cb77458878d7d7076a7aa8b6d590deb99463 | wagtail | 3 |
156,111 | 61 | 14 | 17 | 249 | 30 | 0 | 80 | 183 | repartition | absolufy-imports - No relative - PEP8 (#8796)
Conversation in https://github.com/dask/distributed/issues/5889 | https://github.com/dask/dask.git | def repartition(df, divisions=None, force=False):
token = tokenize(df, divisions)
if isinstance(df, _Frame):
tmp = "repartition-split-" + token
out = "repartition-merge-" + token
dsk = repartition_divisions(
df.divisions, divisions, df._name, tmp, out, force=force
... | 165 | core.py | Python | dask/dataframe/core.py | cccb9d8d8e33a891396b1275c2448c352ef40c27 | dask | 5 | |
293,984 | 8 | 6 | 7 | 25 | 4 | 0 | 8 | 22 | title | Add update entity platform (#68248)
Co-authored-by: Glenn Waters <glenn@watrs.ca> | https://github.com/home-assistant/core.git | def title(self) -> str | None:
return self._attr_title
| 14 | __init__.py | Python | homeassistant/components/update/__init__.py | 073fb40b79cf8aa06790fdceb23b6857db888c99 | core | 1 | |
299,378 | 19 | 8 | 2 | 28 | 3 | 0 | 19 | 40 | shuffle | Improve repeat and shuffle support for Squeezebox (#70941) | https://github.com/home-assistant/core.git | def shuffle(self):
# Squeezebox has a third shuffle mode (album) not recognized by Home Assistant
return self._player.shuffle == "song"
| 14 | media_player.py | Python | homeassistant/components/squeezebox/media_player.py | 0264f060e4fc988f3a0442ba8f951677816c11ea | core | 1 | |
255,418 | 4 | 6 | 9 | 16 | 2 | 0 | 4 | 11 | test_case_connect_partially_no_name_collision | Use Python type annotations rather than comments (#3962)
* These have been supported since Python 3.5.
ONNX doesn't support Python < 3.6, so we can use the annotations.
Diffs generated by https://pypi.org/project/com2ann/.
Signed-off-by: Gary Miguel <garymiguel@microsoft.com>
* Remove MYPY conditional logi... | https://github.com/onnx/onnx.git | def test_case_connect_partially_no_name_collision(self) -> None:
| 37 | compose_test.py | Python | onnx/test/compose_test.py | 83fa57c74edfd13ddac9548b8a12f9e3e2ed05bd | onnx | 1 | |
35,663 | 9 | 9 | 3 | 38 | 6 | 0 | 9 | 34 | freeze_base_model | Add Data2Vec (#15507)
* Add data2vec model cloned from roberta
* Add checkpoint conversion script
* Fix copies
* Update docs
* Add checkpoint conversion script
* Remove fairseq data2vec_text script and fix format
* Add comment on where to get data2vec_text.py
* Remove mock implementation cheat.py ... | https://github.com/huggingface/transformers.git | def freeze_base_model(self):
for param in self.data2vec_audio.parameters():
param.requires_grad = False
| 22 | modeling_data2vec_audio.py | Python | src/transformers/models/data2vec/modeling_data2vec_audio.py | df5a4094a6e3f98f2cb2058cdb688fcc3f453220 | transformers | 2 | |
244,211 | 11 | 6 | 10 | 18 | 4 | 0 | 11 | 17 | split_batch | [Tools] Support respliting data_batch with tag (#7641)
* support respliting data_batch with tag
* add citations
* add a unit test
* fix lint | https://github.com/open-mmlab/mmdetection.git | def split_batch(img, img_metas, kwargs):
# only stack img in the batch | 94 | split_batch.py | Python | mmdet/utils/split_batch.py | c6f467fe9baccc281b0695368c1eae14d5d21fd5 | mmdetection | 4 | |
181,691 | 16 | 10 | 11 | 69 | 14 | 0 | 16 | 77 | test_memory_6 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | https://github.com/EpistasisLab/tpot.git | def test_memory_6():
tpot_obj = TPOTClassifier(
random_state=42,
population_size=1,
offspring_size=2,
generations=1,
config_dict='TPOT light',
memory=str,
verbosity=0
)
assert_raises(ValueError, tpot_obj._setup_memory)
| 45 | tpot_tests.py | Python | tests/tpot_tests.py | 388616b6247ca4ea8de4e2f340d6206aee523541 | tpot | 1 | |
181,726 | 9 | 9 | 3 | 34 | 5 | 0 | 9 | 18 | test_conf_dict_2 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | https://github.com/EpistasisLab/tpot.git | def test_conf_dict_2():
tpot_obj = TPOTClassifier(config_dict=tpot_mdr_classifier_config_dict)
assert tpot_obj.config_dict == tpot_mdr_classifier_config_dict
| 19 | tpot_tests.py | Python | tests/tpot_tests.py | 388616b6247ca4ea8de4e2f340d6206aee523541 | tpot | 1 | |
281,429 | 65 | 18 | 37 | 334 | 28 | 0 | 75 | 258 | get_defi_protocols | Features(crypto): added new commands to defi menu (#1169)
* adding new defi features and refactoring existing ones
* added tests and docs
* added zlot to ignored words
* markdown lint
* fixed pr issues
* fix hugo main.yml
* fix hugo main.yml
* added tests
* fixed prt issue
* added iv_surface... | https://github.com/OpenBB-finance/OpenBBTerminal.git | def get_defi_protocols() -> pd.DataFrame:
response = requests.get(API_URL + "/protocols")
columns = [
"name",
"symbol",
"category",
"chains",
"change_1h",
"change_1d",
"change_7d",
"tvl",
"url",
"description",
"chain",... | 184 | llama_model.py | Python | gamestonk_terminal/cryptocurrency/defi/llama_model.py | d334d5e0878961d2b6cfda82271693d457047bee | OpenBBTerminal | 4 | |
126,674 | 27 | 13 | 10 | 112 | 14 | 0 | 32 | 110 | test_failed_runtime_env_setup | Convert job_manager to be async (#27123)
Updates jobs api
Updates snapshot api
Updates state api
Increases jobs api version to 2
Signed-off-by: Alan Guo aguo@anyscale.com
Why are these changes needed?
follow-up for #25902 (comment) | https://github.com/ray-project/ray.git | async def test_failed_runtime_env_setup(self, job_manager):
run_cmd = f"python {_driver_script_path('override_env_var.py')}"
job_id = await job_manager.submit_job(
entrypoint=run_cmd, runtime_env={"working_dir": "s3://does_not_exist.zip"}
)
await async_wait_for_cond... | 59 | test_job_manager.py | Python | dashboard/modules/job/tests/test_job_manager.py | 326b5bd1acc6d3d00ab0546e4ae45da6bed501f7 | ray | 1 | |
48,723 | 2 | 6 | 6 | 13 | 2 | 0 | 2 | 9 | test_empty_html_checkbox_not_required | Fix BooleanField's allow_null behavior (#8614)
* Fix BooleanField's allow_null behavior
* Update rest_framework.fields
- Use .get with default value for 'allow_null' kwarg in BooleanField's
init | https://github.com/encode/django-rest-framework.git | def test_empty_html_checkbox_not_required(self):
| 51 | test_fields.py | Python | tests/test_fields.py | 1fbe16a8d26ff5be64797cafb7004898f72ca52b | django-rest-framework | 1 | |
130,091 | 89 | 12 | 6 | 125 | 14 | 0 | 118 | 151 | get_incremental_data | [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 get_incremental_data(self, day=0):
start = self._get_day_slice(day - 1)
end = self._get_day_slice(day)
available_data = Subset(self.dataset, list(range(start, end)))
train_n = int(0.8 * (end - start)) # 80% train data, 20% validation data
return random_split(avail... | 75 | tune-serve-integration-mnist.py | Python | doc/source/tune/_tutorials/tune-serve-integration-mnist.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 1 | |
45,040 | 7 | 8 | 16 | 26 | 6 | 0 | 7 | 21 | test_set_serialize_call_old_signature | Add params dag_id, task_id etc to XCom.serialize_value (#19505)
When implementing a custom XCom backend, in order to store XCom objects organized by dag_id, run_id etc, we need to pass those params to `serialize_value`. | https://github.com/apache/airflow.git | def test_set_serialize_call_old_signature(self, get_import, session):
serialize_watcher = MagicMock()
| 82 | test_xcom.py | Python | tests/models/test_xcom.py | 56285eee04285d8b6fac90911248d7e9dd5504d8 | airflow | 1 | |
120,210 | 9 | 8 | 2 | 31 | 3 | 0 | 9 | 11 | mock_4x8x16_devices | [mesh_utils] Support creating device meshes for hybrid networks
Also makes some NFCs to other mesh_utils code.
PiperOrigin-RevId: 442581767 | https://github.com/google/jax.git | def mock_4x8x16_devices(one_device_per_chip):
return mock_devices(4, 8, 16, 'TPU v4', one_device_per_chip)
| 19 | mesh_utils_test.py | Python | tests/mesh_utils_test.py | 3f9e45e0c5b035de27b14588cd3b4cfd5f3c1f04 | jax | 1 | |
248,552 | 30 | 10 | 20 | 135 | 14 | 0 | 49 | 247 | test_random_users_cannot_send_state_before_first_pl | EventAuthTestCase: build events for the right room version
In practice, when we run the auth rules, all of the events have the right room
version. Let's stop building Room V1 events for these tests and use the right
version. | https://github.com/matrix-org/synapse.git | def test_random_users_cannot_send_state_before_first_pl(self):
creator = "@creator:example.com"
joiner = "@joiner:example.com"
auth_events = [
_create_event(RoomVersions.V1, creator),
_join_event(RoomVersions.V1, creator),
_join_event(RoomVersions.V1,... | 89 | test_event_auth.py | Python | tests/test_event_auth.py | 2959184a42398277ff916206235b844a8f7be5d7 | synapse | 1 | |
276,845 | 23 | 8 | 4 | 41 | 4 | 0 | 25 | 71 | get | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def get(self, object_id):
# Explicitly check for `None` internally to make external calling code a
# bit cleaner.
if object_id is None:
return
return self._obj_ids_to_obj.get(object_id)
| 23 | generic_utils.py | Python | keras/utils/generic_utils.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 2 | |
274,615 | 20 | 12 | 9 | 89 | 8 | 0 | 24 | 67 | get | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def get(identifier):
if isinstance(identifier, dict):
return deserialize(identifier)
elif isinstance(identifier, str):
return deserialize(str(identifier))
elif callable(identifier):
return identifier
else:
raise ValueError(f"Could not interpret metric identifier: {id... | 51 | __init__.py | Python | keras/metrics/__init__.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.