complexity int64 1 139 | fun_name stringlengths 1 80 | code stringlengths 101 62.2k | commit_id stringlengths 40 40 | ast_errors stringlengths 0 3.11k | ast_levels int64 6 36 | file_name stringlengths 5 79 | n_ast_nodes int64 17 19.2k | commit_message stringlengths 3 15.3k | d_id int64 12 121k | n_ast_errors int64 0 9 | n_whitespaces int64 4 10.8k | token_counts int64 5 3.06k | vocab_size int64 4 1.11k | id int64 20 338k | n_words int64 4 4.82k | repo stringlengths 3 22 | n_identifiers int64 2 176 | path stringlengths 7 134 | language stringclasses 1
value | nloc int64 1 413 | documentation dict | url stringlengths 31 59 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8 | send_robust | def send_robust(self, sender, **named):
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response)... | 102ca3bf902d7af977b0528f89fbd23415825fe3 | 17 | signals.py | 1,481 | ref(hybrid-cloud): Enforce silo isolation on many model tests (#40946)
Greatly increase the number of stable hybrid cloud model tests, adding more hybrid cloud service interfaces. | 18,372 | 0 | 563 | 128 | 190 | 88,296 | 352 | sentry | 79 | src/sentry/signals.py | Python | 16 | {
"docstring": "\n A reimplementation of send_robust which logs failures, thus recovering stacktraces.\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 10
} | https://github.com/getsentry/sentry.git | |
2 | convert_exception_to_response | def convert_exception_to_response(get_response):
if asyncio.iscoroutinefunction(get_response):
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 7 | exception.py | 26 | Refs #33476 -- Reformatted code with Black. | 50,777 | 0 | 10 | 35 | 4 | 204,538 | 4 | django | 4 | django/core/handlers/exception.py | Python | 9 | {
"docstring": "\n Wrap the given get_response callable in exception-to-response conversion.\n\n All exceptions will be converted. All known 4xx exceptions (Http404,\n PermissionDenied, MultiPartParserError, SuspiciousOperation) will be\n converted to the appropriate response, and all other exceptions wil... | https://github.com/django/django.git | |
2 | convert_python_to_json | def convert_python_to_json(self, par_data_dic, par_json_file=""):
if par_json_file:
with open(par_json_file, "w") as outfile:
return json.dump(par_data_dic, outfile)
else:
return json.dump(par_data_dic)
| f0af0c43340763724f139fa68aa1e5a9ffe458b4 | 13 | JsonParser.py | 75 | refactor: clean code
Signed-off-by: slowy07 <slowy.arfy@gmail.com> | 4,347 | 0 | 75 | 43 | 16 | 22,466 | 17 | Python | 8 | JsonParser.py | Python | 6 | {
"docstring": "\n this function converts dictionary of data to json string and store it in json file if\n json file pass provided if not it only returns the json string\n args:\n par_data_dic: dictionary of data\n par_json_file: the output json file\n return: json ... | https://github.com/geekcomputers/Python.git | |
2 | _maybe_broadcast_to_outputs | def _maybe_broadcast_to_outputs(self, outputs, objects):
if not self._should_broadcast(objects):
return objects
# When there is more than one Model output, this is needed to keep
# each Metric / Loss separate. When there is only one Model output,
# the user-supplied... | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 12 | compile_utils.py | 62 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,680 | 0 | 101 | 54 | 39 | 271,043 | 48 | keras | 10 | keras/engine/compile_utils.py | Python | 6 | {
"docstring": "Determines if losses / metrics should be applied to all outputs.\n\n NOTE: This method should only be called for Metrics / Losses, not for\n y_true / sample_weight.\n\n Args:\n outputs: Model predictions.\n objects: Arbitrary nested structure (e.g. of losses or m... | https://github.com/keras-team/keras.git | |
1 | test_post_save_add_redirect | def test_post_save_add_redirect(self):
post_data = {"name": "John Doe"}
self.assertEqual(Person.objects.count(), 0)
response = self.client.post(
reverse("admin_custom_urls:admin_custom_urls_person_add"), post_data
)
persons = Person.objects.all()
self... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 12 | tests.py | 146 | Refs #33476 -- Reformatted code with Black. | 51,853 | 0 | 120 | 87 | 23 | 207,061 | 28 | django | 18 | tests/admin_custom_urls/tests.py | Python | 12 | {
"docstring": "\n ModelAdmin.response_post_save_add() controls the redirection after\n the 'Save' button has been pressed when adding a new object.\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 16,
"vocab_size": 15
} | https://github.com/django/django.git | |
2 | prepare_metadata | def prepare_metadata(self):
# type: () -> None
assert self.source_dir
with indent_log():
self.metadata_directory = self._generate_metadata()
# Act on the newly generated metadata, based on the name and version.
if not self.name:
self._set_requir... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 10 | req_install.py | 88 | upd; format | 12,377 | 0 | 123 | 47 | 31 | 60,993 | 34 | transferlearning | 10 | .venv/lib/python3.8/site-packages/pip/_internal/req/req_install.py | Python | 9 | {
"docstring": "Ensure that project metadata is available.\n\n Under PEP 517, call the backend hook to prepare the metadata.\n Under legacy processing, call setup.py egg-info.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 23,
"vocab_size": 20
} | https://github.com/jindongwang/transferlearning.git | |
5 | set_terminator | def set_terminator(self, term):
if isinstance(term, str) and self.use_encoding:
term = bytes(term, self.encoding)
elif isinstance(term, int) and term < 0:
raise ValueError('the number of received bytes must be positive')
self.terminator = term
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 11 | asynchat.py | 84 | add python 3.10.4 for windows | 55,951 | 0 | 81 | 52 | 26 | 220,267 | 31 | XX-Net | 11 | python3.10.4/Lib/asynchat.py | Python | 6 | {
"docstring": "Set the input delimiter.\n\n Can be a fixed string of any length, an integer, or None.\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 16,
"vocab_size": 16
} | https://github.com/XX-net/XX-Net.git | |
2 | _object2proto | def _object2proto(self) -> RunClassMethodSMPCAction_PB:
return RunClassMethodSMPCAction_PB(
path=self.path,
_self=sy.serialize(self._self),
args=list(map(lambda x: sy.serialize(x), self.args)),
kwargs={k: sy.serialize(v) for k, v in self.kwargs.items()},... | 5dad7d57c63189553eaa303ece930c639c1b6196 | 15 | run_class_method_smpc_action.py | 173 | modified action creation context to sharetensor level
created global location for context retrieval during multiplication | 91 | 0 | 133 | 115 | 24 | 612 | 24 | PySyft | 20 | packages/syft/src/syft/core/node/common/action/run_class_method_smpc_action.py | Python | 25 | {
"docstring": "Returns a protobuf serialization of self.\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms the current object into the corresponding\n Protobuf object so that it can be further serialized.\n\n :return: returns a protobuf object\n... | https://github.com/OpenMined/PySyft.git | |
17 | pytest_collection_modifyitems | def pytest_collection_modifyitems(session, config, items):
not_services = set(config.getoption("--not-service"))
if config.getoption("--all-services"):
skip_exclude_services(not_services, items)
if config.getoption("--only-service") or config.getoption("--only-services"):
warn... | 38a7efafd45dbe64b292593461330a2de6499bb1 | @pytest.fixture(scope="session") | 20 | conftest.py | 558 | Cleanup pytest service CLI options | 10,960 | 1 | 615 | 284 | 76 | 53,964 | 160 | prefect | 31 | tests/conftest.py | Python | 48 | {
"docstring": "\n Update tests to skip in accordance with service requests\n ",
"language": "en",
"n_whitespaces": 16,
"n_words": 9,
"vocab_size": 9
} | https://github.com/PrefectHQ/prefect.git |
1 | test_approve_task_and_workflow | def test_approve_task_and_workflow(self):
# Unset WAGTAIL_FINISH_WORKFLOW_ACTION - default action should be to publish
del settings.WAGTAIL_FINISH_WORKFLOW_ACTION
# Connect a mock signal handler to page_published signal
mock_handler = mock.MagicMock()
page_published.conn... | d10f15e55806c6944827d801cd9c2d53f5da4186 | 14 | test_workflows.py | 365 | Reformat with black | 15,869 | 0 | 513 | 223 | 89 | 72,276 | 135 | wagtail | 38 | wagtail/admin/tests/test_workflows.py | Python | 33 | {
"docstring": "\n This posts to the approve task view and checks that the page was approved and published\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 16,
"vocab_size": 14
} | https://github.com/wagtail/wagtail.git | |
3 | delete_accounting_dimension | def delete_accounting_dimension(doc):
doclist = get_doctypes_with_dimensions()
frappe.db.sql(
% ("%s", ", ".join(["%s"] * len(doclist))), # nosec
tuple([doc.fieldname] + doclist),
)
frappe.db.sql(
% ("%s", ", ".join(["%s"] * len(doclist))), # nosec
tuple([doc.fieldname] + doclist),
)
budget_aga... | 494bd9ef78313436f0424b918f200dab8fc7c20b | @frappe.whitelist() | 14 | accounting_dimension.py | 285 | style: format code with black | 13,719 | 1 | 40 | 155 | 39 | 64,771 | 57 | erpnext | 22 | erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py | Python | 26 | {
"docstring": "\n\t\tDELETE FROM `tabCustom Field`\n\t\tWHERE fieldname = %s\n\t\tAND dt IN (%s)\n\t\tDELETE FROM `tabProperty Setter`\n\t\tWHERE field_name = %s\n\t\tAND doc_type IN (%s)",
"language": "en",
"n_whitespaces": 18,
"n_words": 24,
"vocab_size": 16
} | https://github.com/frappe/erpnext.git |
1 | _dispatch_run_batch | def _dispatch_run_batch(self, **kwargs):
return self._dispatch_run_general(self.run_batch, **kwargs)
| 738e008020f146ff9820c290311782f515749c48 | 8 | base.py | 35 | Add `run_batch` method to all nodes and `Pipeline` to allow batch querying (#2481)
* Add run_batch methods for batch querying
* Update Documentation & Code Style
* Fix mypy
* Update Documentation & Code Style
* Fix mypy
* Fix linter
* Fix tests
* Update Documentation & Code Style
* Fix tests
... | 75,061 | 0 | 20 | 21 | 6 | 257,301 | 6 | haystack | 5 | haystack/nodes/base.py | Python | 2 | {
"docstring": "\n The Pipelines call this method when run_batch() is executed. This method in turn executes the\n _dispatch_run_general() method with the correct run method.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 22,
"vocab_size": 19
} | https://github.com/deepset-ai/haystack.git | |
1 | test_local_user_not_exists | def test_local_user_not_exists(self):
user = "@unknown:" + self.hs.config.server.server_name
self._test_status(
users=[user],
expected_statuses={
user: {
"exists": False,
},
},
expected_failures... | 250104d357c17a1c87fa46af35bbf3612f4ef171 | 13 | test_account.py | 80 | Implement account status endpoints (MSC3720) (#12001)
See matrix-org/matrix-doc#3720
Co-authored-by: Sean Quah <8349537+squahtx@users.noreply.github.com> | 71,189 | 0 | 139 | 49 | 17 | 246,381 | 18 | synapse | 11 | tests/rest/client/test_account.py | Python | 11 | {
"docstring": "Tests that the account status endpoints correctly reports that a user doesn't\n exist.\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 13,
"vocab_size": 12
} | https://github.com/matrix-org/synapse.git | |
3 | add | def add(self, level, message, extra_tags=""):
if not message:
return
# Check that the message level is not less than the recording level.
level = int(level)
if level < self.level:
return
# Add the message.
self.added_new = True
mes... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 9 | base.py | 96 | Refs #33476 -- Reformatted code with Black. | 50,670 | 0 | 128 | 58 | 31 | 204,175 | 43 | django | 10 | django/contrib/messages/storage/base.py | Python | 9 | {
"docstring": "\n Queue a message to be stored.\n\n The message is only queued if it contained something and its level is\n not less than the recording level (``self.level``).\n ",
"language": "en",
"n_whitespaces": 55,
"n_words": 26,
"vocab_size": 23
} | https://github.com/django/django.git | |
14 | read_shp | def read_shp(path, simplify=True, geom_attrs=True, strict=True):
msg = (
"read_shp is deprecated and will be removed in 3.0."
"See https://networkx.org/documentation/latest/auto_examples/index.html#geospatial."
)
warnings.warn(msg, DeprecationWarning, stacklevel=2)
try:
from... | cc1db275efc709cb964ce88abbfa877798d58c10 | 20 | nx_shp.py | 463 | Minor improvements from general code readthrough (#5414)
* Add deprecated directive to reversed docstring.
* Add missing dep directives to shpfiles.
* Remove defn of INF sentinel.
* typo.
* str -> comment in forloop.
* STY: appropriate casing for var name. | 41,911 | 0 | 573 | 280 | 109 | 176,450 | 150 | networkx | 50 | networkx/readwrite/nx_shp.py | Python | 41 | {
"docstring": "Generates a networkx.DiGraph from shapefiles.\n\n .. deprecated:: 2.6\n\n read_shp is deprecated and will be removed in NetworkX 3.0.\n See https://networkx.org/documentation/latest/auto_examples/index.html#geospatial.\n\n Point geometries are\n translated into nodes, lines into e... | https://github.com/networkx/networkx.git | |
1 | __copy__ | def __copy__(self):
# Shallow copy.
return self.__constructor__(
self.gpu_manager, self.key, self._length_cache, self._width_cache
)
| 2bb9a1fab7b0092974853e616dfd5e7ed98f085d | 8 | partition.py | 43 | REFACTOR-#5363: introduce partition constructor; move `add_to_apply_calls` impl in base class (#5354)
Signed-off-by: Myachev <anatoly.myachev@intel.com> | 36,353 | 0 | 51 | 27 | 12 | 155,358 | 12 | modin | 7 | modin/core/execution/ray/implementations/cudf_on_ray/partitioning/partition.py | Python | 4 | {
"docstring": "\n Create a copy of this object.\n\n Returns\n -------\n cuDFOnRayDataframePartition\n A copy of this object.\n ",
"language": "en",
"n_whitespaces": 61,
"n_words": 14,
"vocab_size": 10
} | https://github.com/modin-project/modin.git | |
2 | disconnect | def disconnect(self):
if self.is_connected is False:
return
self.connection.close()
self.is_connected = False
return self.is_connected
| fc9776d9b342f873cbb3f36fd39955b9e1ea6f76 | 8 | sqlite_handler.py | 52 | added connection_args and connection_args_example dicts | 25,459 | 0 | 59 | 30 | 10 | 115,431 | 13 | mindsdb | 5 | mindsdb/integrations/handlers/sqlite_handler/sqlite_handler.py | Python | 6 | {
"docstring": "\r\n Close any existing connections.\r\n ",
"language": "en",
"n_whitespaces": 19,
"n_words": 4,
"vocab_size": 4
} | https://github.com/mindsdb/mindsdb.git | |
2 | for_each_smith | def for_each_smith(self, fn, selector=None, row=None, col=None) -> "FigureWidget":
for obj in self.select_smiths(selector=selector, row=row, col=col):
fn(obj)
return self
| c95b4fa4388f29e50b6966e45c94c5980013a01d | 9 | _figurewidget.py | 73 | type annotations for chainable Figure methods | 68,409 | 0 | 49 | 48 | 17 | 240,298 | 17 | plotly.py | 8 | packages/python/plotly/plotly/graph_objs/_figurewidget.py | Python | 32 | {
"docstring": "\n Apply a function to all smith objects that satisfy the\n specified selection criteria\n\n Parameters\n ----------\n fn:\n Function that inputs a single smith object.\n selector: dict, function, or None (default None)\n Dict to use as s... | https://github.com/plotly/plotly.py.git | |
3 | is_homepage | def is_homepage(self) -> bool:
return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html')
previous_page: Optional[Page]
next_page: Optional[Page]
parent: Optional[Section]
children: None = None
is_section: bool = False
... | 32359f3e93f5ca7778b9f7c3d6d92f49a629c84c | 9 | pages.py | 143 | Relative links end with slash even for homepage links (#3022)
Fixes #3015 | 57,470 | 0 | 99 | 30 | 27 | 225,565 | 36 | mkdocs | 17 | mkdocs/structure/pages.py | Python | 3 | {
"docstring": "Evaluates to `True` for the homepage of the site and `False` for all other pages.The [page][mkdocs.structure.pages.Page] object for the previous page or `None`.\n The value will be `None` if the current page is the first item in the site navigation\n or if the current page is not included in the... | https://github.com/mkdocs/mkdocs.git | |
1 | test_solo_route_send_immediate_msg_with_reply | def test_solo_route_send_immediate_msg_with_reply() -> None:
node = MockNode()
destination = SpecificLocation()
server = VirtualServerConnection(node=node)
connection = VirtualClientConnection(server=server)
h_solo = SoloRoute(destination=destination, connection=connection)
msg = construct... | dadbb7dfe1062f94e2d95e7670d0a7a4602460c4 | 9 | route_test.py | 114 | fixed signature of send_immediate_msg_with_reply
- changing default timeouts | 187 | 0 | 75 | 69 | 25 | 1,393 | 31 | PySyft | 18 | packages/syft/tests/syft/core/io/route_test.py | Python | 13 | {
"docstring": "Test SoloRoute.send_immediate_msg_with_reply method works.",
"language": "en",
"n_whitespaces": 3,
"n_words": 4,
"vocab_size": 4
} | https://github.com/OpenMined/PySyft.git | |
11 | validate_parameter_constraints | def validate_parameter_constraints(parameter_constraints, params, caller_name):
if len(set(parameter_constraints) - set(params)) != 0:
raise ValueError(
f"The parameter constraints {list(parameter_constraints)}"
" contain unexpected parameters"
f" {set(parameter_cons... | 91f02270a8f49e3e52882dc0fa634eff4d138fc8 | 25 | _param_validation.py | 330 | MAINT Add one-sided set differences for clarity in param validation (#23772)
Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com> | 76,307 | 0 | 590 | 137 | 117 | 260,513 | 181 | scikit-learn | 20 | sklearn/utils/_param_validation.py | Python | 32 | {
"docstring": "Validate types and values of given parameters.\n\n Parameters\n ----------\n parameter_constraints : dict or {\"no_validation\"}\n If \"no_validation\", validation is skipped for this parameter.\n\n If a dict, it must be a dictionary `param_name: list of constraints`.\n A... | https://github.com/scikit-learn/scikit-learn.git | |
3 | notify_clients | async def notify_clients(cls) -> None:
while not cls.STOP:
await asyncio.sleep(cls.UPDATE_INTERVALS)
if cls.EVENT_QUEUE:
await cls.broadcast_estimations()
| b1dfc9a172440e9c9736566f326ba339ff559604 | 12 | event_queue.py | 61 | Release new queue beta (#1969)
* queue-refactor-backend (#1489)
* queue-refactor-backend
- create a template for the new design
* queue-refactor-backend
- clean after the old queue
* queue-refactor-backend
- add basic test to websocket endpoint
* queue-refactor-backend
- small fix
* queue-re... | 43,215 | 0 | 65 | 34 | 13 | 180,689 | 14 | gradio | 8 | gradio/event_queue.py | Python | 8 | {
"docstring": "\n Notify clients about events statuses in the queue periodically.\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 9
} | https://github.com/gradio-app/gradio.git | |
4 | async_purge_expired_orphaned_devices | def async_purge_expired_orphaned_devices(self) -> None:
now_time = time.time()
for deleted_device in list(self.deleted_devices.values()):
if deleted_device.orphaned_timestamp is None:
continue
if (
deleted_device.orphaned_timestamp + ORPH... | 56278a4421209a475558600d220906e35df80fe0 | 11 | device_registry.py | 93 | Simplify device registry (#77715)
* Simplify device registry
* Fix test fixture
* Update homeassistant/helpers/device_registry.py
Co-authored-by: epenet <6771947+epenet@users.noreply.github.com>
* Update device_registry.py
* Remove dead code
Co-authored-by: epenet <6771947+epenet@users.noreply.github... | 104,308 | 0 | 140 | 57 | 22 | 305,522 | 26 | core | 11 | homeassistant/helpers/device_registry.py | Python | 15 | {
"docstring": "Purge expired orphaned devices from the registry.\n\n We need to purge these periodically to avoid the database\n growing without bound.\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 20,
"vocab_size": 18
} | https://github.com/home-assistant/core.git | |
1 | test_https_bad_referer | def test_https_bad_referer(self):
req = self._get_POST_request_with_token()
req._is_secure_override = True
req.META["HTTP_HOST"] = "www.example.com"
req.META["HTTP_REFERER"] = "https://www.evil.org/somepage"
req.META["SERVER_PORT"] = "443"
mw = CsrfViewMiddleware... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 9 | tests.py | 138 | Refs #33476 -- Reformatted code with Black. | 50,106 | 0 | 156 | 78 | 36 | 202,398 | 42 | django | 13 | tests/csrf_tests/tests.py | Python | 14 | {
"docstring": "\n A POST HTTPS request with a bad referer is rejected\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 10
} | https://github.com/django/django.git | |
4 | call | def call(cls, map_func, reduce_func=None, **call_kwds):
if isinstance(map_func, str):
| 58bbcc37477866d19c8b092a0e1974a4f0baa586 | 7 | groupby.py | 36 | REFACTOR-#2656: Update modin to fit algebra (code only) (#3717)
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Co-authored-by: Vasily Litvinov <vasilij.n.litvinov@intel.com>
Co-authored-by: Alexey Prutskov <alexey.prutskov@intel.com>
Co-authored-by: Devin Petersohn <devin-petersohn@users.noreply.github.com... | 35,226 | 0 | 22 | 107 | 8 | 153,042 | 8 | modin | 7 | modin/core/dataframe/algebra/groupby.py | Python | 14 | {
"docstring": "\n Build template GroupBy aggregation function.\n\n Resulted function is applied in parallel via TreeReduce algorithm.\n\n Parameters\n ----------\n map_func : str, dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame\n If `str` this parameter wil... | https://github.com/modin-project/modin.git | |
9 | _evaluate | def _evaluate(model, args, val_dataset, *, padder_mode, num_flow_updates=None, batch_size=None, header=None):
batch_size = batch_size or args.batch_size
device = torch.device(args.device)
model.eval()
if args.distributed:
sampler = torch.utils.data.distributed.DistributedSampler(val_datas... | 3aa2a93d1e2df140866e1937767b83dc27dcf89e | 13 | train.py | 190 | RAFT training reference Improvement (#5590)
* Change optical flow train.py function name from validate to evaluate so it is similar to other references
* Add --device as parameter and enable to run in non distributed mode
* Format with ufmt
* Fix unneccessary param and bug
* Enable saving the optimizer and... | 46,885 | 0 | 119 | 256 | 33 | 192,382 | 43 | vision | 23 | references/optical_flow/train.py | Python | 35 | {
"docstring": "Helper function to compute various metrics (epe, etc.) for a model on a given dataset.\n\n We process as many samples as possible with ddp, and process the rest on a single worker.\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 32,
"vocab_size": 27
} | https://github.com/pytorch/vision.git | |
4 | _create_standalone_pip | def _create_standalone_pip() -> Generator[str, None, None]:
source = pathlib.Path(pip_location).resolve().parent
# Return the current instance if `source` is not a directory. We can't build
# a zip from this, and it likely means the instance is already standalone.
if not source.is_dir():
y... | c69d55f7c82d5ae2cce542bcfb98d043ca4836a0 | 18 | build_env.py | 244 | Vendor in pip 22.1.2 | 3,739 | 0 | 181 | 142 | 63 | 21,259 | 77 | pipenv | 28 | pipenv/patched/notpip/_internal/build_env.py | Python | 19 | {
"docstring": "Create a \"standalone pip\" zip file.\n\n The zip file's content is identical to the currently-running pip.\n It will be used to install requirements into the build environment.\n ",
"language": "en",
"n_whitespaces": 36,
"n_words": 27,
"vocab_size": 24
} | https://github.com/pypa/pipenv.git | |
1 | _get_ray_cr_with_overrides | def _get_ray_cr_with_overrides() -> dict:
cr = _get_basic_ray_cr()
cr["spec"]["workerGroupSpecs"][0]["rayStartParams"]["memory"] = "300000000"
# num-gpus rayStartParam with no gpus in container limits
cr["spec"]["workerGroupSpecs"][0]["rayStartParams"]["num-gpus"] = "100"
# num-gpus rayStartPar... | 7d3ceb222c8af98a5c101b1c28ab37ffcb0a3793 | 12 | test_autoscaling_config.py | 169 | [kuberay][autoscaler] Improve CPU, GPU, and memory detection. (#26219)
This PR improves the autoscaler's resource detection logic | 27,527 | 0 | 65 | 86 | 24 | 124,152 | 38 | ray | 4 | python/ray/tests/kuberay/test_autoscaling_config.py | Python | 8 | {
"docstring": "CR with memory, cpu, and gpu overrides from rayStartParams.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/ray-project/ray.git | |
1 | test_from_percentage | def test_from_percentage(percentage, expected_result):
assert _from_fan_percentage(percentage) == expected_result
| b52a8ba37a5e5e05b80beddff06b116371941d86 | 8 | test_util.py | 26 | Bump pytradfri to 8.0.1 and fix fan preset mode "Auto" bug (#63920)
* Move util functions
* Fix errors
* Revert changes
* Fix tests
* Use self.async_set_percentage()
* Fix calculation functions and associated tests
* Handle case of 0
* Update tests/components/tradfri/test_util.py
Co-authored-by... | 108,183 | 0 | 13 | 15 | 7 | 309,483 | 7 | core | 4 | tests/components/tradfri/test_util.py | Python | 2 | {
"docstring": "Test that we can convert percentage value to fan speed.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/home-assistant/core.git | |
1 | set_3d_properties | def set_3d_properties(self, z=0, zdir='z'):
self._z = z
self._dir_vec = get_dir_vector(zdir)
self.stale = True
| df6f95703b60348e01603f98a439b133da2938a0 | 8 | art3d.py | 54 | Improve mpl_toolkit documentation | 23,827 | 0 | 41 | 32 | 11 | 109,920 | 13 | matplotlib | 8 | lib/mpl_toolkits/mplot3d/art3d.py | Python | 4 | {
"docstring": "\n Set the *z* position and direction of the text.\n\n Parameters\n ----------\n z : float\n The z-position in 3D space.\n zdir : {'x', 'y', 'z', 3-tuple}\n The direction of the text. Default: 'z'.\n See `.get_dir_vector` for a descri... | https://github.com/matplotlib/matplotlib.git | |
2 | test_nav_missing_page | def test_nav_missing_page(self):
nav_cfg = [
{'Home': 'index.md'},
]
expected = dedent(
)
cfg = load_config(nav=nav_cfg, site_url='http://example.com/')
fs = [
File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'... | 372384d8102ddb4be6360f44d1bfddb8b45435a4 | 11 | nav_tests.py | 240 | Some manual changes ahead of formatting code with Black | 57,224 | 0 | 193 | 146 | 37 | 224,171 | 47 | mkdocs | 25 | mkdocs/tests/structure/nav_tests.py | Python | 21 | {
"docstring": "\n Page(title='Home', url='/')\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 2,
"vocab_size": 2
} | https://github.com/mkdocs/mkdocs.git | |
1 | test_large_remote_call | def test_large_remote_call(call_ray_start_shared):
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
| 297341e107daee1ea3aff991ae8ea8c90993c683 | 10 | test_client.py | 29 | [Test][Client] Only start ray once in client tests (#28835)
It looks like we're frequently starting and shutting down Ray in this test because `ray_start_client_server` isn't connecting to the Ray created by `ray_start_regular_shared`, and is instead starting a new Ray head process every time it launches.
Ray clien... | 30,161 | 0 | 12 | 157 | 6 | 133,953 | 6 | ray | 4 | python/ray/tests/test_client.py | Python | 19 | {
"docstring": "\n Test remote calls with large (multiple chunk) arguments\n ",
"language": "en",
"n_whitespaces": 15,
"n_words": 8,
"vocab_size": 8
} | https://github.com/ray-project/ray.git | |
2 | legend | def legend(self, *args, **kwargs):
handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
[self],
*args,
**kwargs)
if len(extra_args):
raise TypeError('legend only accepts two non-keyword arguments')
self.legend_ = m... | 7c67cadfd903a26b3d56dd2c95faf2365367fd1a | 10 | _axes.py | 116 | Highlight information about avoiding labels in legend | 23,529 | 0 | 131 | 75 | 26 | 109,334 | 33 | matplotlib | 15 | lib/matplotlib/axes/_axes.py | Python | 10 | {
"docstring": "\n Place a legend on the Axes.\n\n Call signatures::\n\n legend()\n legend(handles, labels)\n legend(handles=handles)\n legend(labels)\n\n The call signatures correspond to the following different ways to use\n this method:\n\n ... | https://github.com/matplotlib/matplotlib.git | |
8 | _disallow_batch_hooks_in_ps_strategy | def _disallow_batch_hooks_in_ps_strategy(self):
# pylint: disable=protected-access
strategy = tf.distribute.get_strategy()
if strategy._should_use_with_coordinator:
unsupported_callbacks = []
for cb in self.callbacks:
# These Callbacks can accept ... | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | @keras_export("keras.callbacks.Callback") | 14 | callbacks.py | 156 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,365 | 1 | 369 | 80 | 51 | 269,969 | 60 | keras | 17 | keras/callbacks.py | Python | 19 | {
"docstring": "Error out if batch-level callbacks are passed with PSStrategy.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/keras-team/keras.git |
15 | compatible_abstract_dep | def compatible_abstract_dep(self, other):
from .requirements import Requirement
if len(self.candidates) == 1 and next(iter(self.candidates)).editable:
return self
elif len(other.candidates) == 1 and next(iter(other.candidates)).editable:
return other
ne... | 8a4d2eb130fd173466310f59df607ea59bfc44a5 | 15 | dependencies.py | 444 | Vendor in latest requirements lib and pip-shims in order to drop packaging and resolve differences in sourcing it. | 3,973 | 0 | 473 | 285 | 76 | 21,648 | 117 | pipenv | 44 | pipenv/vendor/requirementslib/models/dependencies.py | Python | 40 | {
"docstring": "Merge this abstract dependency with another one.\n\n Return the result of the merge as a new abstract dependency.\n\n :param other: An abstract dependency to merge with\n :type other: :class:`~requirementslib.models.dependency.AbstractDependency`\n :return: A new, combined ... | https://github.com/pypa/pipenv.git | |
2 | shade_normals | def shade_normals(self, normals, fraction=1.):
intensity = normals.dot(self.direction)
# Apply contrast stretch
imin, imax = intensity.min(), intensity.max()
intensity *= fraction
# Rescale to 0-1, keeping range before contrast stretch
# If constant slope, kee... | f16da868d016363c4cd734b2abd6535230b094df | 10 | colors.py | 124 | [Doc] Fix ndarray-links for arguments | 24,318 | 0 | 248 | 78 | 79 | 110,839 | 105 | matplotlib | 13 | lib/matplotlib/colors.py | Python | 9 | {
"docstring": "\n Calculate the illumination intensity for the normal vectors of a\n surface using the defined azimuth and elevation for the light source.\n\n Imagine an artificial sun placed at infinity in some azimuth and\n elevation position illuminating our surface. The parts of the s... | https://github.com/matplotlib/matplotlib.git | |
4 | get_loading_pipeline | def get_loading_pipeline(pipeline):
loading_pipeline_cfg = []
for cfg in pipeline:
obj_cls = PIPELINES.get(cfg['type'])
# TODO:use more elegant way to distinguish loading modules
if obj_cls is not None and obj_cls in (LoadImageFromFile,
... | 301d4a2d4cfe1cdb62608e2892924be3e67e3098 | @HOOKS.register_module() | 12 | utils.py | 113 | [Feature] Support visualization for Panoptic Segmentation (#7041)
* First commit of v2
* split the functions
* Support to show panoptic result
* temp
* Support to show gt
* support show gt
* fix lint
* Support to browse datasets
* Fix unit tests
* Fix findContours
* fix comments
* Fix ... | 70,172 | 1 | 210 | 62 | 50 | 243,970 | 58 | mmdetection | 14 | mmdet/datasets/utils.py | Python | 12 | {
"docstring": "Only keep loading image and annotations related configuration.\n\n Args:\n pipeline (list[dict]): Data pipeline configs.\n\n Returns:\n list[dict]: The new pipeline list with only keep\n loading image and annotations related configuration.\n\n Examples:\n >>> p... | https://github.com/open-mmlab/mmdetection.git |
1 | test_cancel_during_response_hook | def test_cancel_during_response_hook(tctx):
playbook, cff = start_h2_client(tctx)
flow = Placeholder(HTTPFlow)
server = Placeholder(Server)
assert (
playbook
>> DataReceived(
tctx.client,
cff.build_headers_frame(
example_request_headers, flag... | b3587b52b25077f68116b9852b041d33e7fc6601 | 30 | test_http2.py | 266 | make it black! | 73,878 | 0 | 267 | 175 | 43 | 251,888 | 64 | mitmproxy | 29 | test/mitmproxy/proxy/layers/http/test_http2.py | Python | 29 | {
"docstring": "\n Test that we properly handle the case of the following event sequence:\n - we receive a server response\n - we trigger the response hook\n - the client cancels the stream\n - the response hook completes\n\n Given that we have already triggered the response hook, we... | https://github.com/mitmproxy/mitmproxy.git | |
2 | __getitem__ | def __getitem__(self, name):
if name in MEDIA_TYPES:
return Media(**{str(name): getattr(self, "_" + name)})
raise KeyError('Unknown media type "%s"' % name)
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 16 | widgets.py | 69 | Refs #33476 -- Reformatted code with Black. | 51,333 | 0 | 52 | 40 | 20 | 206,035 | 20 | django | 8 | django/forms/widgets.py | Python | 4 | {
"docstring": "Return a Media object that only contains media of the given type.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | https://github.com/django/django.git | |
58 | payload | def payload(self, place=None, parameter=None, value=None, newValue=None, where=None):
if conf.direct:
return self.payloadDirect(newValue)
retVal = ""
if kb.forceWhere:
where = kb.forceWhere
elif where is None and isTechniqueAvailable(getTechnique()):
... | b1881129b6201ffd7d2ea01754ca2c76479776a3 | 22 | agent.py | 1,733 | Bug for JSON-like bug (#5013) | 27,346 | 0 | 1,802 | 1,255 | 188 | 123,418 | 474 | sqlmap | 83 | lib/core/agent.py | Python | 118 | {
"docstring": "\n This method replaces the affected parameter with the SQL\n injection statement to request\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 13,
"vocab_size": 12
} | https://github.com/sqlmapproject/sqlmap.git | |
2 | is_alive | def is_alive(self) -> bool:
return any(thread.is_alive() for thread in self._threads)
| 326110f09d45dbdce2e490fa1ae4b1208e5efe2c | 9 | multithreading.py | 39 | bugfix - timelapse image loader
multithreading.py - typing + docs | 20,745 | 0 | 24 | 23 | 10 | 101,327 | 10 | faceswap | 6 | lib/multithreading.py | Python | 9 | {
"docstring": " Check if any threads are still alive\n\n Returns\n -------\n bool\n ``True`` if any threads are alive. ``False`` if no threads are alive\n ",
"language": "en",
"n_whitespaces": 62,
"n_words": 22,
"vocab_size": 14
} | https://github.com/deepfakes/faceswap.git | |
2 | expand_block | def expand_block(self, block):
w = list(struct.unpack(">16L", block)) + [0] * 64
for i in range(16, 80):
w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1)
return w
| f0af0c43340763724f139fa68aa1e5a9ffe458b4 | 16 | sha1.py | 122 | refactor: clean code
Signed-off-by: slowy07 <slowy.arfy@gmail.com> | 4,456 | 0 | 75 | 80 | 27 | 22,785 | 36 | Python | 10 | sha1.py | Python | 5 | {
"docstring": "\n Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a\n list of 80 integers pafter some bit operations\n ",
"language": "en",
"n_whitespaces": 46,
"n_words": 24,
"vocab_size": 18
} | https://github.com/geekcomputers/Python.git | |
1 | test_redact_relation_annotation | def test_redact_relation_annotation(self) -> None:
channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
self.assertEqual(200, channel.code, channel.json_body)
to_redact_event_id = channel.json_body["event_id"]
channel = self._send_relation(
Rel... | f63bedef07360216a8de71dc38f00f1aea503903 | 13 | test_relations.py | 435 | Invalidate caches when an event with a relation is redacted. (#12121)
The caches for the target of the relation must be cleared
so that the bundled aggregations are re-calculated after
the redaction is processed. | 71,672 | 0 | 352 | 250 | 59 | 247,440 | 115 | synapse | 21 | tests/rest/client/test_relations.py | Python | 33 | {
"docstring": "\n Test that annotations of an event are properly handled after the\n annotation is redacted.\n\n The redacted relation should not be included in bundled aggregations or\n the response to relations.\n ",
"language": "en",
"n_whitespaces": 65,
"n_words": 29,
"... | https://github.com/matrix-org/synapse.git | |
1 | test_collision | def test_collision():
content =
config = parser.parse(content)
assert config["example"]["nested"]["path"] == "first one"
assert config["example"]["nested.path"] == "uh oh"
assert config["reference_to_nested_path"] == "uh oh"
assert config["example"]["nested"]["more_nested"]["value"] == "found i... | aa9251872136235be81f5d5f6d97eec00928a992 | 11 | test_yaml_parser.py | 134 | Low-code connectors: configurable source from yaml (#13038)
* checkout from alex/cac
* checkout from alex/cac
* checkout from alex/cac
* checkout from alex/cac
* Add missing tests
* Add missing files
* Add missing tests
* add missing file
* missing file
* missing file
* sengrid low code c... | 795 | 0 | 53 | 68 | 19 | 5,647 | 32 | airbyte | 5 | airbyte-cdk/python/unit_tests/sources/declarative/parsers/test_yaml_parser.py | Python | 19 | {
"docstring": "\nexample:\n nested:\n path: \"first one\"\n more_nested:\n value: \"found it!\"\n nested.path: \"uh oh\"\nreference_to_nested_path:\n ref: \"*ref(example.nested.path)\"\nreference_to_nested_nested_value:\n ref: \"*ref(example.nested.more_nested.value)\"\n ",
"language": "en",
... | https://github.com/airbytehq/airbyte.git | |
1 | do_get | def do_get(self, arg):
ray.worker.global_worker.debugger_get_breakpoint = self._breakpoint_uuid
self.__restore()
self.handle.connection.close()
return Pdb.do_continue(self, arg)
| 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | 9 | rpdb.py | 69 | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 29,957 | 0 | 46 | 42 | 11 | 133,204 | 11 | ray | 14 | python/ray/util/rpdb.py | Python | 5 | {
"docstring": "get\n Skip to where the current task returns to.\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 9,
"vocab_size": 9
} | https://github.com/ray-project/ray.git | |
2 | trace | def trace(log_dir, create_perfetto_link=False, create_perfetto_trace=False):
start_trace(log_dir, create_perfetto_link, create_perfetto_trace)
try:
yield
finally:
stop_trace()
| 260f1d8b843483df46cf397ae5a1afc0abc9c64f | 10 | profiler.py | 51 | Add option to generate perfetto trace without generating link | 27,075 | 0 | 21 | 30 | 11 | 121,807 | 11 | jax | 6 | jax/_src/profiler.py | Python | 6 | {
"docstring": "Context manager to take a profiler trace.\n\n The trace will capture CPU, GPU, and/or TPU activity, including Python\n functions and JAX on-device operations.\n\n The resulting trace can be viewed with TensorBoard. Note that TensorBoard\n doesn't need to be running when collecting the trace.\n\n ... | https://github.com/google/jax.git | |
1 | get_weights_path | def get_weights_path(url):
url = parse_url(url)
path, _ = get_path(url, WEIGHTS_HOME)
return path
| b29aa30f650b06bea79698adfb3392cc96feb583 | 8 | download.py | 41 | given inference model path, download model automatically (#6403)
* given inference model path, download model automatically
* encapsulate auto download model as a function
* given note that default model dir is download link
* change attr model download path to https://bj.bcebos.com/v1/paddledet/models/pipeli... | 53,022 | 0 | 24 | 24 | 11 | 211,057 | 12 | PaddleDetection | 7 | deploy/pipeline/download.py | Python | 4 | {
"docstring": "Get weights path from WEIGHTS_HOME, if not exists,\n download it from url.\n ",
"language": "en",
"n_whitespaces": 18,
"n_words": 12,
"vocab_size": 11
} | https://github.com/PaddlePaddle/PaddleDetection.git | |
11 | find_batch_size | def find_batch_size(tensors):
if isinstance(tensors, (list, tuple)):
for t in tensors:
result = find_batch_size(t)
if result is not None:
return result
elif isinstance(tensors, Mapping):
for key, value in tensors.items():
result = find_bat... | 18df440709f1b19d1c5617c0d987c5ff8fd0915d | 13 | trainer_pt_utils.py | 192 | Replace dict/BatchEncoding instance checks by Mapping (#17014)
* Replace dict/BatchEncoding instance checks by Mapping
* Typo | 6,828 | 0 | 177 | 126 | 31 | 37,529 | 60 | transformers | 17 | src/transformers/trainer_pt_utils.py | Python | 15 | {
"docstring": "\n Find the first dimension of a tensor in a nested list/tuple/dict of tensors.\n ",
"language": "en",
"n_whitespaces": 20,
"n_words": 13,
"vocab_size": 11
} | https://github.com/huggingface/transformers.git | |
1 | test_spam_checker_shadow_ban | def test_spam_checker_shadow_ban(self) -> None:
user_id = self.get_success(self.handler.register_user(localpart="user"))
# Get an access token.
token = "testtok"
self.get_success(
self.store.add_access_token_to_user(
user_id=user_id, token=token, dev... | 652d1669c5a103b1c20478770c4aaf18849c09a3 | 12 | test_register.py | 197 | Add missing type hints to tests.handlers. (#14680)
And do not allow untyped defs in tests.handlers. | 73,413 | 0 | 175 | 118 | 39 | 250,390 | 47 | synapse | 26 | tests/handlers/test_register.py | Python | 15 | {
"docstring": "A spam checker can choose to shadow-ban a user, which allows registration to succeed.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | https://github.com/matrix-org/synapse.git | |
1 | test_global_selection_header_updates_environment_with_browser_navigation_buttons | def test_global_selection_header_updates_environment_with_browser_navigation_buttons(self):
with self.feature("organizations:global-views"):
self.create_issues()
self.issues_list.visit_issue_list(self.org.slug)
self.issues_list.wait_until_loaded()
... | 5c0c82919f14654cc18405384654fa792d12e31a | 12 | test_organization_global_selection_header.py | 527 | ref(page-filters): Remove mentions of global header in acceptance tests (#35075) | 18,685 | 0 | 504 | 295 | 28 | 90,724 | 91 | sentry | 17 | tests/acceptance/test_organization_global_selection_header.py | Python | 50 | {
"docstring": "\n Global Selection Header should:\n 1) load project from URL if it exists\n 2) clear the current environment if the user clicks clear\n 3) reload the environment from URL if it exists on browser navigation\n \n set up workflow:\n 1) environment... | https://github.com/getsentry/sentry.git | |
2 | plot_colored_circles | def plot_colored_circles(ax, prng, nb_samples=15):
for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'], range(nb_samples)):
ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
radius=1.0, color=sty_dict['color']))
ax.grid(visible=True)
# Add title for enabl... | fd5cf5c88123653b656a8f908aa611e5a20dc923 | 14 | style_sheets_reference.py | 198 | [DOC]: adding a grid to the style sheet reference. (#24020)
* add divider and annotation.
Co-authored-by: Kinza Raza <kanza.imran@careem.com>
* fix flake8
* change from annotate to title
* Update examples/style_sheets/style_sheets_reference.py
Co-authored-by: Jody Klymak <jklymak@gmail.com>
* Update ... | 23,704 | 0 | 104 | 123 | 35 | 109,681 | 38 | matplotlib | 26 | examples/style_sheets/style_sheets_reference.py | Python | 10 | {
"docstring": "\n Plot circle patches.\n\n NB: draws a fixed amount of samples, rather than using the length of\n the color cycle, because different styles may have different numbers\n of colors.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 28,
"vocab_size": 24
} | https://github.com/matplotlib/matplotlib.git | |
2 | first_time_user | def first_time_user() -> bool:
if USER_ENV_FILE.stat().st_size == 0:
set_key("OPENBB_PREVIOUS_USE", "True", True)
return True
return False
| 19660ff3ee39458bd78e729b97fca4a4e552c160 | 10 | keys_model.py | 54 | Updated check for new user (#3302)
* Updated check for new user
* Update docstring
* Fixed import error
Co-authored-by: James Maslek <jmaslek11@gmail.com> | 85,800 | 0 | 38 | 30 | 14 | 286,413 | 15 | OpenBBTerminal | 6 | openbb_terminal/keys_model.py | Python | 13 | {
"docstring": "Whether a user is a first time user. A first time user is someone with an empty .env file.\n If this is true, it also adds an env variable to make sure this does not run again.\n\n Returns\n ----------\n bool\n Whether or not the user is a first time user\n ",
"language": "en",... | https://github.com/OpenBB-finance/OpenBBTerminal.git | |
1 | test_cardinality_limiter | def test_cardinality_limiter(caplog, settings):
settings.SENTRY_METRICS_INDEXER_DEBUG_LOG_SAMPLE_RATE = 1.0
outer_message = _construct_outer_message(
[
(counter_payload, []),
(distribution_payload, []),
(set_payload, []),
]
)
batch = IndexerBatc... | c48fda09e252018a4d2b831bb84e1c68a739c085 | 16 | test_batch.py | 567 | feat(metrics): Add cardinality limiter to indexer [sns-1651] (#38428)
Reopen of https://github.com/getsentry/sentry/pull/38302 to avoid
notification spam
See #38257 and
https://www.notion.so/sentry/Metrics-Dimensionality-Limiting-df010a6a6d4e467ca3c5c19230db862b#4966fb9c07fc4394b720ad161c99a096.
This is just th... | 18,023 | 0 | 1,008 | 344 | 115 | 85,650 | 177 | sentry | 30 | tests/sentry/sentry_metrics/test_batch.py | Python | 73 | {
"docstring": "\n Test functionality of the indexer batch related to cardinality-limiting. More concretely, assert that `IndexerBatch.filter_messages`:\n\n 1. removes the messages from the outgoing batch\n 2. prevents strings from filtered messages from being extracted & indexed\n 3. does not crash when ... | https://github.com/getsentry/sentry.git | |
1 | linear | def linear(x):
return x
@keras_export("keras.activations.serialize")
@tf.__internal__.dispatch.add_dispatch_support | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | @keras_export("keras.activations.serialize")
@tf.__internal__.dispatch.add_dispatch_support | 7 | activations.py | 39 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,014 | 1 | 10 | 8 | 6 | 269,300 | 6 | keras | 7 | keras/activations.py | Python | 2 | {
"docstring": "Linear activation function (pass-through).\n\n For example:\n\n >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)\n >>> b = tf.keras.activations.linear(a)\n >>> b.numpy()\n array([-3., -1., 0., 1., 3.], dtype=float32)\n\n Args:\n x: Input tensor.\n\n Retu... | https://github.com/keras-team/keras.git |
12 | build_args | def build_args(self, category, command=None, generate=False):
logger.debug("Build cli arguments: (category: %s, command: %s, generate: %s)",
category, command, generate)
command = self.command if not command else command
script = f"{category}.py"
pathexecscr... | dab823a3eb7a5257cb1e0818ee10ed234d3de97f | 17 | wrapper.py | 309 | Typing - lib.gui.display_command | 21,327 | 0 | 328 | 183 | 70 | 101,950 | 108 | faceswap | 26 | lib/gui/wrapper.py | Python | 21 | {
"docstring": " Build the faceswap command and arguments list.\n\n If training, pass the model folder and name to the training\n :class:`lib.gui.analysis.Session` for the GUI.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 22,
"vocab_size": 18
} | https://github.com/deepfakes/faceswap.git | |
4 | length | def length(self):
if self._length_cache is None:
if self.axis == 0:
self._length_cache = sum(
o.length() for o in self.list_of_partitions_to_combine
)
else:
self._length_cache = self.list_of_partitions_to_combin... | 8d1004fdbdaa05700613c8e6287641a732acf606 | 15 | virtual_partition.py | 100 | FIX-#3675: Expand virtual partitioning utility (#3886)
Co-authored-by: mvashishtha <mahesh@ponder.io>
Co-authored-by: jeffreykennethli <jkli@ponder.io>
Co-authored-by: Anatoly Myachev <anatoly.myachev@intel.com>
Co-authored-by: Vasily Litvinov <vasilij.n.litvinov@intel.com>
Co-authored-by: Alexey Prutskov <alexey.... | 35,286 | 0 | 138 | 58 | 22 | 153,185 | 28 | modin | 8 | modin/core/execution/ray/implementations/pandas_on_ray/partitioning/virtual_partition.py | Python | 9 | {
"docstring": "\n Get the length of this partition.\n\n Returns\n -------\n int\n The length of the partition.\n ",
"language": "en",
"n_whitespaces": 61,
"n_words": 14,
"vocab_size": 10
} | https://github.com/modin-project/modin.git | |
1 | test_pipenv_respects_package_index_restrictions | def test_pipenv_respects_package_index_restrictions(PipenvInstance):
with PipenvInstance() as p:
with open(p.pipfile_path, 'w') as f:
contents = .strip().format(url=p.pypi, requirement='{version="*", index="local"}')
f.write(contents)
c = p.pipenv('lock')
assert c.re... | 0788b0122e75ca5244ff4185336dc7958543f165 | 15 | test_lock.py | 263 | Refactor test into a version that also check quiet mode, move to correct test file.
Add test cases for pip freeze has expected output
Add test for the package index restrictions. | 2,991 | 0 | 239 | 140 | 54 | 19,475 | 75 | pipenv | 18 | tests/integration/test_lock.py | Python | 29 | {
"docstring": "\n[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[[source]]\nurl = \"{url}/simple\"\nverify_ssl = true\nname = \"local\"\n\n[packages]\nrequests = {requirement}\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 24,
"vocab_size": 13
} | https://github.com/pypa/pipenv.git | |
2 | transpose | def transpose(self) -> Tuple[int, int]:
if self.transpose_method is not None:
# Safety: `transpose` takes an int rather than e.g. an IntEnum.
# self.transpose_method is set above to be a value in
# EXIF_TRANSPOSE_MAPPINGS, and that only contains correct values.
... | 5949ab86f8db0ef3dac2063e42210030f17786fb | 13 | thumbnailer.py | 125 | Fix potential thumbnail memory leaks. (#12932) | 72,299 | 0 | 191 | 74 | 53 | 248,471 | 66 | synapse | 10 | synapse/rest/media/v1/thumbnailer.py | Python | 13 | {
"docstring": "Transpose the image using its EXIF Orientation tag\n\n Returns:\n A tuple containing the new image size in pixels as (width, height).\n ",
"language": "en",
"n_whitespaces": 46,
"n_words": 21,
"vocab_size": 19
} | https://github.com/matrix-org/synapse.git | |
1 | test_displayname_is_set_avatar_is_none | def test_displayname_is_set_avatar_is_none(self) -> None:
channel = self.make_request(
"POST",
self.url,
access_token=self.admin_user_tok,
content={
"user_id": self.other_user,
"content": {"msgtype": "m.text", "body": "test... | 37f329c9adf6ed02df15661850f999edd9e5fd93 | 14 | test_server_notice.py | 129 | Fix that sending server notices fail if avatar is `None` (#13566)
Indroduced in #11846. | 72,899 | 0 | 159 | 78 | 32 | 249,408 | 32 | synapse | 14 | tests/rest/admin/test_server_notice.py | Python | 17 | {
"docstring": "\n Tests that sending a server notices is successfully,\n if a display_name is set, avatar_url is `None` and\n \"check avatar size and mime type\" is set.\n ",
"language": "en",
"n_whitespaces": 54,
"n_words": 25,
"vocab_size": 20
} | https://github.com/matrix-org/synapse.git | |
3 | prepare_stocks_reservations_map | def prepare_stocks_reservations_map(self, variant_ids):
stocks_reservations = defaultdict(int)
if is_reservation_enabled(self.context.site.settings): # type: ignore
# Can't do second annotation on same queryset because it made
# available_quantity annotated value incorr... | fd5a3b24bcb941180bf2c27e6d0c34022d9e3ecd | 18 | dataloaders.py | 124 | Fix quantity available for stocks with cc warehouses (#10343)
* Refactor AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader and fix quantity available calculation
* Add more tests for variant quantity available | 5,169 | 0 | 226 | 73 | 49 | 28,430 | 56 | saleor | 21 | saleor/graphql/warehouse/dataloaders.py | Python | 12 | {
"docstring": "Prepare stock id to quantity reserved map for provided variant ids.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/saleor/saleor.git | |
3 | get_current_student | def get_current_student():
email = frappe.session.user
if email in ("Administrator", "Guest"):
return None
try:
student_id = frappe.get_all("Student", {"student_email_id": email}, ["name"])[0].name
return frappe.get_doc("Student", student_id)
except (IndexError, frappe.DoesNotExistError):
return None
| 494bd9ef78313436f0424b918f200dab8fc7c20b | 15 | utils.py | 117 | style: format code with black | 14,069 | 0 | 18 | 68 | 22 | 65,955 | 27 | erpnext | 11 | erpnext/education/utils.py | Python | 9 | {
"docstring": "Returns current student from frappe.session.user\n\n\tReturns:\n\t object: Student Document\n\t",
"language": "en",
"n_whitespaces": 14,
"n_words": 9,
"vocab_size": 9
} | https://github.com/frappe/erpnext.git | |
6 | copyDataFiles | def copyDataFiles():
for included_datafile in getIncludedDataFiles():
# TODO: directories should be resolved to files.
if (
not isinstance(included_datafile, (IncludedDataFile))
or included_datafile.needsCopy()
):
if shallMakeModule():
... | c2e2b6fd58f535c3419f21a84c54ead13968ddd2 | 15 | IncludedDataFiles.py | 108 | Plugins: Cleanups to how data files are handled | 42,880 | 0 | 242 | 59 | 29 | 178,965 | 34 | Nuitka | 11 | nuitka/freezer/IncludedDataFiles.py | Python | 19 | {
"docstring": "Copy the data files needed for standalone distribution.\n\n Notes:\n This is for data files only, not DLLs or even extension modules,\n those must be registered as entry points, and would not go through\n necessary handling if provided like this.\n \\\nError, data files for ... | https://github.com/Nuitka/Nuitka.git | |
1 | test_commands_with_invalid_settings | def test_commands_with_invalid_settings(self):
args = ["startproject"]
out, err = self.run_django_admin(args, settings_file="bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "You must provide a project name", regex=True)
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 10 | tests.py | 75 | Refs #33476 -- Reformatted code with Black. | 51,944 | 0 | 54 | 43 | 18 | 207,377 | 19 | django | 10 | tests/admin_scripts/tests.py | Python | 5 | {
"docstring": "\n Commands that don't require settings succeed if the settings file\n doesn't exist.\n ",
"language": "en",
"n_whitespaces": 34,
"n_words": 12,
"vocab_size": 11
} | https://github.com/django/django.git | |
5 | do_block | def do_block(parser, token):
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0])
block_name = bits[1]
# Keep track of the... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 14 | loader_tags.py | 226 | Refs #33476 -- Reformatted code with Black. | 51,468 | 0 | 237 | 134 | 93 | 206,286 | 119 | django | 19 | django/template/loader_tags.py | Python | 19 | {
"docstring": "\n Define a block that can be overridden by child templates.\n ",
"language": "en",
"n_whitespaces": 17,
"n_words": 10,
"vocab_size": 10
} | https://github.com/django/django.git | |
1 | test_wrapped_bleak_scanner | async def test_wrapped_bleak_scanner(hass, enable_bluetooth):
scanner = HaBleakScannerWrapper()
switchbot_device = BLEDevice("44:44:33:11:23:45", "wohand")
switchbot_adv = AdvertisementData(
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
)
inject_advertisement(has... | 1b144c0e4dd683e3b47668a89da5eb6da4ae5e08 | 12 | test_models.py | 118 | Update to bleak 0.18.0 (#79008) | 86,942 | 0 | 62 | 70 | 26 | 287,754 | 31 | core | 15 | tests/components/bluetooth/test_models.py | Python | 9 | {
"docstring": "Test wrapped bleak scanner dispatches calls as expected.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | https://github.com/home-assistant/core.git | |
2 | get_best_result | def get_best_result(self) -> Optional[Tuple[Union[int, str], Module, Dict[str, Dict[str, Tensor]], Optional[float], List[Dict]]]:
if self._best_task_id is not None:
compact_model = torch.load(Path(self._log_dir_root, 'best_result', 'model.pth'))
compact_model_masks = torch.load(... | cbac2c5c0f7606aca8ccf08fbd418ffe3adfe427 | 15 | base.py | 199 | [Compression] fix typehints (#4800) | 24,742 | 0 | 123 | 128 | 35 | 112,742 | 43 | nni | 24 | nni/algorithms/compression/v2/pytorch/pruning/tools/base.py | Python | 15 | {
"docstring": "\n Returns\n -------\n Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]]\n If self._best_task_id is not None,\n return best task id, best compact model, masks on the compact model, score, config list used in this task.\n ",
... | https://github.com/microsoft/nni.git | |
11 | _parse_directive | def _parse_directive(self, directive):
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
'global-include',
'global-exclude',
... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 14 | manifest.py | 359 | upd; format | 12,847 | 0 | 670 | 211 | 72 | 62,040 | 132 | transferlearning | 14 | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/manifest.py | Python | 31 | {
"docstring": "\n Validate a directive.\n :param directive: The directive to validate.\n :return: A tuple of action, patterns, thedir, dir_patterns\n ",
"language": "en",
"n_whitespaces": 46,
"n_words": 17,
"vocab_size": 17
} | https://github.com/jindongwang/transferlearning.git | |
3 | parse | def parse(self, fname, num_splits, start, end, header, **kwargs):
import pyarrow as pa
import pyarrow.csv as csv
with open(fname, "rb") as bio:
# The header line for the CSV file
first_line = bio.readline()
bio.seek(start)
to_read = heade... | 14015de80f2387703ca7be52ff917c99ef05fc68 | 14 | parsers.py | 264 | REFACTOR-#5359: Fix code scanning alert - File is not always closed (#5362)
Signed-off-by: Myachev <anatoly.myachev@intel.com> | 36,340 | 0 | 300 | 171 | 62 | 155,337 | 83 | modin | 42 | modin/experimental/core/storage_formats/pyarrow/parsers.py | Python | 22 | {
"docstring": "\n Parse CSV file into PyArrow tables.\n\n Parameters\n ----------\n fname : str\n Name of the CSV file to parse.\n num_splits : int\n Number of partitions to split the resulted PyArrow table into.\n start : int\n Position in t... | https://github.com/modin-project/modin.git | |
15 | test_request_streaming | def test_request_streaming(tctx, why, transfer_encoding, response):
server = Placeholder(Server)
flow = Placeholder(HTTPFlow)
playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))
if why.startswith("body_size"):
tctx.options.stream_large_bodies = why.replace("body_size=", "")
| 56eea20f6389b751d38079fb09b29237a0d2b262 | 11 | test_http.py | 102 | tutils: add BytesMatching placeholder | 73,598 | 0 | 43 | 683 | 18 | 251,118 | 21 | mitmproxy | 20 | test/mitmproxy/proxy/layers/http/test_http.py | Python | 104 | {
"docstring": "\n Test HTTP request streaming\n\n This is a bit more contrived as we may receive server data while we are still sending the request.\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 23,
"vocab_size": 22
} | https://github.com/mitmproxy/mitmproxy.git | |
4 | get_data | def get_data(filters):
accounts = frappe.db.sql(
,
filters.company,
as_dict=True,
)
company_currency = filters.presentation_currency or erpnext.get_company_currency(filters.company)
if not accounts:
return None
accounts, accounts_by_name, parent_children_map = filter_accounts(accounts)
min_lft, max_rg... | 494bd9ef78313436f0424b918f200dab8fc7c20b | 12 | trial_balance.py | 279 | style: format code with black | 13,872 | 0 | 55 | 187 | 67 | 65,377 | 93 | erpnext | 35 | erpnext/accounts/report/trial_balance/trial_balance.py | Python | 40 | {
"docstring": "select name, account_number, parent_account, account_name, root_type, report_type, lft, rgt\n\n\t\tfrom `tabAccount` where company=%s order by lftselect min(lft), max(rgt) from `tabAccount`\n\t\twhere company=%s",
"language": "en",
"n_whitespaces": 19,
"n_words": 22,
"vocab_size": 18
} | https://github.com/frappe/erpnext.git | |
3 | queryset_chunks | def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE):
i = 0
while True:
items = list(qs[i * chunk_size :][:chunk_size])
if not items:
break
yield items
i += 1
| d10f15e55806c6944827d801cd9c2d53f5da4186 | 14 | update_index.py | 73 | Reformat with black | 16,427 | 0 | 104 | 44 | 21 | 75,606 | 24 | wagtail | 8 | wagtail/search/management/commands/update_index.py | Python | 8 | {
"docstring": "\n Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded\n will be a list, not a queryset. Iterating over the chunks is done in a\n transaction so that the order and count of items in the queryset\n remains stable.\n ",
"language": "en",
"n_whit... | https://github.com/wagtail/wagtail.git | |
3 | prepare_sql_script | def prepare_sql_script(self, sql):
return [
sqlparse.format(statement, strip_comments=True)
for statement in sqlparse.split(sql)
if statement
]
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 9 | operations.py | 50 | Refs #33476 -- Reformatted code with Black. | 50,934 | 0 | 68 | 32 | 13 | 204,857 | 14 | django | 8 | django/db/backends/base/operations.py | Python | 6 | {
"docstring": "\n Take an SQL script that may contain multiple lines and return a list\n of statements to feed to successive cursor.execute() calls.\n\n Since few databases are able to process raw SQL scripts in a single\n cursor.execute() call and PEP 249 doesn't talk about this use case... | https://github.com/django/django.git | |
6 | angle_mod | def angle_mod(x, zero_2_2pi=False, degree=False):
if isinstance(x, float):
is_float = True
else:
is_float = False
x = np.asarray(x).flatten()
if degree:
x = np.deg2rad(x)
if zero_2_2pi:
mod_angle = x % (2 * np.pi)
else:
mod_angle = (x + np.pi) % (2 ... | 32b545fe7c35b57f280cd9d570f62839886f2e4b | 14 | angle.py | 185 | Enhance dubins path docs (#664)
* Engance dubins path docs
* Update dubins_path.rst
* fix doc artifact link in CI
* wip
* wip
* wip
* Update dubins_path.rst
* wip
* wip
* wip
* wip
* wip | 2,936 | 0 | 141 | 114 | 30 | 19,322 | 55 | PythonRobotics | 15 | utils/angle.py | Python | 18 | {
"docstring": "\n Angle modulo operation\n Default angle modulo range is [-pi, pi)\n\n Parameters\n ----------\n x : float or array_like\n A angle or an array of angles. This array is flattened for\n the calculation. When an angle is provided, a float angle is returned.\n zero_2_2pi :... | https://github.com/AtsushiSakai/PythonRobotics.git | |
3 | __ror__ | def __ror__(self, other):
if isinstance(other, str_type):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
"Cannot combine element of type {} with ParserElement".format(
type(other).__na... | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | 14 | core.py | 86 | 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... | 3,433 | 0 | 140 | 52 | 26 | 20,578 | 30 | pipenv | 11 | pipenv/patched/notpip/_vendor/pyparsing/core.py | Python | 10 | {
"docstring": "\n Implementation of ``|`` operator when left operand is not a :class:`ParserElement`\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 11,
"vocab_size": 11
} | https://github.com/pypa/pipenv.git | |
2 | get_tables | def get_tables(self) -> Response:
response = None
log.info("%s: calling 'get_tables'", self.__class__.__name__)
try:
r = self._do("/get_tables")
r = self._convert_response(r.json())
response = Response(data_frame=r.get("data_frame", None),
... | e1d031d0375f0a3575fa2c4607fc0f5d5bc8044d | 14 | db_client.py | 258 | Move DB handlers in a separate service (#3063)
* Move DB handlers in a separate service
* add docker-compose initial | 25,846 | 0 | 354 | 156 | 46 | 116,838 | 60 | mindsdb | 26 | mindsdb/integrations/handlers_client/db_client.py | Python | 24 | {
"docstring": "List all tabels in the database without the system data.\n\n Returns:\n A list of all records in the database in case of success\n An error message and error code if case of fail\n ",
"language": "en",
"n_whitespaces": 69,
"n_words": 33,
"vocab_size": 23
} | https://github.com/mindsdb/mindsdb.git | |
1 | close_tilt_position | def close_tilt_position(self) -> PowerviewShadeMove:
return PowerviewShadeMove(self._shade.close_position_tilt, {})
| 3ab294e8efc00c9f3cda2993318bb582ba675f8c | 9 | cover.py | 34 | Powerview refactor prep for all shade types (#79862) | 87,917 | 0 | 21 | 20 | 7 | 288,765 | 7 | core | 5 | homeassistant/components/hunterdouglas_powerview/cover.py | Python | 3 | {
"docstring": "Return the close tilt position and required additional positions.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/home-assistant/core.git | |
7 | append | def append(self, key, _item):
if not isinstance(_item, Item):
_item = item(_item)
self._value.append(key, _item)
if isinstance(key, Key):
key = next(iter(key)).key
_item = self._value[key]
if key is not None:
dict.__setitem__(se... | 8faa74cdc9da20cfdcc69f5ec29b91112c95b4c9 | 15 | items.py | 262 | Update tomlkit==0.9.2
Used:
python -m invoke vendoring.update --package=tomlkit | 4,037 | 0 | 257 | 166 | 39 | 21,764 | 69 | pipenv | 21 | pipenv/vendor/tomlkit/items.py | Python | 20 | {
"docstring": "\n Appends a (key, item) to the table.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | https://github.com/pypa/pipenv.git | |
1 | get_preference | def get_preference(self, *args, **kwargs):
# type: (t.Any, t.Any) -> t.Union[float, int]
raise NotImplementedError
| 143e7fb45e7b916fa973613000e97ee889f5666c | 6 | providers.py | 25 | ansible-galaxy - support resolvelib versions >= 0.5.3, < 0.9.0 (#77649)
* ansible-galaxy - support resolvelib versions >= 0.5.3, <= 0.8.1
Test incompatibilities are removed for resolvelib >= 0.6.0
Test against the latest 0.8.x version and fix requirements
* Fix tests - use a venv for testing the range of reso... | 78,911 | 0 | 34 | 14 | 13 | 267,451 | 13 | ansible | 5 | lib/ansible/galaxy/dependency_resolution/providers.py | Python | 2 | {
"docstring": "Return sort key function return value for given requirement.\n\n This result should be based on preference that is defined as\n \"I think this requirement should be resolved first\".\n The lower the return value is, the more preferred this\n group of arguments is.\n\n ... | https://github.com/ansible/ansible.git | |
30 | plot_wireframe | def plot_wireframe(self, X, Y, Z, **kwargs):
had_data = self.has_data()
if Z.ndim != 2:
raise ValueError("Argument Z must be 2-dimensional.")
# FIXME: Support masked arrays
X, Y, Z = np.broadcast_arrays(X, Y, Z)
rows, cols = Z.shape
has_stride = 'rs... | 6ef6b37fc2113c041f7d2643d70b553ec335d597 | 19 | axes3d.py | 846 | Remove *args deprecations | 22,518 | 0 | 1,017 | 539 | 193 | 106,941 | 393 | matplotlib | 52 | lib/mpl_toolkits/mplot3d/axes3d.py | Python | 54 | {
"docstring": "\n Plot a 3D wireframe.\n\n .. note::\n\n The *rcount* and *ccount* kwargs, which both default to 50,\n determine the maximum number of samples used in each direction. If\n the input data is larger, it will be downsampled (by slicing) to\n these n... | https://github.com/matplotlib/matplotlib.git | |
1 | test_source_decode_2 | def test_source_decode_2():
import_str, op_str, op_obj = source_decode("sklearn.linear_model.LogisticReg")
from sklearn.linear_model import LogisticRegression
assert import_str == "sklearn.linear_model"
assert op_str == "LogisticReg"
assert op_obj is None
| 388616b6247ca4ea8de4e2f340d6206aee523541 | 9 | tpot_tests.py | 60 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | 43,489 | 0 | 41 | 33 | 19 | 181,702 | 23 | tpot | 8 | tests/tpot_tests.py | Python | 6 | {
"docstring": "Assert that the source_decode return None when sourcecode is not available.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/EpistasisLab/tpot.git | |
1 | save | def save(self, loc, **kwargs) -> Plot:
# TODO expose important keyword arguments in our signature?
with theme_context(self._theme_with_defaults()):
self._plot().save(loc, **kwargs)
return self
| 762db897b52d16ab2f164d5103df4cc26c1d0503 | 11 | plot.py | 66 | Add rudimentary themeing support (#2929)
* WIP Plot.theme
* Add default values for theme to match set_theme()
* Depend on matplotib style defaults and update rcParams more selectively
* Fix lines test
* Improve test coverage | 7,483 | 0 | 60 | 38 | 20 | 42,087 | 21 | seaborn | 8 | seaborn/_core/plot.py | Python | 16 | {
"docstring": "\n Compile the plot and write it to a buffer or file on disk.\n\n Parameters\n ----------\n loc : str, path, or buffer\n Location on disk to save the figure, or a buffer to write into.\n kwargs\n Other keyword arguments are passed through to\n ... | https://github.com/mwaskom/seaborn.git | |
1 | test_update_single_object_with_values | def test_update_single_object_with_values(self):
site2 = Site.objects.get(name='Site 2')
original_cfvs = {**site2.custom_field_data}
data = {
'custom_fields': {
'text_field': 'ABCD',
'number_field': 1234,
},
}
url =... | fa1e28e860c4bdb3e585a968bd248a2ac666e1f6 | 12 | test_customfields.py | 623 | Initial work on #7006 | 77,617 | 0 | 333 | 361 | 59 | 264,131 | 78 | netbox | 26 | netbox/extras/tests/test_customfields.py | Python | 31 | {
"docstring": "\n Update an object with existing custom field values. Ensure that only the updated custom field values are\n modified.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 16
} | https://github.com/netbox-community/netbox.git | |
2 | __virtual__ | def __virtual__():
if salt.utils.napalm.virtual(__opts__, __virtualname__, __file__):
return __virtualname__
else:
err_msg = "NAPALM is not installed."
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
| 4e3632254fb73210ce3e1954ec507473433018b8 | 11 | napalm_beacon.py | 71 | Align enhanced logging accross beacons | 53,868 | 0 | 63 | 42 | 23 | 215,170 | 26 | salt | 11 | salt/beacons/napalm_beacon.py | Python | 7 | {
"docstring": "\n This beacon can only work when running under a regular or a proxy minion, managed through napalm.\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 17,
"vocab_size": 16
} | https://github.com/saltstack/salt.git | |
5 | get_preprocess_function | def get_preprocess_function(self, field, value, export_format):
# Try to find a field specific function and return it
format_dict = self.custom_field_preprocess.get(field, {})
if export_format in format_dict:
return format_dict[export_format]
# Otherwise check for ... | d10f15e55806c6944827d801cd9c2d53f5da4186 | 10 | mixins.py | 105 | Reformat with black | 15,891 | 0 | 153 | 67 | 40 | 72,424 | 60 | wagtail | 13 | wagtail/admin/views/mixins.py | Python | 8 | {
"docstring": "Returns the preprocessing function for a given field name, field value, and export format",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | https://github.com/wagtail/wagtail.git | |
3 | remove_experiment_folder | def remove_experiment_folder(experiment_path):
fs = fsspec.get_mapper(experiment_path).fs
checkpoint_files = fs.glob(experiment_path + "/*.pth")
if not checkpoint_files:
if fs.exists(experiment_path):
fs.rm(experiment_path, recursive=True)
print(" ! Run is removed from {... | 72d85e53c98b908345bbff70f7cfba2174e883ce | 14 | generic_utils.py | 120 | Update model file extension (#1422)
* Update model file ext to ```.pth```
* Update docs
* Rename more
* Find model files | 77,203 | 0 | 83 | 68 | 25 | 262,392 | 32 | TTS | 12 | TTS/utils/generic_utils.py | Python | 9 | {
"docstring": "Check folder if there is a checkpoint, otherwise remove the folder",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 10
} | https://github.com/coqui-ai/TTS.git | |
6 | full_info | def full_info(self):
retval = "\n============ System Information ============\n"
sys_info = {"os_platform": self._system["platform"],
"os_machine": self._system["machine"],
"os_release": self._system["release"],
"py_conda_version": sel... | 48c886b3dce3d3117ad16edaf35c8abd28dc51f5 | 16 | sysinfo.py | 519 | Allow decoding errors | 21,438 | 0 | 722 | 267 | 84 | 102,073 | 112 | faceswap | 30 | lib/sysinfo.py | Python | 36 | {
"docstring": " Obtain extensive system information stats, formatted into a human readable format.\n\n Returns\n -------\n str\n The system information for the currently running system, formatted for output to\n console or a log file.\n ",
"language": "en",
"n_wh... | https://github.com/deepfakes/faceswap.git | |
4 | _get_handles | def _get_handles(self):
if self._is_plaidml:
self._handles = self._plaid.devices
elif IS_MACOS:
self._handles = metal.get_handles()
else:
self._handles = [pynvml.nvmlDeviceGetHandleByIndex(i)
for i in range(self._device_co... | 444762114c1b1ad2e72c871e825373bd74880aba | 14 | gpu_stats.py | 123 | Initial somewhat working version | 19,776 | 0 | 121 | 73 | 21 | 100,266 | 25 | faceswap | 17 | lib/gpu_stats.py | Python | 9 | {
"docstring": " Obtain the internal handle identifiers for the system GPUs and allocate to\n :attr:`_handles`. ",
"language": "en",
"n_whitespaces": 21,
"n_words": 13,
"vocab_size": 12
} | https://github.com/deepfakes/faceswap.git | |
1 | test_boost_mode | async def test_boost_mode(hass, aioclient_mock, mock_deconz_websocket):
data = {
"sensors": {
"0": {
"config": {
"battery": 58,
"heatsetpoint": 2200,
"locked": False,
"mode": "heat",
... | 7a6897c7578dffd6b67f57747ebd81b67b153e01 | 15 | test_climate.py | 549 | Add deconz current hvac operation to thermostate based on "state" (#59989)
* deconz - add current hvac operation to thermostate based on "state"
* deconz - extend current hvac operation to thermostate based on "state" and "mode"
* Add tests for current hvac action
* Add boost mode as special case
* format ... | 106,894 | 0 | 811 | 297 | 112 | 308,133 | 151 | core | 27 | tests/components/deconz/test_climate.py | Python | 58 | {
"docstring": "Test that a climate device with boost mode and different state works.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | https://github.com/home-assistant/core.git | |
4 | keyPressEvent | def keyPressEvent(self, e):
if e.key() == Qt.Key.Key_Insert and e.modifiers() == Qt.KeyboardModifier.ShiftModifier:
try:
text = utils.get_clipboard(selection=True, fallback=True)
except utils.ClipboardError: # pragma: no cover
e.ignore()
... | 0877fb0d78635692e481c8bde224fac5ad0dd430 | 13 | prompt.py | 137 | Run scripts/dev/rewrite_enums.py | 117,615 | 0 | 154 | 81 | 27 | 321,260 | 28 | qutebrowser | 20 | qutebrowser/mainwindow/prompt.py | Python | 11 | {
"docstring": "Override keyPressEvent to paste primary selection on Shift + Ins.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/qutebrowser/qutebrowser.git | |
1 | test_get_pdu_returns_nothing_when_event_does_not_exist | def test_get_pdu_returns_nothing_when_event_does_not_exist(self):
remote_pdu = self.get_success(
self.hs.get_federation_client().get_pdu(
["yet.another.server"],
"event_should_not_exist",
RoomVersions.V9,
)
)
self.a... | 0f971ca68e808dd16f53f5594a6b33b7bddcc9a9 | 13 | test_federation_client.py | 71 | Update `get_pdu` to return the original, pristine `EventBase` (#13320)
Update `get_pdu` to return the untouched, pristine `EventBase` as it was originally seen over federation (no metadata added). Previously, we returned the same `event` reference that we stored in the cache which downstream code modified in place and... | 72,511 | 0 | 108 | 42 | 12 | 248,920 | 13 | synapse | 10 | tests/federation/test_federation_client.py | Python | 9 | {
"docstring": "No event should be returned when the event does not exist",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 10
} | https://github.com/matrix-org/synapse.git | |
1 | test_form | def test_form(self):
form = self.EventPageForm(
instance=self.event_page, for_user=self.commenting_user
)
self.assertIn("comments", form.formsets)
comments_formset = form.formsets["comments"]
self.assertEqual(len(comments_formset.forms), 1)
self.ass... | 5fe2554934e5f9d6f27cf2bd4333b8ebe24ae592 | 10 | test_edit_handlers.py | 182 | Refactor commenting forms to receive the user object on instantiation
Use the inherit_kwargs feature added to django-modelcluster in https://github.com/wagtail/django-modelcluster/pull/156 / https://github.com/wagtail/django-modelcluster/pull/157 to pass the for_user attribute from the root form to the comments formse... | 16,567 | 0 | 105 | 115 | 21 | 76,676 | 24 | wagtail | 15 | wagtail/admin/tests/test_edit_handlers.py | Python | 11 | {
"docstring": "\n Check that the form has the comments/replies formsets, and that the\n user has been set on each CommentForm/CommentReplyForm instance\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 19,
"vocab_size": 15
} | https://github.com/wagtail/wagtail.git | |
20 | get_pydot_graph | def get_pydot_graph(caffe_net, rankdir, label_edges=True, phase=None):
pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net',
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
... | cc4d0564756ca067516f71718a3d135996525909 | 16 | draw.py | 667 | Balanced joint maximum mean discrepancy for deep transfer learning | 12,040 | 0 | 946 | 406 | 121 | 60,247 | 208 | transferlearning | 43 | code/deep/BJMMD/caffe/python/caffe/draw.py | Python | 54 | {
"docstring": "Create a data structure which represents the `caffe_net`.\n\n Parameters\n ----------\n caffe_net : object\n rankdir : {'LR', 'TB', 'BT'}\n Direction of graph layout.\n label_edges : boolean, optional\n Label the edges (default is True).\n phase : {caffe_pb2.Phase.TRAIN... | https://github.com/jindongwang/transferlearning.git | |
10 | _lstsq | def _lstsq(a, b, rcond, *, numpy_resid=False):
# TODO: add lstsq to lax_linalg and implement this function via those wrappers.
# TODO: add custom jvp rule for more robust lstsq differentiation
a, b = _promote_dtypes_inexact(a, b)
if a.shape[0] != b.shape[0]:
raise ValueError("Leading dimensions of input arr... | bb2682db6df5b9388ce0b161e3f449624238718b | @_wraps(np.linalg.lstsq, lax_description=textwrap.dedent("""\
It has two important differences:
1. In `numpy.linalg.lstsq`, the default `rcond` is `-1`, and warns that in the future
the default will be `None`. Here, the default rcond is `None`.
2. In `np.linalg.lstsq` the returned residuals are empt... | 14 | linalg.py | 580 | remove numpy.linalg._promote_arg_dtypes
in favor of numpy.util._promote_dtypes_inexact | 26,804 | 1 | 280 | 336 | 145 | 120,239 | 218 | jax | 55 | jax/_src/numpy/linalg.py | Python | 34 | {
"docstring": "\\\n It has two important differences:\n\n 1. In `numpy.linalg.lstsq`, the default `rcond` is `-1`, and warns that in the future\n the default will be `None`. Here, the default rcond is `None`.\n 2. In `np.linalg.lstsq` the returned residuals are empty for low-rank or over-determined\n ... | https://github.com/google/jax.git |
2 | _add_results | def _add_results(self, results, trial_id):
for result in results:
self.logger.debug("Appending result: %s" % result)
result["trial_id"] = trial_id
result_record = ResultRecord.from_json(result)
result_record.save()
| d2f0c3b2f64b41f6541f6521e98cf3a37577c016 | 11 | collector.py | 75 | Clean up docstyle in data, ml, and tune packages (#25188) | 31,929 | 0 | 78 | 44 | 19 | 140,345 | 20 | ray | 11 | python/ray/tune/automlboard/backend/collector.py | Python | 6 | {
"docstring": "Add a list of results into db.\n\n Args:\n results: A list of json results.\n trial_id: Id of the trial.\n ",
"language": "en",
"n_whitespaces": 55,
"n_words": 19,
"vocab_size": 16
} | https://github.com/ray-project/ray.git | |
1 | test_login_session_without_hash_session_key | def test_login_session_without_hash_session_key(self):
user = User.objects.get(username="testclient")
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session[SESSION_KEY] = user.id
session.save()
original_session_key = session.sess... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 10 | test_views.py | 136 | Refs #33476 -- Reformatted code with Black. | 49,961 | 0 | 94 | 82 | 18 | 201,522 | 24 | django | 23 | tests/auth_tests/test_views.py | Python | 10 | {
"docstring": "\n Session without django.contrib.auth.HASH_SESSION_KEY should login\n without an exception.\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 8,
"vocab_size": 7
} | https://github.com/django/django.git | |
1 | house_graph | def house_graph(create_using=None):
description = [
"adjacencylist",
"House Graph",
5,
[[2, 3], [1, 4], [1, 4, 5], [2, 3, 5], [3, 4]],
]
G = make_small_undirected_graph(description, create_using)
return G
| dec723f072eb997a497a159dbe8674cd39999ee9 | 9 | small.py | 90 | Docstrings for the small.py module (#5240)
* added description for the first 5 small graphs
* modified descriptions based on comment and added description for two more functions
* added doctrings to all the functions
* Minor touchups.
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu> | 41,724 | 0 | 71 | 64 | 24 | 176,154 | 28 | networkx | 5 | networkx/generators/small.py | Python | 9 | {
"docstring": "\n Returns the House graph (square with triangle on top)\n\n The house graph is a simple undirected graph with\n 5 nodes and 6 edges [1]_.\n\n Parameters\n ----------\n create_using : NetworkX graph constructor, optional (default=nx.Graph)\n Graph type to create. If graph insta... | https://github.com/networkx/networkx.git | |
10 | getclosurevars | def getclosurevars(func):
if ismethod(func):
func = func.__func__
if not isfunction(func):
raise TypeError("{!r} is not a Python function".format(func))
code = func.__code__
# Nonlocal references are named in co_freevars and resolved
# by looking them up in __closure__ by pos... | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 15 | inspect.py | 319 | add python 3.10.4 for windows | 55,282 | 0 | 419 | 181 | 113 | 218,397 | 165 | XX-Net | 34 | python3.10.4/Lib/inspect.py | Python | 32 | {
"docstring": "\n Get the mapping of free variables to their current values.\n\n Returns a named tuple of dicts mapping the current nonlocal, global\n and builtin references as seen by the body of the function. A final\n set of unbound names that could not be resolved is also provided.\n ",
"languag... | https://github.com/XX-net/XX-Net.git | |
5 | process_deferred | def process_deferred(self) -> None:
update: typing.Dict[str, typing.Any] = {}
for optname, value in self.deferred.items():
if optname in self._options:
if isinstance(value, _UnconvertedStrings):
value = self._parse_setval(self._options[optname], v... | 6f0587734e2525eab49ba9a1d2052c87922125c7 | 16 | optmanager.py | 151 | Refactor how we process `--set` options (#5067)
* refactor how we process `--set` options
* minor improvements based on @marwinxxii's review
* fix nits
* update changelog | 73,536 | 0 | 141 | 97 | 27 | 250,719 | 35 | mitmproxy | 18 | mitmproxy/optmanager.py | Python | 14 | {
"docstring": "\n Processes options that were deferred in previous calls to set, and\n have since been added.\n ",
"language": "en",
"n_whitespaces": 45,
"n_words": 15,
"vocab_size": 15
} | https://github.com/mitmproxy/mitmproxy.git | |
4 | _minmax_mhlo | def _minmax_mhlo(op, cmp, x, y):
tensor_type = ir.RankedTensorType(x.type)
if ir.ComplexType.isinstance(tensor_type.element_type):
rx = mhlo.RealOp(x).result
ry = mhlo.RealOp(y).result
dims = [tensor_type.get_dim_size(i) for i in range(tensor_type.rank)]
bool_shape = ir.RankedTensorType.get(dims,... | 6cd9804163203e4da13b33171c5889b6d17e5f43 | 16 | mlir.py | 570 | Replace (deprecated) StrEnumAttr with EnumAttr.
ref: https://reviews.llvm.org/D120834
PiperOrigin-RevId: 435550738 | 26,700 | 0 | 556 | 347 | 56 | 119,845 | 97 | jax | 45 | jax/interpreters/mlir.py | Python | 32 | {
"docstring": "Min/max that compares complex values lexicographically as pairs.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | https://github.com/google/jax.git | |
2 | test_invites_by_users_ratelimit | def test_invites_by_users_ratelimit(self) -> None:
for _ in range(3):
room_id = self.helper.create_room_as(self.user_id)
self.helper.invite(room_id, self.user_id, "@other-users:red")
room_id = self.helper.create_room_as(self.user_id)
self.helper.invite(room_id,... | 2ffaf30803f93273a4d8a65c9e6c3110c8433488 | 11 | test_rooms.py | 115 | Add type hints to `tests/rest/client` (#12108)
* Add type hints to `tests/rest/client`
* newsfile
* fix imports
* add `test_account.py`
* Remove one type hint in `test_report_event.py`
* change `on_create_room` to `async`
* update new functions in `test_third_party_rules.py`
* Add `test_filter.py`... | 71,582 | 0 | 71 | 72 | 16 | 247,311 | 21 | synapse | 10 | tests/rest/client/test_rooms.py | Python | 7 | {
"docstring": "Tests that invites to a specific user are actually rate-limited.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/matrix-org/synapse.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.