complexity int64 1 56 | n_identifiers int64 1 114 | code stringlengths 19 12.7k | path stringlengths 8 134 | n_ast_nodes int64 12 2.35k | ast_errors stringlengths 0 4.01k | repo stringlengths 3 28 | documentation dict | n_words int64 2 866 | language stringclasses 1
value | vocab_size int64 2 323 | commit_id stringlengths 40 40 | file_name stringlengths 5 79 | id int64 243 338k | nloc int64 1 228 | token_counts int64 5 1.4k | fun_name stringlengths 1 77 | url stringlengths 31 60 | commit_message stringlengths 3 15.3k | n_whitespaces int64 1 3.23k | n_ast_errors int64 0 20 | d_id int64 74 121k | ast_levels int64 4 29 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 1 | def tutorial_taskflow_api_etl_docker_virtualenv():
# [END instantiate_dag]
# [START extract_virtualenv] | airflow/providers/docker/example_dags/tutorial_taskflow_api_etl_docker_virtualenv.py | 14 | airflow | {
"docstring": "\n ### TaskFlow API Tutorial Documentation\n This is a simple ETL data pipeline example which demonstrates the use of\n the TaskFlow API using three simple tasks for Extract, Transform, and Load.\n Documentation that goes along with the Airflow TaskFlow API tutorial is\n located\n [h... | 8 | Python | 7 | 5d89dea56843d7b76d5e308e373ba16ecbcffa77 | tutorial_taskflow_api_etl_docker_virtualenv.py | 45,428 | 14 | 66 | tutorial_taskflow_api_etl_docker_virtualenv | https://github.com/apache/airflow.git | Switch to Debian 11 (bullseye) as base for our dockerfiles (#21378)
Debian 11 Bullseye have been released some time ago as the new
LTS Debian release and already all our dependencies (including
MySQL and MSSQL ODBC drivers) caught up with it so we can finally
migrate to it.
This change switches base images to bu... | 17 | 0 | 8,558 | 6 | |
2 | 18 | def call_score(self, other_args):
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="score",
description=,
)
ns_parser = parse_known_args_and_warn(
parser, other_arg... | gamestonk_terminal/cryptocurrency/due_diligence/dd_controller.py | 97 | OpenBBTerminal | {
"docstring": "Process score command\n In this view you can find different kind of scores for loaded coin.\n Those scores represents different rankings, sentiment metrics, some user stats and others.\n You will see CoinGecko scores, Developer Scores, Community Scores, Sentiment, Redd... | 24 | Python | 21 | ea964109d654394cc0a5237e6ec5510ba6404097 | dd_controller.py | 281,134 | 18 | 61 | call_score | https://github.com/OpenBB-finance/OpenBBTerminal.git | Crypto menu refactor (#1119)
* enabled some crypto commands in dd to be called independent of source loaded
* support for coin_map_df in all dd functions + load ta and plot chart refactor
* updated tests and removed coingecko scrapping where possible
* removed ref of command from hugo
* updated pycoingecko... | 158 | 0 | 83,546 | 11 | |
13 | 28 | def defragment6(packets):
# Remove non fragments
lst = [x for x in packets if IPv6ExtHdrFragment in x]
if not lst:
return []
id = lst[0][IPv6ExtHdrFragment].id
llen = len(lst)
lst = [x for x in lst if x[IPv6ExtHdrFragment].id == id]
if len(lst) != llen:
warning("defra... | scapy/layers/inet6.py | 473 | scapy | {
"docstring": "\n Performs defragmentation of a list of IPv6 packets. Packets are reordered.\n Crap is dropped. What lacks is completed by 'X' characters.\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 21,
"vocab_size": 19
} | 174 | Python | 102 | 08b1f9d67c8e716fd44036a027bdc90dcb9fcfdf | inet6.py | 209,547 | 40 | 297 | defragment6 | https://github.com/secdev/scapy.git | 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-... | 412 | 0 | 52,730 | 15 | |
8 | 15 | def flattened_having(self) -> List[Condition]:
flattened: List[Condition] = []
boolean_conditions: List[BooleanCondition] = []
for condition in self.having:
if isinstance(condition, Condition):
flattened.append(condition)
elif isinstance(conditio... | src/sentry/search/events/builder.py | 184 | sentry | {
"docstring": "Return self.having as a flattened list ignoring boolean operators\n This is because self.having can have a mix of BooleanConditions and Conditions. And each BooleanCondition can in\n turn be a mix of either type.\n ",
"language": "en",
"n_whitespaces": 54,
"n_words": 33,
"... | 45 | Python | 30 | 2a4da479b2d4a2faa901701f4c73ff823236e9e8 | builder.py | 95,431 | 20 | 116 | flattened_having | https://github.com/getsentry/sentry.git | fix(snql): Add aggregations to select in auto_aggregation (#31061)
- This is to fix an issue for queries that have the uniq aggregation in
the HAVING clause, and is not selected.
- Previously we would not add the aggregation to the select clause in
these cases
- Now anything in the having clause will get... | 229 | 0 | 19,211 | 14 | |
1 | 7 | def scale_var(self) -> tk.StringVar:
retval = self._vars["scale"]
assert isinstance(retval, tk.StringVar)
return retval
| lib/training/preview_tk.py | 49 | faceswap | {
"docstring": ":class:`tkinter.StringVar`: The variable holding the currently selected \"##%\" formatted\n percentage scaling amount displayed in the Combobox. ",
"language": "en",
"n_whitespaces": 23,
"n_words": 16,
"vocab_size": 15
} | 12 | Python | 11 | 7da2cc3dd266aabebf41a31384cc2e0e7e5af6e5 | preview_tk.py | 101,568 | 6 | 29 | scale_var | https://github.com/deepfakes/faceswap.git | Training - Use custom preview pop-out | 40 | 0 | 20,978 | 8 | |
1 | 9 | def test_second_upgrade_from_different_user(self) -> None:
channel = self._upgrade_room()
self.assertEqual(200, channel.code, channel.result)
channel = self._upgrade_room(self.other_token, expire_cache=False)
self.assertEqual(400, channel.code, channel.result)
| tests/rest/client/test_upgrade_room.py | 89 | synapse | {
"docstring": "A second room upgrade from a different user is blocked.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 17 | Python | 13 | 99d3931974e65865d1102ee79d7b7e2b017a3180 | test_upgrade_room.py | 248,623 | 6 | 57 | test_second_upgrade_from_different_user | https://github.com/matrix-org/synapse.git | Add more tests for room upgrades (#13074)
Signed-off-by: Sean Quah <seanq@element.io> | 52 | 0 | 72,381 | 9 | |
5 | 18 | def generate_tex_file(expression, environment=None, tex_template=None):
if tex_template is None:
tex_template = config["tex_template"]
if environment is not None:
output = tex_template.get_texcode_for_expression_in_env(expression, environment)
else:
output = tex_template.get_tex... | manim/utils/tex_file_writing.py | 213 | manim | {
"docstring": "Takes a tex expression (and an optional tex environment),\n and returns a fully formed tex file ready for compilation.\n\n Parameters\n ----------\n expression : :class:`str`\n String containing the TeX expression to be rendered, e.g. ``\\\\sqrt{2}`` or ``foo``\n environment : Op... | 55 | Python | 40 | 9d1f066d637cb15baea10e6907ab85efff8fb36f | tex_file_writing.py | 190,078 | 18 | 122 | generate_tex_file | https://github.com/ManimCommunity/manim.git | Migrate more `os.path` to `pathlib` (#2980)
* Migrate more `os.path` to `pathlib`
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* fix type errors with recent pathlib code
* pathlib fixes
* more pathlib fixes
* remove unused imports introduced b... | 153 | 0 | 46,314 | 13 | |
1 | 8 | def find_legacy_row() -> StatementLambdaElement:
return lambda_stmt(lambda: select(func.max(States.event_id)))
| homeassistant/components/recorder/queries.py | 42 | core | {
"docstring": "Check if there are still states in the table with an event_id.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | 7 | Python | 7 | a70e2a33dcd85608f1145d8fc2e89a87620f4ef3 | queries.py | 300,743 | 3 | 24 | find_legacy_row | https://github.com/home-assistant/core.git | Fixing purging legacy rows and improve performance (#71916) | 13 | 0 | 99,602 | 13 | |
2 | 7 | def completed_count(self):
return sum(int(result.successful()) for result in self.results)
| celery/result.py | 41 | celery | {
"docstring": "Task completion count.\n\n Note that `complete` means `successful` in this context. In other words, the\n return value of this method is the number of ``successful`` tasks.\n\n Returns:\n int: the number of complete (i.e. successful) tasks.\n ",
"language": "en... | 8 | Python | 8 | 720d1928c4b583f36ca0cce7607b616466f2ffbb | result.py | 208,244 | 2 | 24 | completed_count | https://github.com/celery/celery.git | Add clarifying information to completed_count documentation (#7873)
* Add clarifying information to completed_count docstring
* Update canvas documentation | 22 | 0 | 52,260 | 11 | |
1 | 15 | def _create_mock_app_session(*args, **kwargs):
mock_id = mock.PropertyMock(
return_value="mock_id:%s" % ServerTestCase._next_session_id
)
ServerTestCase._next_session_id += 1
mock_session = mock.MagicMock(AppSession, autospec=True, *args, **kwargs)
type(mock... | lib/tests/server_test_case.py | 93 | streamlit | {
"docstring": "Create a mock AppSession. Each mocked instance will have\n its own unique ID.",
"language": "en",
"n_whitespaces": 19,
"n_words": 13,
"vocab_size": 13
} | 24 | Python | 19 | 704eab3478cf69847825b23dabf15813a8ac9fa2 | server_test_case.py | 118,583 | 8 | 57 | _create_mock_app_session | https://github.com/streamlit/streamlit.git | Rename and refactor `Report` machinery (#4141)
This refactor renames (almost) everything related to the outdated "report" concept with more precise concepts that we use throughout our code, primarily "script run", "session", and "app". | 84 | 0 | 26,306 | 11 | |
12 | 30 | def upgrade(refresh=True, dist_upgrade=False, **kwargs):
cache_valid_time = kwargs.pop("cache_valid_time", 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if "force_conf_new" in kwargs and kwargs["force_conf_new"]:
dpkg_options = ["--force-con... | salt/modules/aptpkg.py | 446 | salt | {
"docstring": "\n .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0\n On minions running systemd>=205, `systemd-run(1)`_ is now used to\n isolate commands which modify installed packages from the\n ``salt-minion`` daemon's control group. This is done to keep systemd\n from killing any a... | 95 | Python | 74 | 9e1ca8b5b9e7006fea28f473711917755cf5a262 | aptpkg.py | 216,507 | 36 | 254 | upgrade | https://github.com/saltstack/salt.git | Add --allow-downgrades capability for apt upgrade | 275 | 0 | 54,618 | 13 | |
1 | 9 | def elu(x, alpha=1.0):
return backend.elu(x, alpha)
@keras_export("keras.activations.selu")
@tf.__internal__.dispatch.add_dispatch_support | keras/activations.py | 54 | @keras_export("keras.activations.selu")
@tf.__internal__.dispatch.add_dispatch_support | keras | {
"docstring": "Exponential Linear Unit.\n\n The exponential linear unit (ELU) with `alpha > 0` is:\n `x` if `x > 0` and\n `alpha * (exp(x) - 1)` if `x < 0`\n The ELU hyperparameter `alpha` controls the value to which an\n ELU saturates for negative net inputs. ELUs diminish the\n vanishing gradient... | 8 | Python | 8 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | activations.py | 269,313 | 2 | 21 | elu | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 12 | 1 | 80,027 | 7 |
4 | 24 | async def async_update(self) -> None:
try:
self._weather = await self._weather_api.async_get_weather(self._station)
except (asyncio.TimeoutError, aiohttp.ClientError, ValueError) as error:
_LOGGER.error("Could not fetch weather data: %s", error)
return
... | homeassistant/components/trafikverket_weatherstation/sensor.py | 173 | core | {
"docstring": "Get the latest data from Trafikverket and updates the states.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 51 | Python | 46 | 395093351428d349246e4c1de526b159a167f382 | sensor.py | 308,863 | 19 | 109 | async_update | https://github.com/home-assistant/core.git | Code improvements to trafikverket_weatherstation (#62854)
* Code cleanup
* Fix extra state attributes
* Fix review comments
* Fix precipitation_amount if None
* Fix sensors returning None
* Use const for sensors reporting None | 213 | 0 | 107,592 | 12 | |
1 | 7 | def required_resources(self) -> Dict[str, float]:
return _sum_bundles(self._bundles)
| python/ray/tune/execution/placement_groups.py | 33 | ray | {
"docstring": "Returns a dict containing the sums of all resources",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | 7 | Python | 7 | 96cceb08e8bf73df990437002e25883c5a72d30c | placement_groups.py | 127,516 | 3 | 20 | required_resources | https://github.com/ray-project/ray.git | [tune] Raise error in PGF if head and worker bundles are empty (#28445)
Scheduling empty placement groups is not supported by Ray core (see e.g. #28443), so we shouldn't allow them to be created in the first place.
If we need fully empty resource requests, we can include this in the upcoming execution/resource refa... | 21 | 0 | 28,458 | 8 | |
1 | 5 | def chvatal_graph(create_using=None):
description = [
"adjacencylist",
"Chvatal Graph",
12,
[
[2, 5, 7, 10],
[3, 6, 8],
[4, 7, 9],
[5, 8, 10],
[6, 9],
[11, 12],
[11, 12],
[9, 12],
... | networkx/generators/small.py | 138 | networkx | {
"docstring": "\n Returns the Chvátal Graph\n\n The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_.\n It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized\n LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_.\n\n Parameters\n ----------\... | 44 | Python | 32 | dec723f072eb997a497a159dbe8674cd39999ee9 | small.py | 176,152 | 22 | 105 | chvatal_graph | https://github.com/networkx/networkx.git | 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> | 226 | 0 | 41,722 | 9 | |
1 | 14 | async def test_igration_and_updating_configuration(hass, hass_storage):
core_data = {
"data": {
"elevation": 10,
"latitude": 55,
"location_name": "Home",
"longitude": 13,
"time_zone": "Europe/Copenhagen",
"unit_system": "imperial",... | tests/test_config.py | 314 | core | {
"docstring": "Test updating configuration stores the new configuration.",
"language": "en",
"n_whitespaces": 6,
"n_words": 7,
"vocab_size": 7
} | 88 | Python | 70 | 67d1dde69fbacf33f2c39ea14d89f2afa425ed18 | test_config.py | 289,512 | 30 | 166 | test_igration_and_updating_configuration | https://github.com/home-assistant/core.git | Rename IMPERIAL_SYSTEM to US_CUSTOMARY_SYSTEM (#80253)
* Rename IMPERIAL_SYSTEM
* Deprecate is_metric property and adjust tests
* Adjust unit_system config validation
* Add yaml tests
* Add tests for private name
* Fix incorrect rebase
* Adjust docstring
* Add store migration
* Update unit_syst... | 280 | 0 | 88,654 | 11 | |
1 | 8 | def mock_cpuinfo_config_flow() -> Generator[MagicMock, None, None]:
with patch(
"homeassistant.components.cpuspeed.config_flow.cpuinfo.get_cpu_info",
return_value=True,
) as cpuinfo_mock:
yield cpuinfo_mock
@pytest.fixture | tests/components/cpuspeed/conftest.py | 58 | @pytest.fixture | core | {
"docstring": "Return a mocked get_cpu_info.\n\n It is only used to check truthy or falsy values, so it is mocked\n to return True.\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 21,
"vocab_size": 18
} | 16 | Python | 16 | 63d519c1a896c6eb20f7ffb032cb7712bbac6b5c | conftest.py | 291,535 | 11 | 29 | mock_cpuinfo_config_flow | https://github.com/home-assistant/core.git | Spelling updates (#82867) | 45 | 1 | 90,642 | 11 |
15 | 10 | def _propagate_index_objs(self, axis=None):
self._filter_empties()
if axis is None or axis == 0:
cum_row_lengths = np.cumsum([0] + self._row_lengths)
if axis is None or axis == 1:
cum_col_widths = np.cumsum([0] + self._column_widths)
if axis is None:
| modin/core/dataframe/pandas/dataframe/dataframe.py | 107 | modin | {
"docstring": "\n Synchronize labels by applying the index object for specific `axis` to the `self._partitions` lazily.\n\n Adds `set_axis` function to call-queue of each partition from `self._partitions`\n to apply new axis.\n\n Parameters\n ----------\n axis : int, default... | 34 | Python | 20 | 3c740dbfcdd69ddc3ab45a42be996e5c61104342 | dataframe.py | 152,956 | 64 | 373 | _propagate_index_objs | https://github.com/modin-project/modin.git | FEAT-#3111: Ensure relabeling Modin Frame does not lose partition shape (#3662)
Co-authored-by: Devin Petersohn <devin.petersohn@gmail.com>
Signed-off-by: Naren Krishna <naren@ponder.io> | 91 | 0 | 35,202 | 12 | |
5 | 28 | def _get_counts(values, uniques):
if values.dtype.kind in "OU":
counter = _NaNCounter(values)
output = np.zeros(len(uniques), dtype=np.int64)
for i, item in enumerate(uniques):
with suppress(KeyError):
output[i] = counter[item]
return output
uniq... | sklearn/utils/_encode.py | 252 | scikit-learn | {
"docstring": "Get the count of each of the `uniques` in `values`.\n\n The counts will use the order passed in by `uniques`. For non-object dtypes,\n `uniques` is assumed to be sorted and `np.nan` is at the end.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 35,
"vocab_size": 28
} | 63 | Python | 47 | 7f0006c8aad1a09621ad19c3db19c3ff0555a183 | _encode.py | 259,242 | 16 | 161 | _get_counts | https://github.com/scikit-learn/scikit-learn.git | ENH Adds infrequent categories to OneHotEncoder (#16018)
* ENH Completely adds infrequent categories
* STY Linting
* STY Linting
* DOC Improves wording
* DOC Lint
* BUG Fixes
* CLN Address comments
* CLN Address comments
* DOC Uses math to description float min_frequency
* DOC Adds comment r... | 154 | 0 | 75,673 | 13 | |
1 | 5 | def log_error(self, format, *args):
self.log_message(format, *args)
| python3.10.4/Lib/http/server.py | 33 | XX-Net | {
"docstring": "Log an error.\n\n This is called when a request cannot be fulfilled. By\n default it passes the message on to log_message().\n\n Arguments are the same as for log_message().\n\n XXX This should go to the separate error log.\n\n ",
"language": "en",
"n_whitespace... | 6 | Python | 6 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | server.py | 217,889 | 2 | 20 | log_error | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 20 | 0 | 54,992 | 8 | |
1 | 12 | def _video_tmp_file(self) -> str:
path, filename = os.path.split(self._output_filename)
retval = os.path.join(path, f"__tmp_{filename}")
logger.debug(retval)
return retval
| plugins/convert/writer/ffmpeg.py | 75 | faceswap | {
"docstring": " str: Full path to the temporary video file that is generated prior to muxing final\n audio. ",
"language": "en",
"n_whitespaces": 24,
"n_words": 16,
"vocab_size": 15
} | 15 | Python | 13 | 60291d49c4da1cd260fbc0b04aa6a312eedfefbb | ffmpeg.py | 100,621 | 7 | 43 | _video_tmp_file | https://github.com/deepfakes/faceswap.git | ffmpeg writer: Create new filename if output pre-exists | 50 | 0 | 20,083 | 10 | |
2 | 10 | def bar_chart(self, data=None, width=0, height=0, use_container_width=True):
if _use_arrow():
return self.dg._arrow_bar_chart(data, width, height, use_container_width)
else:
return self.dg._legacy_bar_chart(data, width, height, use_container_width)
| lib/streamlit/elements/dataframe_selector.py | 86 | streamlit | {
"docstring": "Display a bar chart.\n\n This is just syntax-sugar around st.altair_chart. The main difference\n is this command uses the data's own column and indices to figure out\n the chart's spec. As a result this is easier to use for many \"just plot\n this\" scenarios, while being l... | 19 | Python | 15 | 72703b38029f9358a0ec7ca5ed875a6b438ece19 | dataframe_selector.py | 118,728 | 5 | 59 | bar_chart | https://github.com/streamlit/streamlit.git | Replace static apps with live Cloud apps (#4317)
Co-authored-by: kajarenc <kajarenc@gmail.com> | 62 | 0 | 26,385 | 11 | |
1 | 11 | def write_filepath(filepath, strategy):
dirpath = os.path.dirname(filepath)
base = os.path.basename(filepath)
return os.path.join(write_dirpath(dirpath, strategy), base)
| keras/distribute/distributed_file_utils.py | 70 | keras | {
"docstring": "Returns the writing file path to be used to save file distributedly.\n\n Directory to contain `filepath` would be created if it doesn't exist.\n\n Args:\n filepath: Original filepath that would be used without distribution.\n strategy: The tf.distribute strategy object currently used.\... | 13 | Python | 12 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | distributed_file_utils.py | 270,311 | 4 | 44 | write_filepath | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 25 | 0 | 80,425 | 9 | |
1 | 11 | def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX")
| lib/matplotlib/backend_bases.py | 60 | matplotlib | {
"docstring": "\n Draw a TeX instance.\n\n Parameters\n ----------\n gc : `.GraphicsContextBase`\n The graphics context.\n x : float\n The x location of the text in display coords.\n y : float\n The y location of the text baseline in display ... | 17 | Python | 12 | 3b52d2b64f58c1eb912bd343e7c197a1ed0b92b5 | backend_bases.py | 109,806 | 2 | 44 | draw_tex | https://github.com/matplotlib/matplotlib.git | Remove redundant method, fix signature and add doc-string to draw_tex | 31 | 0 | 23,757 | 9 | |
2 | 31 | def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
company_currency = erpnext.get_company_currency(filters.get("company"))
def get_accounts(with_account_type_filter):
account_type_condition = ""
if with_account_type_filter:
account_type_condition = "AND account_type in %(account_types... | erpnext/controllers/queries.py | 249 | @frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs | erpnext | {
"docstring": "\n\t\t\tSELECT name, parent_account\n\t\t\tFROM `tabAccount`\n\t\t\tWHERE `tabAccount`.docstatus!=2\n\t\t\t\t{account_type_condition}\n\t\t\t\tAND is_group = 0\n\t\t\t\tAND company = %(company)s\n\t\t\t\tAND disabled = %(disabled)s\n\t\t\t\tAND (account_currency = %(currency)s or ifnull(account_curren... | 57 | Python | 44 | a1e3ae8869194a487acccc706a381db74c4aa1ff | queries.py | 68,540 | 7 | 48 | tax_account_query | https://github.com/frappe/erpnext.git | fix: user can select disabled accounts in taxes table | 28 | 1 | 14,815 | 16 |
6 | 8 | def filter_packages_untagged(self, package_data):
matches = {}
for package in package_data:
if "metadata" in package and "container" in package["metadata"]:
container_metadata = package["metadata"]["container"]
if "tags" in container_metadata:
... | .github/scripts/cleanup-tags.py | 121 | paperless-ngx | {
"docstring": "\n Filters the given package data to those which have no tags at all\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 13,
"vocab_size": 13
} | 36 | Python | 25 | 0fdd3d56f43c8442a0c9ecd3cad07a88137ff7de | cleanup-tags.py | 319,884 | 10 | 67 | filter_packages_untagged | https://github.com/paperless-ngx/paperless-ngx.git | Changes the cleanup images workflow so it uses a OAuth token with the correct scope (GITHUB_TOKEN is not enough). Also prevents running if the token is not defined and generally does commenting/cleanups" | 166 | 0 | 117,011 | 17 | |
9 | 30 | def employee_query(doctype, txt, searchfield, start, page_len, filters):
filters = frappe._dict(filters)
conditions = []
include_employees = []
emp_cond = ""
if not filters.payroll_frequency:
frappe.throw(_("Select Payroll Frequency."))
if filters.start_date and filters.end_date:
employee_list = get_employe... | erpnext/payroll/doctype/payroll_entry/payroll_entry.py | 387 | erpnext | {
"docstring": "select name, employee_name from `tabEmployee`\n\t\twhere status = 'Active'\n\t\t\tand docstatus < 2\n\t\t\tand ({key} like %(txt)s\n\t\t\t\tor employee_name like %(txt)s)\n\t\t\t{emp_cond}\n\t\t\t{fcond} {mcond}\n\t\torder by\n\t\t\tif(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),\n\t\t\tif(... | 103 | Python | 77 | 494bd9ef78313436f0424b918f200dab8fc7c20b | payroll_entry.py | 66,903 | 52 | 224 | employee_query | https://github.com/frappe/erpnext.git | style: format code with black | 63 | 0 | 14,374 | 14 | |
10 | 22 | def _process_contour_level_args(self, args):
if self.levels is None:
if len(args) == 0:
levels_arg = 7 # Default, hard-wired.
else:
levels_arg = args[0]
else:
levels_arg = self.levels
if isinstance(levels_arg, Integral... | lib/matplotlib/contour.py | 299 | matplotlib | {
"docstring": "\n Determine the contour levels and store in self.levels.\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 8,
"vocab_size": 8
} | 96 | Python | 66 | 1068a6faa19767724437461bcfb88c6852ec435c | contour.py | 110,019 | 23 | 185 | _process_contour_level_args | https://github.com/matplotlib/matplotlib.git | Remove unnecessary np.{,as}array / astype calls.
Quite often numpy will call asarray for us, saving us the need to call
asarray explicitly.
When we do call asarray (or array) ourselves, a dtype can directly be
passed in, rather than immediately calling astype immediately after.
Passing the dtype makes it unnecessary ... | 342 | 0 | 23,889 | 12 | |
3 | 13 | def _get_classifier_global_metrics(is_binomial, y, y_pred, y_probs, labels):
metrics = {}
metrics["accuracy"] = sk_metrics.accuracy_score(y, y_pred)
metrics["example_count"] = len(y)
if not is_binomial:
metrics["f1_score_micro"] = sk_metrics.f1_score(y, y_pred, average="micro", labels=labe... | mlflow/models/evaluation/default_evaluator.py | 176 | mlflow | {
"docstring": "\n get classifier metrics which computing over all classes examples.\n ",
"language": "en",
"n_whitespaces": 16,
"n_words": 9,
"vocab_size": 9
} | 43 | Python | 29 | 964f5ab75098c55f028f8acfeeae05df35ea68d5 | default_evaluator.py | 19,048 | 10 | 111 | _get_classifier_global_metrics | https://github.com/mlflow/mlflow.git | Evaluation Default evaluator (#5092)
* init
Signed-off-by: Weichen Xu <weichen.xu@databricks.com>
* update
Signed-off-by: Weichen Xu <weichen.xu@databricks.com>
* update
Signed-off-by: Weichen Xu <weichen.xu@databricks.com>
* update
Signed-off-by: Weichen Xu <weichen.xu@databricks.com>
* update... | 85 | 0 | 2,882 | 12 | |
1 | 8 | def test_show_message_twice(view, info1, info2, count):
view.show_message(info1)
view.show_message(info2)
assert len(view._messages) == count
| tests/unit/mainwindow/test_messageview.py | 53 | qutebrowser | {
"docstring": "Show the exact same message twice -> only one should be shown.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | 11 | Python | 11 | 676e01677183825d19107d3b2fbf1bb2c0684ede | test_messageview.py | 320,942 | 4 | 33 | test_show_message_twice | https://github.com/qutebrowser/qutebrowser.git | Only replace the exact same message
If we have a error message followed by an info message with the same text, they
should both be shown, not replaced automatically. | 23 | 0 | 117,451 | 9 | |
1 | 2 | def check_auth(f):
| py/visdom/utils/server_utils.py | 13 | visdom | {
"docstring": "\n Wrapper for server access methods to ensure that the access\n is authorized.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 12,
"vocab_size": 11
} | 2 | Python | 2 | 60c90e313e106c0af62339d29eeda0e62823c648 | server_utils.py | 106,773 | 3 | 10 | check_auth | https://github.com/fossasia/visdom.git | Refactoring server.py into more intentional files | 5 | 0 | 22,434 | 6 | |
1 | 8 | def start_leader_mode(self):
logger.info("Running rpc.replicate in Leader mode")
logger.info("-" * 15)
logger.info(f"API_KEY: {self.secret_api_key}")
logger.info("-" * 15)
self.register_leader_endpoint()
self.submit_coroutine(self.leader_loop())
| freqtrade/rpc/replicate/__init__.py | 100 | freqtrade | {
"docstring": "\n Register the endpoint and start the leader loop\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 8,
"vocab_size": 7
} | 17 | Python | 14 | 9f6bba40af1a407f190a89f5c0c8b4e3f528ba46 | __init__.py | 150,410 | 7 | 50 | start_leader_mode | https://github.com/freqtrade/freqtrade.git | initial concept for replicate, basic leader and follower logic | 66 | 0 | 34,734 | 10 | |
1 | 9 | def test_exclude_glob_case5():
incl_dom = {}
incl_glob = {}
incl_ent = {"binary_sensor.working"}
excl_dom = {}
excl_glob = {"binary_sensor.*"}
excl_ent = {"light.ignoreme", "sensor.notworking"}
testfilter = generate_filter(
incl_dom, incl_ent, excl_dom, excl_ent, incl_glob, excl... | tests/helpers/test_entityfilter.py | 169 | core | {
"docstring": "Test case 5 - include and exclude specified, with excluded glob.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 53 | Python | 33 | a8349a4866d22cddbca9ac9367d4affae39a8325 | test_entityfilter.py | 314,752 | 17 | 93 | test_exclude_glob_case5 | https://github.com/home-assistant/core.git | Adjust entity filters to make includes stronger than excludes (#74080)
* Adjust entity filters to make includes stronger than excludes
Fixes #59080
* adjust test for stronger entity glob includes
* sync with docs | 108 | 0 | 113,356 | 9 | |
1 | 3 | def _generate_client_device_id() -> str:
return random_uuid_hex()
| homeassistant/components/jellyfin/config_flow.py | 22 | core | {
"docstring": "Generate a random UUID4 string to identify ourselves.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 6 | Python | 6 | 5b0a37a44752edbbf785d6a200e3b7a3f5fa2047 | config_flow.py | 288,716 | 3 | 11 | _generate_client_device_id | https://github.com/home-assistant/core.git | Use persistent device id for jellyfin requests (#79840) | 12 | 0 | 87,869 | 7 | |
2 | 16 | def evaluate_loss(net, data_iter, loss):
metric = d2l.Accumulator(2) # Sum of losses, no. of examples
for X, y in data_iter:
l = loss(net(X), y)
metric.add(d2l.reduce_sum(l), d2l.size(l))
return metric[0] / metric[1]
DATA_HUB = dict()
DATA_URL = 'http://d2l-data.s3-accelerate.amazonaw... | d2l/mxnet.py | 116 | d2l-zh | {
"docstring": "Evaluate the loss of a model on the given dataset.\n\n Defined in :numref:`sec_model_selection`",
"language": "en",
"n_whitespaces": 15,
"n_words": 13,
"vocab_size": 12
} | 35 | Python | 31 | b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2 | mxnet.py | 158,210 | 6 | 64 | evaluate_loss | https://github.com/d2l-ai/d2l-zh.git | [PaddlePaddle] Merge master into Paddle branch (#1186)
* change 15.2 title in chinese version (#1109)
change title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘
* 修改部分语义表述 (#1105)
* Update r0.17.5 (#1120)
* Bump versions in installation
* 94行typo: (“bert.mall”)->(“bert.small”) (#1129)
* line 313: "b... | 60 | 0 | 37,379 | 12 | |
2 | 10 | def _copy2_ignoring_special_files(src, dest):
# type: (str, str) -> None
try:
copy2_fixed(src, dest)
except shutil.SpecialFileError as e:
# SpecialFileError may be raised due to either the source or
# destination. If the destination was the cause then we would actually
#... | .venv/lib/python3.8/site-packages/pip/_internal/operations/prepare.py | 69 | transferlearning | {
"docstring": "Copying special files is not supported, but as a convenience to users\n we skip errors copying them. This supports tools that may create e.g.\n socket files in the project source directory.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 31,
"vocab_size": 30
} | 79 | Python | 66 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | prepare.py | 60,951 | 10 | 39 | _copy2_ignoring_special_files | https://github.com/jindongwang/transferlearning.git | upd; format | 184 | 0 | 12,357 | 12 | |
1 | 2 | def prepare_template(self) -> None:
| airflow/models/base.py | 16 | airflow | {
"docstring": "Hook triggered after the templated fields get replaced by their content.\n\n If you need your operator to alter the content of the file before the\n template is rendered, it should override this method to do so.\n ",
"language": "en",
"n_whitespaces": 57,
"n_words": 36,
"v... | 4 | Python | 4 | ff3bbc3db24f9f3f4f88033d48859fb08fc3237b | base.py | 44,166 | 6 | 8 | prepare_template | https://github.com/apache/airflow.git | Implement enough interface for MappedOperator to be baggable (#20945) | 11 | 0 | 8,185 | 6 | |
1 | 2 | def hiddenlabels(self):
return self["hiddenlabels"]
| packages/python/plotly/plotly/graph_objs/_layout.py | 22 | plotly.py | {
"docstring": "\n hiddenlabels is the funnelarea & pie chart analog of\n visible:'legendonly' but it can contain many labels, and can\n simultaneously hide slices from several pies/funnelarea charts\n\n The 'hiddenlabels' property is an array that may be specified as a tuple,\n lis... | 4 | Python | 4 | 43e3a4011080911901176aab919c0ecf5046ddd3 | _layout.py | 227,329 | 2 | 11 | hiddenlabels | https://github.com/plotly/plotly.py.git | switch to black .22 | 18 | 0 | 59,002 | 7 | |
1 | 11 | def test_dataset_shard_error_with_both_format_and_loader_fn(self):
dset = ray.data.range(100)
config = {
"input": "dataset",
"input_config": {
"format": "json",
"paths": self.dset_path,
"loader_fn": lambda: dset,
... | rllib/offline/tests/test_dataset_reader.py | 105 | ray | {
"docstring": "Tests whether the dataset_shard function raises an error when both format\n and loader_fn are specified.",
"language": "en",
"n_whitespaces": 21,
"n_words": 15,
"vocab_size": 15
} | 24 | Python | 22 | 569fe0109629048d08e1d9e023f7769f10bd2244 | test_dataset_reader.py | 125,006 | 12 | 57 | test_dataset_shard_error_with_both_format_and_loader_fn | https://github.com/ray-project/ray.git | [RLlib] improved unittests for dataset_reader and fixed bugs (#26458) | 148 | 0 | 27,746 | 11 | |
3 | 18 | async def async_refresh_sensor(self) -> None:
_LOGGER.debug("Refreshing library sensor for '%s'", self.name)
try:
await self.hass.async_add_executor_job(self._update_state_and_attrs)
self._attr_available = True
except NotFound:
self._attr_available = ... | homeassistant/components/plex/sensor.py | 132 | core | {
"docstring": "Update state and attributes for the library sensor.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 42 | Python | 33 | 474844744bdd2b0dcba46b82d9d3fcd8e3dbad24 | sensor.py | 305,878 | 16 | 78 | async_refresh_sensor | https://github.com/home-assistant/core.git | Improve entity type hints [p] (#77871) | 195 | 0 | 104,662 | 12 | |
1 | 15 | def test_joindocuments_score_none(join_mode, sort_by_score):
inputs = [
{"documents": [Document(content="text document 1", content_type="text", score=0.2)]},
{"documents": [Document(content="text document 2", content_type="text", score=None)]},
]
join_docs = JoinDocuments(join_mode=joi... | test/nodes/test_other.py | 181 | haystack | {
"docstring": "Testing JoinDocuments() node when some of the documents have `score=None`",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 40 | Python | 28 | 408d8e6ff559ed0a195b68284baf3ab23707ffd7 | test_other.py | 257,752 | 10 | 112 | test_joindocuments_score_none | https://github.com/deepset-ai/haystack.git | Enable the `JoinDocuments` node to work with documents with `score=None` (#2984)
* Enable the `JoinDocuments` node to work with documents with `score=None`
This fixes #2983
As of now, the `JoinDocuments` node will error out if any of the documents has `score=None` - which is possible, as some retriever are not a... | 78 | 0 | 75,129 | 14 | |
2 | 33 | def test_parent_skip_branch(session, dag_maker):
start_date = pendulum.datetime(2020, 1, 1)
with dag_maker(
"test_parent_skip_branch_dag",
schedule_interval=None,
start_date=start_date,
session=session,
):
op1 = BranchPythonOperator(task_id="op1", python_callable... | tests/ti_deps/deps/test_not_previously_skipped_dep.py | 272 | airflow | {
"docstring": "\n A simple DAG with a BranchPythonOperator that does not follow op2. NotPreviouslySkippedDep is not met.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 15,
"vocab_size": 14
} | 59 | Python | 49 | 49e336ae0302b386a2f47269a6d13988382d975f | test_not_previously_skipped_dep.py | 47,672 | 21 | 168 | test_parent_skip_branch | https://github.com/apache/airflow.git | Replace usage of `DummyOperator` with `EmptyOperator` (#22974)
* Replace usage of `DummyOperator` with `EmptyOperator` | 162 | 0 | 9,207 | 14 | |
3 | 14 | def _check_precomputed(X):
if not issparse(X):
X = check_array(X)
check_non_negative(X, whom="precomputed distance matrix.")
return X
else:
graph = X
if graph.format not in ("csr", "csc", "coo", "lil"):
raise TypeError(
"Sparse matrix in {!r} format ... | sklearn/neighbors/_base.py | 184 | scikit-learn | {
"docstring": "Check precomputed distance matrix.\n\n If the precomputed distance matrix is sparse, it checks that the non-zero\n entries are sorted by distances. If not, the matrix is copied and sorted.\n\n Parameters\n ----------\n X : {sparse matrix, array-like}, (n_samples, n_samples)\n Dis... | 66 | Python | 48 | b94bc5ea6821607d1e9826ce2d084c76379820ba | _base.py | 259,864 | 17 | 105 | _check_precomputed | https://github.com/scikit-learn/scikit-learn.git | ENH add new function sort_graph_by_row_values (#23139)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> | 157 | 0 | 75,958 | 13 | |
2 | 14 | def _set_per_output_metric_attributes(self, metrics_dict, output_index):
updated_metrics_dict = collections.OrderedDict()
for metric_name, metric_fn in metrics_dict.items():
metric_name = self._add_unique_metric_name(
metric_name, metric_fn, output_index
... | keras/engine/training_v1.py | 99 | keras | {
"docstring": "Sets the metric attributes on the model for the given output.\n\n Args:\n metrics_dict: A dict with metric names as keys and metric fns as values.\n output_index: The index of the model output for which the metric\n attributes are added.\n\n Returns:\n ... | 53 | Python | 40 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | training_v1.py | 272,015 | 10 | 61 | _set_per_output_metric_attributes | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 174 | 0 | 80,937 | 10 | |
1 | 20 | async def test_peer_cert_ignored_with_supervisor(hass, tmpdir):
cert_path, key_path, peer_cert_path = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmpdir
)
with patch("ssl.SSLContext.load_cert_chain"), patch(
"homeassistant.components.http.supervisor.has_supervisor", ... | tests/components/http/test_init.py | 209 | core | {
"docstring": "Test peer certiicate requirement ignored in supervised deployments.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | 62 | Python | 48 | 938b64081b0cbc21d1a9c1141c1e575824ce31ae | test_init.py | 292,578 | 31 | 119 | test_peer_cert_ignored_with_supervisor | https://github.com/home-assistant/core.git | Block peer certs on supervisor (#66837)
Co-authored-by: Pascal Vizeli <pvizeli@syshack.ch>
Co-authored-by: Mike Degatano <michael.degatano@gmail.com> | 375 | 0 | 91,654 | 17 | |
5 | 21 | def get_default_locale(self):
# Check if the object has any parental keys to another translatable model
# If so, take the locale from the object referenced in that parental key
parental_keys = [
field
for field in self._meta.get_fields()
if isinstance... | wagtail/core/models/i18n.py | 140 | wagtail | {
"docstring": "\n Finds the default locale to use for this object.\n\n This will be called just before the initial save.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 17
} | 59 | Python | 48 | d10f15e55806c6944827d801cd9c2d53f5da4186 | i18n.py | 73,907 | 17 | 86 | get_default_locale | https://github.com/wagtail/wagtail.git | Reformat with black | 260 | 0 | 16,170 | 18 | |
1 | 13 | def test_copy_with_encryption(self):
op = DatabricksCopyIntoOperator(
file_location=COPY_FILE_LOCATION,
file_format='CSV',
table_name='test',
task_id=TASK_ID,
encryption={'TYPE': 'AWS_SSE_C', 'MASTER_KEY': 'abc'},
)
assert (
... | tests/providers/databricks/operators/test_databricks_sql.py | 95 | airflow | {
"docstring": "COPY INTO test\nFROM '{COPY_FILE_LOCATION}' WITH ( ENCRYPTION (TYPE = 'AWS_SSE_C', MASTER_KEY = 'abc'))\nFILEFORMAT = CSV\n",
"language": "en",
"n_whitespaces": 14,
"n_words": 17,
"vocab_size": 15
} | 20 | Python | 19 | 401419432082d222b823e4f2a66f21e5cc3ab28d | test_databricks_sql.py | 45,915 | 15 | 53 | test_copy_with_encryption | https://github.com/apache/airflow.git | Add new options to DatabricksCopyIntoOperator (#22076)
This includes:
* `encryption` - to specify encryption options for a given location
* `credential` - to specify authentication options for a given location
* `validate` - to control validation of schema & data | 124 | 0 | 8,742 | 12 | |
5 | 7 | def tokenize(lines, token='word'):
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type: ' + token)
| d2l/mxnet.py | 90 | d2l-zh | {
"docstring": "Split text lines into word or character tokens.\n\n Defined in :numref:`sec_text_preprocessing`",
"language": "en",
"n_whitespaces": 13,
"n_words": 11,
"vocab_size": 11
} | 31 | Python | 23 | b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2 | mxnet.py | 158,197 | 7 | 51 | tokenize | https://github.com/d2l-ai/d2l-zh.git | [PaddlePaddle] Merge master into Paddle branch (#1186)
* change 15.2 title in chinese version (#1109)
change title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘
* 修改部分语义表述 (#1105)
* Update r0.17.5 (#1120)
* Bump versions in installation
* 94行typo: (“bert.mall”)->(“bert.small”) (#1129)
* line 313: "b... | 64 | 0 | 37,370 | 12 | |
3 | 18 | def export_model(self, model_path, calibration_path=None, onnx_path=None, input_shape=None, device=None):
assert model_path is not None, 'model_path must be specified'
self._unwrap_model()
calibration_config = {}
for name, module in self.bound_model.named_modules():
... | nni/compression/pytorch/quantization/bnn_quantizer.py | 168 | nni | {
"docstring": "\n Export quantized model weights and calibration parameters(optional)\n\n Parameters\n ----------\n model_path : str\n path to save quantized model weight\n calibration_path : str\n (optional) path to save quantize parameters after calibration\... | 44 | Python | 39 | d68c786ff81bad19c04619d6a999ff34aaa724e7 | bnn_quantizer.py | 113,612 | 11 | 110 | export_model | https://github.com/microsoft/nni.git | [Compression] remove pruning v1 & refactor directory (#5228) | 145 | 0 | 24,975 | 13 | |
1 | 12 | def test_new_room_user_is_not_local(self) -> None:
channel = self.make_request(
"DELETE",
self.url,
content={"new_room_user_id": "@not:exist.bla"},
access_token=self.admin_user_tok,
)
self.assertEqual(400, channel.code, msg=channel.json_... | tests/rest/admin/test_room.py | 107 | synapse | {
"docstring": "\n Check that only local users can create new room to move members.\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 12,
"vocab_size": 12
} | 25 | Python | 24 | 2281427175e4c93a30c39607fb4ac23c2a1f399f | test_room.py | 249,342 | 15 | 65 | test_new_room_user_is_not_local | https://github.com/matrix-org/synapse.git | Use literals in place of `HTTPStatus` constants in tests (#13488)
* Use literals in place of `HTTPStatus` constants in tests
* newsfile
* code style
* code style | 133 | 0 | 72,845 | 12 | |
12 | 34 | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
... | pipenv/patched/notpip/_vendor/distlib/_backport/shutil.py | 479 | pipenv | {
"docstring": "Create a zip file from all the files under 'base_dir'.\n\n The output zip file will be named 'base_name' + \".zip\". Uses either the\n \"zipfile\" Python module (if available) or the InfoZIP \"zip\" utility\n (if installed and found on the default search path). If neither tool is\n avail... | 148 | Python | 97 | c69d55f7c82d5ae2cce542bcfb98d043ca4836a0 | shutil.py | 21,352 | 30 | 210 | _make_zipfile | https://github.com/pypa/pipenv.git | Vendor in pip 22.1.2 | 529 | 0 | 3,780 | 21 | |
1 | 20 | def test_get_instance_view_filters_out_name_with_filter_backend(self):
instance_view = InstanceView.as_view(filter_backends=(ExclusiveFilterBackend,))
request = factory.get('/1')
response = instance_view(request, pk=1).render()
assert response.status_code == status.HTTP_404_NOT_... | tests/test_generics.py | 116 | django-rest-framework | {
"docstring": "\n GET requests to RetrieveUpdateDestroyAPIView should raise 404 when model filtered out.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 11,
"vocab_size": 11
} | 31 | Python | 27 | 56946fac8f29aa44ce84391f138d63c4c8a2a285 | test_generics.py | 48,681 | 11 | 68 | test_get_instance_view_filters_out_name_with_filter_backend | https://github.com/encode/django-rest-framework.git | Preserve exception messages for wrapped Django exceptions (#8051)
* Preserve messages for wrapped Django exceptions
* Fix the test
* Update test_generics.py
* Update test_generics.py
Co-authored-by: Tom Christie <tom@tomchristie.com> | 132 | 0 | 9,567 | 12 | |
1 | 3 | def onCopiedDLL(self, dll_filename):
# Virtual method, pylint: disable=no-self-use,unused-argument
return None
| nuitka/plugins/PluginBase.py | 19 | Nuitka | {
"docstring": "Chance for a plugin to modify DLLs after copy, e.g. to compress it, remove attributes, etc.\n\n Args:\n dll_filename: the filename of the DLL\n\n Notes:\n Do not remove or add any files in this method, this will not work well, there\n is e.g. getExtraDLLs... | 10 | Python | 10 | 87c7dd5551f276dc0b68168d952c55aa3e4d07f8 | PluginBase.py | 178,438 | 2 | 10 | onCopiedDLL | https://github.com/Nuitka/Nuitka.git | Plugins: Add support for modifying DLLs after standalone copy | 31 | 0 | 42,698 | 6 | |
6 | 9 | def set_video_backend(backend):
global _video_backend
if backend not in ["pyav", "video_reader", "cuda"]:
raise ValueError("Invalid video backend '%s'. Options are 'pyav', 'video_reader' and 'cuda'" % backend)
if backend == "video_reader" and not io._HAS_VIDEO_OPT:
# TODO: better messag... | torchvision/__init__.py | 125 | vision | {
"docstring": "\n Specifies the package used to decode videos.\n\n Args:\n backend (string): Name of the video backend. one of {'pyav', 'video_reader'}.\n The :mod:`pyav` package uses the 3rd party PyAv library. It is a Pythonic\n binding for the FFmpeg libraries.\n The ... | 78 | Python | 49 | 2e833520618dc460cbeb693e29e40b65a02ccafb | __init__.py | 194,093 | 12 | 66 | set_video_backend | https://github.com/pytorch/vision.git | Pyav backend for VideoReader API (#6598)
* Test: add backend parameter
* VideoReader object now works on backend
* Frame reading now passes
* Keyframe seek now passes
* Pyav backend now supports metadata
* changes in test to reflect GPU decoder change
* Linter?
* Test GPU output
* Addressing Jo... | 152 | 0 | 46,938 | 11 | |
1 | 17 | def step(self, action, sumo_handler):
logger.debug("Agent %s: action %d", self.agent_id, action)
# Subscriptions EXAMPLE:
# {"agent_0": {64: 14.603468282230542, 104: None},
# "agent_1": {64: 12.922797055918513,
# 104: ("veh.19", 27.2398701218025... | rllib/examples/simulators/sumo/marlenvironment.py | 157 | ray | {
"docstring": "Implements the logic of each specific action passed as input.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | 49 | Python | 40 | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | marlenvironment.py | 143,721 | 11 | 96 | step | https://github.com/ray-project/ray.git | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 184 | 0 | 33,027 | 11 | |
2 | 17 | def test_kbinsdiscrtizer_get_feature_names_out(encode, expected_names):
X = [[-2, 1, -4], [-1, 2, -3], [0, 3, -2], [1, 4, -1]]
kbd = KBinsDiscretizer(n_bins=4, encode=encode).fit(X)
Xt = kbd.transform(X)
input_features = [f"feat{i}" for i in range(3)]
output_names = kbd.get_feature_names_out(... | sklearn/preprocessing/tests/test_discretization.py | 174 | scikit-learn | {
"docstring": "Check get_feature_names_out for different settings.\n Non-regression test for #22731\n ",
"language": "en",
"n_whitespaces": 15,
"n_words": 9,
"vocab_size": 8
} | 40 | Python | 36 | 36c6c74e5fd9033e9b89a1348de2466e7ac48a8c | test_discretization.py | 259,155 | 8 | 115 | test_kbinsdiscrtizer_get_feature_names_out | https://github.com/scikit-learn/scikit-learn.git | FIX Fixes KBinsDiscretizer for encode=ordinal (#22735)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> | 64 | 0 | 75,608 | 11 | |
3 | 10 | def _has_arrow_table(self):
if not isinstance(self._op, FrameNode):
return False
return all(p.arrow_table is not None for p in self._partitions.flatten())
| modin/experimental/core/execution/native/implementations/hdk_on_native/dataframe/dataframe.py | 63 | modin | {
"docstring": "\n Return True for materialized frame with Arrow table.\n\n Returns\n -------\n bool\n ",
"language": "en",
"n_whitespaces": 47,
"n_words": 11,
"vocab_size": 11
} | 17 | Python | 15 | 027f92a7655ae5b473839b7956ff52bf7879f3cc | dataframe.py | 154,793 | 4 | 39 | _has_arrow_table | https://github.com/modin-project/modin.git | FIX-#4022: Fixed empty data frame with index (#4910)
Signed-off-by: Andrey Pavlenko <andrey.a.pavlenko@gmail.com> | 49 | 0 | 36,150 | 11 | |
2 | 14 | def get_experiment_checkpoint_dir(cls, run_obj, local_dir=None, name=None):
assert run_obj
local_dir = _get_local_dir_with_expand_user(local_dir)
run_identifier = cls.get_trainable_name(run_obj)
combined_name = name or run_identifier
dir_name = _get_dir_name(run_obj, na... | python/ray/tune/experiment.py | 89 | ray | {
"docstring": "Get experiment checkpoint dir without setting up an experiment.\n\n This is only used internally for better support of Tuner API.\n\n Args:\n run_obj (str|function|class): Trainable to run.\n name (str): The name of the experiment specified by user.\n loc... | 26 | Python | 22 | 814b49356c1e773f2ec8d7c643acef48b6db08cf | experiment.py | 146,782 | 7 | 58 | get_experiment_checkpoint_dir | https://github.com/ray-project/ray.git | [tuner] Tuner impl. (#22848) | 75 | 0 | 33,777 | 8 | |
2 | 4 | def dag_id(self) -> str:
if self.dag:
return self.dag.dag_id
return "_in_memory_dag_"
| airflow/models/taskmixin.py | 38 | airflow | {
"docstring": "Returns dag id if it has one or an adhoc/meaningless ID",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 10 | Python | 9 | 34154803ac73d62d3e969e480405df3073032622 | taskmixin.py | 46,825 | 5 | 21 | dag_id | https://github.com/apache/airflow.git | Show tasks in grid view based on topological sort. (#22741)
This takes the existing topological sort that existed on a DAG and moves
it down to TaskGroup.
In order to do this (and not have duplicated sort) the existing sort on
DAG is re-implemented on top of the new method.
This also surfaced a tiny bug in des... | 42 | 0 | 9,007 | 9 | |
5 | 21 | def _check_pkg(target):
log.debug(f"_check_pkg target '{target}'")
ret = {}
cmd = ["/usr/bin/lslpp", "-Lc", target]
lines = __salt__["cmd.run_all"](cmd, python_shell=False).splitlines()
name = ""
version_num = ""
rpmpkg = False
for line in lines:
if line.startswith("#"):
... | salt/modules/aixpkg.py | 272 | salt | {
"docstring": "\n Return name, version and if rpm package for specified target\n ",
"language": "en",
"n_whitespaces": 17,
"n_words": 10,
"vocab_size": 10
} | 94 | Python | 70 | b2f8271fed3f05160431c55ad7c4e8f3e3e95c3e | aixpkg.py | 215,103 | 28 | 148 | _check_pkg | https://github.com/saltstack/salt.git | Complete intial tests for AIX yum and dnf support | 290 | 0 | 53,820 | 17 | |
1 | 10 | def polyfit(x, y, deg, rcond=None, full=False, w=None):
return pu._fit(polyvander, x, y, deg, rcond, full, w)
| numpy/polynomial/polynomial.py | 56 | numpy | {
"docstring": "\n Least-squares fit of a polynomial to data.\n\n Return the coefficients of a polynomial of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one f... | 15 | Python | 13 | 4f479744bb9f5150d1406fdb0203c5d8714e7283 | polynomial.py | 160,848 | 2 | 41 | polyfit | https://github.com/numpy/numpy.git | DOC: Replace the mathematical notation N(...) with text.
The meaning of the second argument in the mathematical notation
N(mu, b) for the normal distribution is not consistent. In some
references it is the variance while in others it is the standard
deviation. Let's avoid the ambiguity by not using the notation.
Fix... | 21 | 0 | 38,758 | 7 | |
1 | 10 | def get_metrics(self, font, font_class, sym, fontsize, dpi):
r
info = self._get_info(font, font_class, sym, fontsize, dpi)
return info.metrics
| lib/matplotlib/_mathtext.py | 50 | matplotlib | {
"docstring": "\n Parameters\n ----------\n font : str\n One of the TeX font names: \"tt\", \"it\", \"rm\", \"cal\", \"sf\", \"bf\",\n \"default\", \"regular\", \"bb\", \"frak\", \"scr\". \"default\" and \"regular\"\n are synonyms and use the non-math font.\n ... | 17 | Python | 14 | 85f30cbd485eddc93e3c9ff115ac21c0886909d5 | _mathtext.py | 108,619 | 38 | 37 | get_metrics | https://github.com/matplotlib/matplotlib.git | Remove *math* parameter of various mathtext internal APIs.
The *math* parameter is passed through many layers of the call stack
but is ultimately only used for a single purpose: deciding whether to
replace the ASCII hyphen by a (longer) unicode minus. Instead of doing
that, just do the substitution at the parsing sta... | 37 | 0 | 23,274 | 8 | |
3 | 18 | def to_objectchange(self, action):
from extras.models import ObjectChange
objectchange = ObjectChange(
changed_object=self,
object_repr=str(self)[:200],
action=action
)
if hasattr(self, '_prechange_snapshot'):
objectchange.prechang... | netbox/netbox/models/features.py | 118 | netbox | {
"docstring": "\n Return a new ObjectChange representing a change made to this object. This will typically be called automatically\n by ChangeLoggingMiddleware.\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 19,
"vocab_size": 18
} | 30 | Python | 26 | b67859832afa52742defa0a5bd60f9be1ddbe8e4 | features.py | 264,331 | 12 | 75 | to_objectchange | https://github.com/netbox-community/netbox.git | Refactor to_objectchange() | 134 | 0 | 77,693 | 12 | |
17 | 37 | def custom_lemmas(self, tab_file, lang):
lg = lang.split("_")[0]
if len(lg) != 3:
raise ValueError("lang should be a (3 character) ISO 639-3 code")
self._lang_data[lang] = [
defaultdict(list),
defaultdict(list),
defaultdict(list),
... | nltk/corpus/reader/wordnet.py | 554 | nltk | {
"docstring": "\n Reads a custom tab file containing mappings of lemmas in the given\n language to Princeton WordNet 3.0 synset offsets, allowing NLTK's\n WordNet functions to then be used with that language.\n\n See the \"Tab files\" section at http://compling.hss.ntu.edu.sg/omw/ for\n ... | 185 | Python | 122 | 3ca43e26efd7d5aa37b3cd79446258d8bfa79561 | wordnet.py | 42,581 | 45 | 325 | custom_lemmas | https://github.com/nltk/nltk.git | Fix wordnet's all_synsets() function (#3078)
* Fix all_synsets() function
* Add simple regression tests for #3077
* Add suggestions by @tomaarsen
Co-authored-by: Tom Aarsen <Cubiegamedev@gmail.com> | 1,060 | 0 | 7,637 | 20 | |
1 | 7 | def connect(self, **kwargs) -> Dict[str, int]:
raise NotImplementedError()
| mindsdb/integrations/libs/base_handler.py | 33 | mindsdb | {
"docstring": "\n Set up any connections required by the handler here.\n\n Should return output of check_status() method after attempting connection.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 18
} | 8 | Python | 8 | c40c732253043ea111fbf197248a1bff4b7a524e | base_handler.py | 115,077 | 7 | 20 | connect | https://github.com/mindsdb/mindsdb.git | handlers | 22 | 0 | 25,356 | 7 | |
6 | 11 | def get_function_for_token(frame, token, previous_frame=None):
frame_function_name = frame.get("function")
token_function_name = token.function_name
# Try to use the function name we got from sourcemap-cache, filtering useless names.
if token_function_name not in USELESS_FN_NAMES:
return ... | src/sentry/lang/javascript/processor.py | 127 | sentry | {
"docstring": "\n Get function name for a given frame based on the token resolved by symbolic.\n It tries following paths in order:\n - return token function name if we have a usable value (filtered through `USELESS_FN_NAMES` list),\n - return mapped name of the caller (previous frame) token if it had,\n... | 109 | Python | 74 | a00ada51c238564b48412cd59f261b84492b96a5 | processor.py | 87,555 | 12 | 72 | get_function_for_token | https://github.com/getsentry/sentry.git | ref(processor): Try to fallback to previous frames token function name (#40602)
This change applies the same heuristic that we previously used in the
original `JavaScriptStacktraceProcessor`.
The rest is described in `get_function_for_token` function comment. | 195 | 0 | 18,314 | 15 | |
1 | 13 | def _expand_to_beam_size(self, x):
r
check_type(x, 'x', (Variable), 'BeamSearchDecoder._expand_to_beam_size')
x = nn.unsqueeze(x, [1])
expand_times = [1] * len(x.shape)
expand_times[1] = self.beam_size
x = paddle.tile(x, expand_times)
return x
| modules/image/text_to_image/disco_diffusion_ernievil_base/vit_b_16x/ernievil2/transformers/beam.py | 102 | PaddleHub | {
"docstring": "\n This function takes a tensor t shaped `[batch_size, s0, s1, ...]` composed\n of minibatch entries `t[0], ..., t[batch_size - 1]` and tiles it to have a\n shape `[batch_size, beam_size, s0, s1, ...]` composed of minibatch entries\n `t[0], t[0], ..., t[1], t[1], ...` where... | 26 | Python | 21 | ffcde21305c61d950a9f93e57e6180c9a9665b87 | beam.py | 50,182 | 22 | 65 | _expand_to_beam_size | https://github.com/PaddlePaddle/PaddleHub.git | add disco_diffusion_ernievil_base | 74 | 0 | 10,040 | 10 | |
3 | 11 | def get_object_id(cls, **data):
object_id, ext_ref = data.get("id"), data.get("external_reference")
validate_one_of_args_is_in_mutation(
CoreErrorCode, "id", object_id, "external_reference", ext_ref
)
if ext_ref and not object_id:
object_id = ext_ref_to_... | saleor/graphql/core/mutations.py | 98 | saleor | {
"docstring": "Resolve object id by given id or external reference.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | 26 | Python | 21 | db7e91a3e124b0df2c08d373a541d9a225ebcb05 | mutations.py | 29,997 | 8 | 58 | get_object_id | https://github.com/saleor/saleor.git | Allow external references to be used instead of Saleor-assigned IDs (#11410)
* Add external_reference to Product model; handle product query, update and delete by external_reference; cover changes with tests
Handle ProductVariant
Handle Order
Handle Attribute
Handle Warehouse query only
Refactor resolve... | 90 | 0 | 5,272 | 12 | |
1 | 21 | def test_mod_gen_f77(capfd, hello_world_f90, monkeypatch):
MNAME = "hi"
foutl = get_io_paths(hello_world_f90, mname=MNAME)
ipath = foutl.f90inp
monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME}'.split())
with util.switchdir(ipath.parent):
f2pycli()
# Always generate C modu... | numpy/f2py/tests/test_f2py2e.py | 134 | numpy | {
"docstring": "Checks the generation of files based on a module name\n CLI :: -m\n ",
"language": "en",
"n_whitespaces": 19,
"n_words": 13,
"vocab_size": 13
} | 41 | Python | 37 | 729ad4f92420231e2a7009b3223c6c7620b8b808 | test_f2py2e.py | 160,160 | 9 | 74 | test_mod_gen_f77 | https://github.com/numpy/numpy.git | TST: Initialize f2py2e tests of the F2PY CLI (#20668)
Increases F2PY coverage by around 15 percent. For the CLI itself it covers the major features (around 70 percent), with the exception of mostly numpy.distutils stuff.
More importantly, sets the groundwork for #20056, in that passing the same testsuite should ind... | 78 | 0 | 38,532 | 11 | |
1 | 4 | def average(inputs, **kwargs):
return Average(**kwargs)(inputs)
| keras/layers/merging/average.py | 32 | keras | {
"docstring": "Functional interface to the `tf.keras.layers.Average` layer.\n\n Example:\n\n >>> x1 = np.ones((2, 2))\n >>> x2 = np.zeros((2, 2))\n >>> y = tf.keras.layers.Average()([x1, x2])\n >>> y.numpy().tolist()\n [[0.5, 0.5], [0.5, 0.5]]\n\n Usage in a functional model:\n\n >>> input1 =... | 5 | Python | 5 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | average.py | 272,643 | 2 | 18 | average | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 11 | 0 | 81,029 | 9 | |
3 | 29 | def get_data(filters):
conditions = get_conditions(filters)
data = frappe.db.sql(
% conditions,
as_dict=1,
)
unit = {
"Bag": "BAGS",
"Bottle": "BOTTLES",
"Kg": "KILOGRAMS",
"Liter": "LITERS",
"Meter": "METERS",
"Nos": "NUMBERS",
"PKT": "PACKS",
"Roll": "ROLLS",
"Set": "SETS",
}
# Regu... | erpnext/regional/report/eway_bill/eway_bill.py | 423 | erpnext | {
"docstring": "\n\t\tSELECT\n\t\t\tdn.name as dn_id, dn.posting_date, dn.company, dn.company_gstin, dn.customer, dn.customer_gstin, dni.item_code, dni.item_name, dni.description, dni.gst_hsn_code, dni.uom, dni.qty, dni.amount, dn.mode_of_transport, dn.distance, dn.transporter_name, dn.gst_transporter_id, dn.lr_no, d... | 117 | Python | 98 | 494bd9ef78313436f0424b918f200dab8fc7c20b | eway_bill.py | 67,202 | 39 | 235 | get_data | https://github.com/frappe/erpnext.git | style: format code with black | 83 | 0 | 14,440 | 18 | |
5 | 32 | def _get_credentials_and_project_id(self) -> Tuple[google.auth.credentials.Credentials, Optional[str]]:
if self._cached_credentials is not None:
return self._cached_credentials, self._cached_project_id
key_path: Optional[str] = self._get_field('key_path', None)
try:
... | airflow/providers/google/common/hooks/base_google.py | 337 | airflow | {
"docstring": "Returns the Credentials object for Google API and the associated project_id",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 10
} | 84 | Python | 56 | 55fd02a38919526776cfe69d715873da75d6f26f | base_google.py | 42,898 | 31 | 217 | _get_credentials_and_project_id | https://github.com/apache/airflow.git | Add key_secret_project_id parameter which specifies a project with KeyFile (#23930) | 358 | 0 | 7,759 | 12 | |
4 | 15 | def connect(self):
if hasattr(self, "_connecting_future") and not self._connecting_future.done():
future = self._connecting_future
else:
future = salt.ext.tornado.concurrent.Future()
self._connecting_future = future
self.io_loop.add_callback(self.... | salt/transport/tcp.py | 112 | salt | {
"docstring": "\n Ask for this client to reconnect to the origin\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 8
} | 35 | Python | 26 | 43277294a3454e5dcd9079e005f747bf880801f6 | tcp.py | 215,590 | 11 | 76 | connect | https://github.com/saltstack/salt.git | Test fix | 122 | 0 | 54,043 | 14 | |
1 | 13 | def test_state_changes_on_tab_change(backforward_widget, tabs, fake_web_tab):
tab_with_history = fake_web_tab(can_go_back=True, can_go_forward=True)
tab_without_history = fake_web_tab(can_go_back=False, can_go_forward=False)
tabs.widget.tabs = [tab_with_history]
backforward_widget.enabled = True
... | tests/unit/mainwindow/statusbar/test_backforward.py | 146 | qutebrowser | {
"docstring": "Test we go invisible when switching to a tab without history.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 32 | Python | 23 | 79bb6670d8969b850965cd5d895bcd8f09d59311 | test_backforward.py | 321,887 | 11 | 90 | test_state_changes_on_tab_change | https://github.com/qutebrowser/qutebrowser.git | bar: Test enabled attribute on progress and backforward
There is now some code in statusbar relying on the enabled attribute
stopping events from being processed (or at least stopping them from
showing the widget again). So add tests to make sure that behaviour
keeps working.
Also split the big test in test_backforwa... | 65 | 0 | 117,965 | 9 | |
2 | 7 | def execute():
if frappe.db.exists("DocType", "Lost Reason Detail"):
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason")
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason_detail")
frappe.reload_doc("setup", "doctype", "quotation_lost_reason_detail")
frappe.db.sql(
)
frappe.db.sq... | erpnext/patches/v12_0/rename_lost_reason_detail.py | 151 | erpnext | {
"docstring": "INSERT INTO `tabOpportunity Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Opportunity'INSERT INTO `tabQuotation Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Quotation'INSERT INTO `tabQuotation Lost Reason` (`name`, `creation`, `modif... | 26 | Python | 17 | 494bd9ef78313436f0424b918f200dab8fc7c20b | rename_lost_reason_detail.py | 66,651 | 17 | 78 | execute | https://github.com/frappe/erpnext.git | style: format code with black | 14 | 0 | 14,272 | 10 | |
1 | 3 | async def _async_run_connected_events(self) -> None:
await self._async_connect_ble_scanner()
| homeassistant/components/shelly/coordinator.py | 28 | core | {
"docstring": "Run connected events.\n\n This will be executed on connect or when the config entry\n is updated.\n ",
"language": "en",
"n_whitespaces": 37,
"n_words": 16,
"vocab_size": 16
} | 7 | Python | 7 | 435fc237375b86a5d6d8498ba5216c208b665ecc | coordinator.py | 290,641 | 7 | 14 | _async_run_connected_events | https://github.com/home-assistant/core.git | Add shelly ble scanner support (#82007) | 21 | 0 | 89,755 | 8 | |
1 | 9 | def _tf_tensor_numpy_output(self, string):
modified_string = self._NUMPY_OUTPUT_RE.sub(r"\1", string)
return modified_string, modified_string != string
MESSAGE = textwrap.dedent(
)
| keras/testing_infra/keras_doctest_lib.py | 56 | keras | {
"docstring": "\\n\n #############################################################\n Check the documentation (go/testable-docstrings) on how to\n write testable docstrings.\n #############################################################",
"language": "en",
"n_whitespaces": 40,
"n_wo... | 16 | Python | 14 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras_doctest_lib.py | 276,314 | 3 | 26 | _tf_tensor_numpy_output | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 43 | 0 | 81,627 | 9 | |
1 | 2 | def cli():
@cli.command() | scripts-dev/release.py | 23 | @cli.command() | synapse | {
"docstring": "An interactive script to walk through the parts of creating a release.\n\n Requires the dev dependencies be installed, which can be done via:\n\n pip install -e .[dev]\n\n Then to use:\n\n ./scripts-dev/release.py prepare\n\n # ... ask others to look at the changelog ...\n\n... | 3 | Python | 3 | 12d1f82db213603972d60be3f46f6a36c3c2330f | release.py | 247,752 | 1 | 5 | cli | https://github.com/matrix-org/synapse.git | Generate announcement links in release script (#12242) | 5 | 1 | 71,897 | 6 |
1 | 8 | def check_for_new_doc_with_same_name_as_deleted_parent(doc):
parent_creation_time = frappe.db.get_value(doc["parenttype"], doc["parent"], "creation")
child_creation_time = doc["creation"]
return getdate(parent_creation_time) > getdate(child_creation_time)
| erpnext/patches/v13_0/delete_orphaned_tables.py | 74 | erpnext | {
"docstring": "\n\tCompares creation times of parent and child docs.\n\tSince Transaction Deletion Record resets the naming series after deletion,\n\tit allows the creation of new docs with the same names as the deleted ones.\n\t",
"language": "en",
"n_whitespaces": 30,
"n_words": 33,
"vocab_size": 28
} | 14 | Python | 13 | 494bd9ef78313436f0424b918f200dab8fc7c20b | delete_orphaned_tables.py | 66,743 | 4 | 42 | check_for_new_doc_with_same_name_as_deleted_parent | https://github.com/frappe/erpnext.git | style: format code with black | 10 | 0 | 14,315 | 10 | |
1 | 7 | def set_capstyle(self, s):
cs = CapStyle(s)
self._capstyle = cs
self.stale = True
| lib/matplotlib/patches.py | 41 | matplotlib | {
"docstring": "\n Set the `.CapStyle`.\n\n The default capstyle is 'round' for `.FancyArrowPatch` and 'butt' for\n all other patches.\n\n Parameters\n ----------\n s : `.CapStyle` or %(CapStyle)s\n ",
"language": "en",
"n_whitespaces": 73,
"n_words": 23,
"voca... | 12 | Python | 9 | b24acb7772e0534f4bcdb0b5b492d9d94954dd91 | patches.py | 107,201 | 4 | 24 | set_capstyle | https://github.com/matplotlib/matplotlib.git | DOC: Document default cap styles
- remove '(default)' from cap style demo as this is only true for Line2D
and the default rcParameters
- document default cap styles for Line2D and Patch in their cap style
setters
- document default cap style for GraphicsContextBase in the same way as
it's already done for joinst... | 40 | 0 | 22,641 | 8 | |
1 | 9 | def mode(self, axis=0, numeric_only=False, dropna=True): # noqa: PR01, RT01, D200
axis = self._get_axis_number(axis)
return self.__constructor__(
query_compiler=self._query_compiler.mode(
axis=axis, numeric_only=numeric_only, dropna=dropna
)
)
| modin/pandas/base.py | 80 | modin | {
"docstring": "\n Get the mode(s) of each element along the selected axis.\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 9
} | 21 | Python | 20 | 605efa618e7994681f57b11d04d417f353ef8d50 | base.py | 153,576 | 7 | 52 | mode | https://github.com/modin-project/modin.git | DOCS-#3099: Fix `BasePandasDataSet` docstrings warnings (#4333)
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: Alexander Myskov <alexander.myskov@intel.com> | 87 | 0 | 35,457 | 11 | |
1 | 3 | def read_text(self, filename):
| python3.10.4/Lib/importlib/metadata/__init__.py | 15 | XX-Net | {
"docstring": "Attempt to load metadata file given by the name.\n\n :param filename: The name of the file in the distribution info.\n :return: The text if found, otherwise None.\n ",
"language": "en",
"n_whitespaces": 48,
"n_words": 27,
"vocab_size": 23
} | 3 | Python | 3 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | __init__.py | 218,296 | 1 | 8 | read_text | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 10 | 0 | 55,244 | 6 | |
1 | 14 | async def test_load_types(hass, create_hdmi_network, create_cec_entity):
config = {"platform": "media_player", "types": {"hdmi_cec.hdmi_3": "switch"}}
hdmi_network = await create_hdmi_network(config=config)
mock_hdmi_device = MockHDMIDevice(logical_address=3)
await create_cec_entity(hdmi_network, m... | tests/components/hdmi_cec/test_switch.py | 235 | core | {
"docstring": "Test that switch entity is loaded when types is set.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | 60 | Python | 30 | 7cd4be1310b3f76398b4404d3f4ecb26b9533cee | test_switch.py | 303,600 | 17 | 136 | test_load_types | https://github.com/home-assistant/core.git | Add tests for the HDMI-CEC integration (#75094)
* Add basic tests to the HDMI-CEC component
* Add tests for the HDMI-CEC switch component
* Add test for watchdog code
* Start adding tests for the HDMI-CEC media player platform
Also some cleanup and code move.
* Add more tests for media_player
And cle... | 111 | 0 | 102,418 | 11 | |
1 | 73 | def track_tf1_style_variables(method):
| keras/legacy_tf_layers/variable_scope_shim.py | 244 | """Wrapmodulethis decorator to capturestyle weights.
Decorating a `tf.keras.Layer`'s or `tf.Module`'s methods withwill cause the layermodule to track weightsviaand by extensioninside the decorated method.
In addition to tracking the weights themselves under theif the methodto a `tf.keras.Layer` then any regu... | keras | {
"docstring": "Wrap layer & module methods in this decorator to capture tf1-style weights.\n\n Decorating a `tf.keras.Layer`'s or `tf.Module`'s methods with this\n decorator will cause the layer/module to track weights created/used\n via `tf.compat.v1.get_variable` (and by extension `tf.compat.v1.layers`)\... | 2 | Python | 2 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | variable_scope_shim.py | 274,464 | 5 | 25 | track_tf1_style_variables | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 5 | 20 | 81,205 | 12 |
1 | 3 | def warning(self, response):
return '110 - "Response is Stale"'
| .venv/lib/python3.8/site-packages/pip/_vendor/cachecontrol/heuristics.py | 20 | transferlearning | {
"docstring": "\n Return a valid 1xx warning header value describing the cache\n adjustments.\n\n The response is provided too allow warnings like 113\n http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need\n to explicitly say response is over 24 hours old.\n ",
"... | 9 | Python | 9 | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | heuristics.py | 61,500 | 2 | 10 | warning | https://github.com/jindongwang/transferlearning.git | upd; format | 23 | 0 | 12,595 | 6 | |
2 | 26 | def debug_launcher(function, args=(), num_processes=2):
if is_torch_version("<", "1.5.0"):
raise ImportError(
"Using `debug_launcher` for distributed training on GPUs require torch >= 1.5.0, got "
f"{torch.__version__}."
)
from torch.multiprocessing import start_pro... | src/accelerate/launchers.py | 182 | accelerate | {
"docstring": "\n Launches a training function using several processes on CPU for debugging purposes.\n\n <Tip warning={true}>\n\n This function is provided for internal testing and debugging, but it's not intended for real trainings. It will\n only use the CPU.\n\n </Tip>\n\n Args:\n functi... | 79 | Python | 70 | f6ec2660f01e5bb37399407b3a01b72a43ceb328 | launchers.py | 337,603 | 36 | 102 | debug_launcher | https://github.com/huggingface/accelerate.git | Refactor version checking into a utility (#395)
Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com> | 243 | 0 | 121,089 | 13 | |
7 | 25 | def _autodetect_num_gpus():
result = 0
if importlib.util.find_spec("GPUtil"):
gpu_list = GPUtil.getGPUs()
result = len(gpu_list)
elif sys.platform.startswith("linux"):
proc_gpus_path = "/proc/driver/nvidia/gpus"
if os.path.isdir(proc_gpus_path):
result = len(... | python/ray/_private/resource_spec.py | 227 | ray | {
"docstring": "Attempt to detect the number of GPUs on this machine.\n\n TODO(rkn): Only detects NVidia GPUs (except when using WMIC on windows)\n\n Returns:\n The number of GPUs if any were detected, otherwise 0.\n ",
"language": "en",
"n_whitespaces": 48,
"n_words": 32,
"vocab_size": 27
} | 51 | Python | 35 | b87731c1b64988cea5ce80a6aec55207ef7efd6f | resource_spec.py | 125,305 | 15 | 130 | _autodetect_num_gpus | https://github.com/ray-project/ray.git | Windows gpu detection workaround with GPUtil (#25701)
Because [WMIC is now deprecated](https://docs.microsoft.com/en-us/windows/deployment/planning/windows-10-deprecated-features), #9300 may stop working on recent Windows systems. As a workaround this PR extends GPUtil to do GPU detection when installed on Windows sys... | 136 | 0 | 27,830 | 16 | |
3 | 16 | def apply_valid_mask(losses, sw, mask, reduction):
if mask is not None:
mask = tf.cast(mask, losses.dtype)
if reduction in (ReductionV2.AUTO, ReductionV2.SUM_OVER_BATCH_SIZE):
# Valid entries have weight `total/valid`, while invalid ones
# have 0. When summed over batch... | keras/utils/losses_utils.py | 131 | keras | {
"docstring": "Redistribute sample weights considering only valid entries.",
"language": "en",
"n_whitespaces": 6,
"n_words": 7,
"vocab_size": 7
} | 94 | Python | 51 | 4f1308112f4188c4e14fdf3a59af8fe5f30db61f | losses_utils.py | 279,206 | 8 | 83 | apply_valid_mask | https://github.com/keras-team/keras.git | Update docs | 233 | 0 | 82,878 | 14 | |
1 | 5 | def modified_vars(self) -> Dict[str, "tk.BooleanVar"]:
assert self.command_notebook is not None
return self.command_notebook.modified_vars
| lib/gui/utils.py | 43 | faceswap | {
"docstring": " dict: The command notebook modified tkinter variables. ",
"language": "en",
"n_whitespaces": 8,
"n_words": 7,
"vocab_size": 7
} | 12 | Python | 12 | dc18c74eea0c7837a820d27628cb12b0824fa30e | utils.py | 101,524 | 4 | 26 | modified_vars | https://github.com/deepfakes/faceswap.git | Bugfix: Preview for extract in batch mode | 33 | 0 | 20,935 | 7 | |
4 | 9 | def _is_zero_copy_possible(self) -> bool:
if self.__is_zero_copy_possible is None:
if self._df._has_arrow_table():
# If PyArrow table is already materialized then we can
# retrieve data zero-copy
self.__is_zero_copy_possible = True
... | modin/experimental/core/execution/native/implementations/omnisci_on_native/exchange/dataframe_protocol/dataframe.py | 112 | modin | {
"docstring": "\n Check whether it's possible to retrieve data from the DataFrame zero-copy.\n\n The 'zero-copy' term also means that no extra computations or data transers\n are needed to access the data.\n\n Returns\n -------\n bool\n ",
"language": "en",
"n_whi... | 71 | Python | 50 | 0c1a2129df64cf45bf1ff49c8ed92c510fdb1c82 | dataframe.py | 153,666 | 19 | 64 | _is_zero_copy_possible | https://github.com/modin-project/modin.git | FEAT-#4244: Implement dataframe exchange protocol for OmniSci (#4269)
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Co-authored-by: Vasily Litvinov <vasilij.n.litvinov@intel.com>
Signed-off-by: Dmitry Chigarev <dmitry.chigarev@intel.com> | 245 | 0 | 35,528 | 15 | |
6 | 43 | def test_loss_of_perfect_prediction(loss, sample_weight):
if not loss.is_multiclass:
# Use small values such that exp(value) is not nan.
raw_prediction = np.array([-10, -0.1, 0, 0.1, 3, 10])
# If link is identity, we must respect the interval of y_pred:
if isinstance(loss.link, ... | sklearn/_loss/tests/test_loss.py | 446 | @pytest.mark.parametrize("loss", LOSS_INSTANCES, ids=loss_instance_name)
@pytest.mark.parametrize("sample_weight", [None, "range"]) | scikit-learn | {
"docstring": "Test value of perfect predictions.\n\n Loss of y_pred = y_true plus constant_to_optimal_zero should sums up to\n zero.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 17,
"vocab_size": 16
} | 159 | Python | 110 | 75a94f518f7bd7d0bf581ffb67d9f961e3c4efbc | test_loss.py | 259,435 | 32 | 266 | test_loss_of_perfect_prediction | https://github.com/scikit-learn/scikit-learn.git | ENH migrate GLMs / TweedieRegressor to linear loss (#22548)
Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org>
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> | 438 | 1 | 75,769 | 15 |
1 | 3 | def head_bundle_is_empty(self):
return self._head_bundle_is_empty
| python/ray/air/execution/resources/request.py | 19 | ray | {
"docstring": "Returns True if head bundle is empty while child bundles\n need resources.\n\n This is considered an internal API within Tune.\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 20,
"vocab_size": 19
} | 4 | Python | 4 | edb17fd2069844f12237c85ba6607afae536401d | request.py | 138,036 | 2 | 10 | head_bundle_is_empty | https://github.com/ray-project/ray.git | [air/tune] Internal resource management 1 - Ray AIR resource manager implementation (#30777)
Prerequisite to #30016
This PR adds a new Ray AIR resource manager to replace the PlacementGroupManager of Ray Tune. Details can be found in #30016.
Specifically, this PR
- Adds the main resource manager abstractions
-... | 18 | 0 | 31,282 | 6 | |
1 | 3 | def _transform_unaggregated_gradients(self, grads_and_vars):
return grads_and_vars
| keras/optimizers/optimizer_v2/optimizer_v2.py | 18 | keras | {
"docstring": "Called in `apply_gradients` before gradient aggregation.",
"language": "en",
"n_whitespaces": 5,
"n_words": 6,
"vocab_size": 6
} | 5 | Python | 5 | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | optimizer_v2.py | 275,502 | 2 | 10 | _transform_unaggregated_gradients | https://github.com/keras-team/keras.git | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 19 | 0 | 81,400 | 6 | |
1 | 4 | def execute():
frappe.db.sql(
)
| erpnext/patches/v12_0/set_quotation_status.py | 23 | erpnext | {
"docstring": " UPDATE `tabQuotation` set status = 'Open'\n\t\twhere docstatus = 1 and status = 'Submitted' ",
"language": "en",
"n_whitespaces": 14,
"n_words": 14,
"vocab_size": 11
} | 4 | Python | 4 | 494bd9ef78313436f0424b918f200dab8fc7c20b | set_quotation_status.py | 66,677 | 5 | 12 | execute | https://github.com/frappe/erpnext.git | style: format code with black | 1 | 0 | 14,287 | 8 | |
5 | 15 | def temporary_settings(**kwargs):
old_env = os.environ.copy()
old_settings = prefect.settings.from_env()
try:
for setting in kwargs:
os.environ[setting] = str(kwargs[setting])
assert old_env != os.environ, "Environment did not change"
new_settings = prefect.setting... | src/prefect/utilities/testing.py | 178 | prefect | {
"docstring": "\n Temporarily override setting values. \n \n This will _not_ mutate values that have been already been accessed at module\n load time.\n\n This function should only be used for testing.\n\n Example:\n >>> import prefect.settings\n >>> with temporary_settings(PREFECT_OR... | 52 | Python | 35 | 1d4218a287ef343f32f1e32482592b471be5df1d | testing.py | 53,411 | 16 | 109 | temporary_settings | https://github.com/PrefectHQ/prefect.git | Move `prefect.settings` to `prefect.settings.from_env()` | 172 | 0 | 10,795 | 16 | |
14 | 55 | def parse_semver(version, operator) -> Optional[SemverFilter]:
(operator, negated) = handle_operator_negation(operator)
try:
operator = OPERATOR_TO_DJANGO[operator]
except KeyError:
raise InvalidSearchQuery("Invalid operation 'IN' for semantic version filter.")
version = version if... | src/sentry/search/events/filter.py | 498 | sentry | {
"docstring": "\n Attempts to parse a release version using our semver syntax. version should be in\n format `<package_name>@<version>` or `<version>`, where package_name is a string and\n version is a version string matching semver format (https://semver.org/). We've\n slightly extended this format to a... | 191 | Python | 132 | 4ffb52489e662029a08169351cd997d525977e88 | filter.py | 98,450 | 50 | 224 | parse_semver | https://github.com/getsentry/sentry.git | fix(events-search): Return helpful error message on semver filter (#33785)
'IN' type queries currently raise an unhandled KeyError, raising an
InvalidSearchQuery instead. | 651 | 0 | 19,571 | 18 | |
5 | 2 | def test_schedules_with_save_and_resume(self):
| tests/training/learning_rate_schedulers/cosine_test.py | 13 | allennlp | {
"docstring": "Make sure scheduler will resume with the right state.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | 2 | Python | 2 | 39b3c96181ab9f33a44b4fe591b348b5b48ecf76 | cosine_test.py | 280,865 | 15 | 130 | test_schedules_with_save_and_resume | https://github.com/allenai/allennlp.git | Dependabot GitHub Actions (#5640)
* chore: Included githubactions in the dependabot config
This should help with keeping the GitHub actions updated on new releases. This will also help with keeping it secure.
Dependabot helps in keeping the supply chain secure https://docs.github.com/en/code-security/dependabot
... | 9 | 0 | 83,445 | 6 | |
3 | 14 | def to_bytes(self, *, exclude=tuple()):
self._validate_serialization_attrs()
serialize = {}
if hasattr(self, "cfg") and self.cfg is not None:
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
serialize["vocab"] = lambda: self.vocab.to_bytes(exclude=exclude)
... | spacy/pipeline/legacy/entity_linker.py | 165 | spaCy | {
"docstring": "Serialize the pipe to a bytestring.\n\n exclude (Iterable[str]): String names of serialization fields to exclude.\n RETURNS (bytes): The serialized object.\n\n DOCS: https://spacy.io/api/entitylinker#to_bytes\n ",
"language": "en",
"n_whitespaces": 50,
"n_words": 22,
... | 33 | Python | 28 | 91acc3ea75d219ad07ed2b106e7b8bdcb01516dd | entity_linker.py | 111,232 | 16 | 99 | to_bytes | https://github.com/explosion/spaCy.git | Fix entity linker batching (#9669)
* Partial fix of entity linker batching
* Add import
* Better name
* Add `use_gold_ents` option, docs
* Change to v2, create stub v1, update docs etc.
* Fix error type
Honestly no idea what the right type to use here is.
ConfigValidationError seems wrong. Maybe a N... | 100 | 0 | 24,362 | 12 | |
1 | 15 | def test_importable_project_name(self):
bad_name = "os"
args = ["startproject", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"CommandError: 'os' conflicts with th... | tests/admin_scripts/tests.py | 112 | django | {
"docstring": "\n startproject validates that project name doesn't clash with existing\n Python modules.\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 11,
"vocab_size": 11
} | 46 | Python | 42 | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | tests.py | 207,316 | 12 | 64 | test_importable_project_name | https://github.com/django/django.git | Refs #33476 -- Reformatted code with Black. | 146 | 0 | 51,927 | 10 | |
2 | 12 | async def _cancel_and_wait(fut, loop):
waiter = loop.create_future()
cb = functools.partial(_release_waiter, waiter)
fut.add_done_callback(cb)
try:
fut.cancel()
# We cannot wait on *fut* directly to make
# sure _cancel_and_wait itself is reliably cancellable.
await... | python3.10.4/Lib/asyncio/tasks.py | 87 | XX-Net | {
"docstring": "Cancel the *fut* future or task and wait until it completes.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | 47 | Python | 41 | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | tasks.py | 220,813 | 9 | 48 | _cancel_and_wait | https://github.com/XX-net/XX-Net.git | add python 3.10.4 for windows | 100 | 0 | 56,126 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.