in_source_id
stringlengths
13
58
issue
stringlengths
3
241k
before_files
listlengths
0
3
after_files
listlengths
0
3
pr_diff
stringlengths
109
107M
ansible__ansible-32912
packet_device not working with ipxe_script_url set ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME modules/cloud/packet ##### ANSIBLE VERSION ``` ansible 2.4.1.0 config file = /home/krist/.ansible.cfg configured module search path = [u'/home/krist/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = bin/ansible python version = 2.7.14 (default, Nov 2 2017, 18:42:05) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] ``` ##### CONFIGURATION ``` ANSIBLE_PIPELINING(/home/krist/Work/LAB/pakket/ansible.cfg) = True DEFAULT_HOST_LIST(/home/krist/Work/LAB/pakket/ansible.cfg) = [u'/home/krist/Work/LAB/pakket/inventory'] DEFAULT_ROLES_PATH(/home/krist/Work/LAB/pakket/ansible.cfg) = [u'/home/krist/Work/LAB/pakket/roles'] DEFAULT_VAULT_PASSWORD_FILE(/home/krist/Work/LAB/pakket/ansible.cfg) = /home/krist/.ansible/password ``` ##### OS / ENVIRONMENT Fedora 26, Ansible from git devel branch. ##### SUMMARY packet_device: Creating a packet host with ipxeboot does not work. ##### STEPS TO REPRODUCE Install the packet.net CLI tools. Create a group_vars/all/main.yaml with correct values for location, api key and project id. Try to provision a host with a playbook: ```yaml - name: create rhev lab hosts: localhost tasks: - packet_sshkey: key_file: "{{ lookup('env','HOME') + '/.ssh/id_rsa.pub' }}" label: default key - packet_device: project_id: "{{ project_id }}" hostnames: "{{ item }}" operating_system: custom_ipxe ipxe_script_url: http://boot.example.com/rhvh/boot.ipxe plan: baremetal_0 facility: "{{ location }}" auth_token: "{{ api_key }}" with_items: - rhvh1 ``` ##### EXPECTED RESULTS Host is provisioned and attempts a ipxe boot with the URL provided. ##### ACTUAL RESULTS ``` task path: /home/krist/Work/LAB/pakket/create_rhvh_lab.yaml:9 Using module file /usr/lib/python2.7/site-packages/ansible/modules/cloud/packet/packet_device.py <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: krist <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python && sleep 0' failed: [localhost] (item=rhvh1) => { "changed": false, "failed": true, "invocation": { "module_args": { "auth_token": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "facility": "ams1", "hostnames": "rhvh1", "ipxe_script_url": "http://boot.example.com/rhvh/boot.ipxe", "operating_system": "custom_ipxe", "plan": "baremetal_0", "project_id": "be6b7156-3c89-447c-b46e-ee376809a3d2" } }, "item": "rhvh1", "msg": "parameters are mutually exclusive: ('ipxe_script_url', 'operating_system')" ``` I assumed that this just meant that I should not define operating_system when ipxe_script_url is set. So I also tested with a playbook where I had removed the operating_system parameter. There the result was: ``` task path: /home/krist/Work/LAB/pakket/create_rhvh_lab.yaml:9 Using module file /usr/lib/python2.7/site-packages/ansible/modules/cloud/packet/packet_device.py <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: krist <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python && sleep 0' The full traceback is: Traceback (most recent call last): File "/tmp/ansible_qyWyXe/ansible_module_packet_device.py", line 640, in main module.exit_json(**act_on_devices(module, packet_conn, state)) File "/tmp/ansible_qyWyXe/ansible_module_packet_device.py", line 575, in act_on_devices for n in create_hostnames] File "/tmp/ansible_qyWyXe/ansible_module_packet_device.py", line 445, in create_single_device % param) Exception: operating_system parameter is required for new device. failed: [localhost] (item=rhvh1) => { "changed": false, "failed": true, "invocation": { "module_args": { "always_pxe": false, "auth_token": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "count": 1, "count_offset": 1, "device_ids": null, "facility": "ams1", "features": null, "hostnames": [ "rhvh1" ], "ipxe_script_url": "http://home.kri.st/rhvh/boot.ipxe", "locked": false, "operating_system": null, "plan": "baremetal_0", "project_id": "be6b7156-3c89-447c-b46e-ee376809a3d2", "state": "present", "user_data": null, "wait_for_public_IPv": null, "wait_timeout": 900 } }, "item": "rhvh1", "msg": "failed to set device state present, error: operating_system parameter is required for new device." } ``` I think that packet_device should either allow both operating_system and ipxe_script_url to be set, or otherwise just automatically set operating_system to custom_ipxe when ipxe_script_url is set. Fix Packet guide to comply with latest version of the packet module ##### SUMMARY This PR fixes the Packet Guide doc to follow the latest merged changes in the packet_device module. ##### ISSUE TYPE - Docs Pull Request ##### COMPONENT NAME docs/docsite/rst/guide_packet.rst ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes below --> ``` ansible 2.5.0 (fix-packet-guide-to-comply-with-latest-device-module acdda6f020) last updated 2017/10/06 15:03:35 (GMT +300) config file = None configured module search path = [u'/home/tomk/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /home/tomk/ansible/lib/ansible executable location = /home/tomk/ansible/bin/ansible python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] ```
[ { "content": "#!/usr/bin/python\n# (c) 2016, Tomas Karasek <tom.to.the.k@gmail.com>\n# (c) 2016, Matt Baldwin <baldwin@stackpointcloud.com>\n# (c) 2016, Thibaud Morel l'Horset <teebes@gmail.com>\n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ i...
[ { "content": "#!/usr/bin/python\n# (c) 2016, Tomas Karasek <tom.to.the.k@gmail.com>\n# (c) 2016, Matt Baldwin <baldwin@stackpointcloud.com>\n# (c) 2016, Thibaud Morel l'Horset <teebes@gmail.com>\n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ i...
diff --git a/lib/ansible/modules/cloud/packet/packet_device.py b/lib/ansible/modules/cloud/packet/packet_device.py index b2879cb04a2c49..3ae8065e42e26b 100644 --- a/lib/ansible/modules/cloud/packet/packet_device.py +++ b/lib/ansible/modules/cloud/packet/packet_device.py @@ -458,7 +458,9 @@ def create_single_device(module, packet_conn, hostname): facility=facility, operating_system=operating_system, userdata=user_data, - locked=locked) + locked=locked, + ipxe_script_url=ipxe_script_url, + always_pxe=always_pxe) return device
open-telemetry__opentelemetry-python-1813
OpenTelemetry distro as a default distro for OpenTelemetry Instrumentation The `opentelemetry-instrumentation` auto instrumentation doesn't work without installing `opentelemetry-distro` as the components initialisation is done in distro package. How does a regular user know about this and shouldn't openetemetry distro be the default and can give an option to let user use others?
[ { "content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by...
[ { "content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by...
diff --git a/docs/examples/auto-instrumentation/README.rst b/docs/examples/auto-instrumentation/README.rst index 9298c9bef2f..23fb47b3964 100644 --- a/docs/examples/auto-instrumentation/README.rst +++ b/docs/examples/auto-instrumentation/README.rst @@ -45,7 +45,7 @@ Manually instrumented server return "served" Server not instrumented manually -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``server_uninstrumented.py`` @@ -57,7 +57,7 @@ Server not instrumented manually return "served" Prepare ------------ +------- Execute the following example in a separate virtual environment. Run the following commands to prepare for auto-instrumentation: @@ -69,7 +69,7 @@ Run the following commands to prepare for auto-instrumentation: $ source auto_instrumentation/bin/activate Install ------------- +------- Run the following commands to install the appropriate packages. The ``opentelemetry-instrumentation`` package provides several @@ -90,7 +90,7 @@ a server as well as the process of executing an automatically instrumented server. Execute a manually instrumented server -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Execute the server in two separate consoles, one to run each of the scripts that make up this example: @@ -145,7 +145,7 @@ similar to the following example: } Execute an automatically instrumented server -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Stop the execution of ``server_instrumented.py`` with ``ctrl + c`` and run the following command instead: @@ -208,7 +208,7 @@ You can see that both outputs are the same because automatic instrumentation doe exactly what manual instrumentation does. Instrumentation while debugging -=============================== +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The debug mode can be enabled in the Flask app like this: @@ -226,3 +226,11 @@ reloader. To run instrumentation while the debug mode is enabled, set the if __name__ == "__main__": app.run(port=8082, debug=True, use_reloader=False) + + +Additional resources +~~~~~~~~~~~~~~~~~~~~ + +In order to send telemetry to an OpenTelemetry Collector without doing any +additional configuration, read about the `OpenTelemetry Distro <../distro/README.html>`_ +package. diff --git a/docs/examples/distro/README.rst b/docs/examples/distro/README.rst new file mode 100644 index 00000000000..f58680609ab --- /dev/null +++ b/docs/examples/distro/README.rst @@ -0,0 +1,104 @@ +OpenTelemetry Distro +==================== + +In order to make using OpenTelemetry and auto-instrumentation as quick as possible without sacrificing flexibility, +OpenTelemetry distros provide a mechanism to automatically configure some of the more common options for users. By +harnessing their power, users of OpenTelemetry can configure the components as they need. The ``opentelemetry-distro`` +package provides some defaults to users looking to get started, it configures: + +- the SDK TracerProvider +- a BatchSpanProcessor +- the OTLP ``SpanExporter`` to send data to an OpenTelemetry collector + +The package also provides a starting point for anyone interested in producing an alternative distro. The +interfaces implemented by the package are loaded by the auto-instrumentation via the ``opentelemetry_distro`` +and ``opentelemetry_configurator`` entry points to configure the application before any other code is +executed. + +In order to automatically export data from OpenTelemetry to the OpenTelemetry collector, installing the +package will setup all the required entry points. + +.. code:: sh + + $ pip install opentelemetry-distro[otlp] opentelemetry-instrumentation + +Start the Collector locally to see data being exported. Write the following file: + +.. code-block:: yaml + + # /tmp/otel-collector-config.yaml + receivers: + otlp: + protocols: + grpc: + http: + exporters: + logging: + loglevel: debug + processors: + batch: + service: + pipelines: + traces: + receivers: [otlp] + exporters: [logging] + processors: [batch] + +Then start the Docker container: + +.. code-block:: sh + + docker run -p 4317:4317 \ + -v /tmp/otel-collector-config.yaml:/etc/otel-collector-config.yaml \ + otel/opentelemetry-collector:latest \ + --config=/etc/otel-collector-config.yaml + +The following code will create a span with no configuration. + +.. code:: python + + # no_configuration.py + from opentelemetry import trace + + with trace.get_tracer(__name__).start_as_current_span("foo"): + with trace.get_tracer(__name__).start_as_current_span("bar"): + print("baz") + +Lastly, run the ``no_configuration.py`` with the auto-instrumentation: + +.. code-block:: sh + + $ opentelemetry-instrument python no_configuration.py + +The resulting span will appear in the output from the collector and look similar to this: + +.. code-block:: sh + + Resource labels: + -> telemetry.sdk.language: STRING(python) + -> telemetry.sdk.name: STRING(opentelemetry) + -> telemetry.sdk.version: STRING(1.1.0) + -> service.name: STRING(unknown_service) + InstrumentationLibrarySpans #0 + InstrumentationLibrary __main__ + Span #0 + Trace ID : db3c99e5bfc50ef8be1773c3765e8845 + Parent ID : 0677126a4d110cb8 + ID : 3163b3022808ed1b + Name : bar + Kind : SPAN_KIND_INTERNAL + Start time : 2021-05-06 22:54:51.23063 +0000 UTC + End time : 2021-05-06 22:54:51.230684 +0000 UTC + Status code : STATUS_CODE_UNSET + Status message : + Span #1 + Trace ID : db3c99e5bfc50ef8be1773c3765e8845 + Parent ID : + ID : 0677126a4d110cb8 + Name : foo + Kind : SPAN_KIND_INTERNAL + Start time : 2021-05-06 22:54:51.230549 +0000 UTC + End time : 2021-05-06 22:54:51.230706 +0000 UTC + Status code : STATUS_CODE_UNSET + Status message : + diff --git a/docs/getting_started/otlpcollector_example.py b/docs/getting_started/otlpcollector_example.py index 48c0d32a594..71f9ed97541 100644 --- a/docs/getting_started/otlpcollector_example.py +++ b/docs/getting_started/otlpcollector_example.py @@ -24,7 +24,7 @@ span_exporter = OTLPSpanExporter( # optional - # endpoint:="myCollectorURL:4317", + # endpoint="myCollectorURL:4317", # credentials=ChannelCredentials(credentials), # headers=(("metadata", "metadata")), ) diff --git a/opentelemetry-distro/README.rst b/opentelemetry-distro/README.rst index 4189131fc26..80952839104 100644 --- a/opentelemetry-distro/README.rst +++ b/opentelemetry-distro/README.rst @@ -14,9 +14,10 @@ Installation pip install opentelemetry-distro -This package provides entrypoints to configure OpenTelemetry +This package provides entrypoints to configure OpenTelemetry. References ---------- * `OpenTelemetry Project <https://opentelemetry.io/>`_ +* `Example using opentelemetry-distro <https://opentelemetry-python.readthedocs.io/en/latest/examples/distro/README.html>`_
translate__translate-3683
setcontext is not working correctly for mounit Calling setcontext on mounit does currently nothing as it inherits code from base class: ``` python def setcontext(self, context): """Set the message context""" pass ``` I'd expect it to properly update context as it does for other storages.
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2007 Zuza Software Foundation\n#\n# the function \"serialize\" was derived from Python v2.4\n# (Tools/i18n/msgfmt.py - function \"generate\"):\n# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>\n# Copyright (c) 2001, 2002, 2003, 2004, 2...
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2007 Zuza Software Foundation\n#\n# the function \"serialize\" was derived from Python v2.4\n# (Tools/i18n/msgfmt.py - function \"generate\"):\n# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>\n# Copyright (c) 2001, 2002, 2003, 2004, 2...
diff --git a/translate/storage/mo.py b/translate/storage/mo.py index ad20515162..2a538fcc72 100644 --- a/translate/storage/mo.py +++ b/translate/storage/mo.py @@ -118,6 +118,9 @@ def getcontext(self): return None return "".join(self.msgctxt) + def setcontext(self, context): + self.msgctxt = [context] + def isheader(self): """Is this a header entry?""" return self.source == u"" diff --git a/translate/storage/test_mo.py b/translate/storage/test_mo.py index 9c14681198..a03911b213 100644 --- a/translate/storage/test_mo.py +++ b/translate/storage/test_mo.py @@ -9,6 +9,11 @@ class TestMOUnit(test_base.TestTranslationUnit): UnitClass = mo.mounit + def test_context(self): + unit = self.UnitClass("Message") + unit.setcontext('context') + assert unit.getcontext() == 'context' + posources = [ r''' @@ -124,6 +129,14 @@ def test_language(self): store.updateheader(add=True, Language="zu") assert store.gettargetlanguage() == "zu" + def test_context(self): + store = self.StoreClass() + unit = self.StoreClass.UnitClass('source') + unit.target = 'target' + unit.setcontext('context') + store.addunit(unit) + assert b'context' in store.__bytes__() + def test_output(self): for posource in posources: print("PO source file")
mit-ll-responsible-ai__hydra-zen-615
Bump actions/upload-artifact from 3 to 4 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/actions/upload-artifact/releases">actions/upload-artifact's releases</a>.</em></p> <blockquote> <h2>v4.0.0</h2> <h2>What's Changed</h2> <p>The release of upload-artifact@v4 and download-artifact@v4 are major changes to the backend architecture of Artifacts. They have numerous performance and behavioral improvements.</p> <p>For more information, see the <a href="https://github.com/actions/toolkit/tree/main/packages/artifact"><code>@​actions/artifact</code></a> documentation.</p> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/vmjoseph"><code>@​vmjoseph</code></a> made their first contribution in <a href="https://redirect.github.com/actions/upload-artifact/pull/464">actions/upload-artifact#464</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/upload-artifact/compare/v3...v4.0.0">https://github.com/actions/upload-artifact/compare/v3...v4.0.0</a></p> <h2>v3.1.3</h2> <h2>What's Changed</h2> <ul> <li>chore(github): remove trailing whitespaces by <a href="https://github.com/ljmf00"><code>@​ljmf00</code></a> in <a href="https://redirect.github.com/actions/upload-artifact/pull/313">actions/upload-artifact#313</a></li> <li>Bump <code>@​actions/artifact</code> version to v1.1.2 by <a href="https://github.com/bethanyj28"><code>@​bethanyj28</code></a> in <a href="https://redirect.github.com/actions/upload-artifact/pull/436">actions/upload-artifact#436</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/upload-artifact/compare/v3...v3.1.3">https://github.com/actions/upload-artifact/compare/v3...v3.1.3</a></p> <h2>v3.1.2</h2> <ul> <li>Update all <code>@actions/*</code> NPM packages to their latest versions- <a href="https://redirect.github.com/actions/upload-artifact/issues/374">#374</a></li> <li>Update all dev dependencies to their most recent versions - <a href="https://redirect.github.com/actions/upload-artifact/issues/375">#375</a></li> </ul> <h2>v3.1.1</h2> <ul> <li>Update actions/core package to latest version to remove <code>set-output</code> deprecation warning <a href="https://redirect.github.com/actions/upload-artifact/issues/351">#351</a></li> </ul> <h2>v3.1.0</h2> <h2>What's Changed</h2> <ul> <li>Bump <code>@​actions/artifact</code> to v1.1.0 (<a href="https://redirect.github.com/actions/upload-artifact/pull/327">actions/upload-artifact#327</a>) <ul> <li>Adds checksum headers on artifact upload (<a href="https://redirect.github.com/actions/toolkit/pull/1095">actions/toolkit#1095</a>) (<a href="https://redirect.github.com/actions/toolkit/pull/1063">actions/toolkit#1063</a>)</li> </ul> </li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/actions/upload-artifact/commit/c7d193f32edcb7bfad88892161225aeda64e9392"><code>c7d193f</code></a> Merge pull request <a href="https://redirect.github.com/actions/upload-artifact/issues/466">#466</a> from actions/v4-beta</li> <li><a href="https://github.com/actions/upload-artifact/commit/13131bb095770b4070a7477c3cd2d96e1c16d9f4"><code>13131bb</code></a> licensed cache</li> <li><a href="https://github.com/actions/upload-artifact/commit/4a6c273b9834f66a1d05c170dc3f80f9cdb9def1"><code>4a6c273</code></a> Merge branch 'main' into v4-beta</li> <li><a href="https://github.com/actions/upload-artifact/commit/f391bb91a3d3118aeca171c365bb319ece276b37"><code>f391bb9</code></a> Merge pull request <a href="https://redirect.github.com/actions/upload-artifact/issues/465">#465</a> from actions/robherley/v4-documentation</li> <li><a href="https://github.com/actions/upload-artifact/commit/9653d03c4b74c32144e02dae644fea70e079d4b3"><code>9653d03</code></a> Apply suggestions from code review</li> <li><a href="https://github.com/actions/upload-artifact/commit/875b63076402f25ef9d52c294c86ba4f97810575"><code>875b630</code></a> add limitations section</li> <li><a href="https://github.com/actions/upload-artifact/commit/ecb21463e93740a6be75c3116242169bfdbcb15a"><code>ecb2146</code></a> add compression example</li> <li><a href="https://github.com/actions/upload-artifact/commit/5e7604f84a055838f64ed68bb9904751523081ae"><code>5e7604f</code></a> trim some repeated info</li> <li><a href="https://github.com/actions/upload-artifact/commit/d6437d07581fe318a364512e6cf6b1dca6b4f92c"><code>d6437d0</code></a> naming</li> <li><a href="https://github.com/actions/upload-artifact/commit/1b561557037b4957d7d184e9aac02bec86c771eb"><code>1b56155</code></a> s/v4-beta/v4/g</li> <li>Additional commits viewable in <a href="https://github.com/actions/upload-artifact/compare/v3...v4">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/upload-artifact&package-manager=github_actions&previous-version=3&new-version=4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
[ { "content": "# Copyright (c) 2023 Massachusetts Institute of Technology\n# SPDX-License-Identifier: MIT\n# pyright: strict\nfrom dataclasses import MISSING\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Any, Type, Union\n\nfrom typing_extensions import TypeGuard\n\nfrom hydra_zen.funcs impor...
[ { "content": "# Copyright (c) 2023 Massachusetts Institute of Technology\n# SPDX-License-Identifier: MIT\n# pyright: strict\nfrom dataclasses import MISSING\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Any, Type, Union\n\nfrom typing_extensions import TypeGuard\n\nfrom hydra_zen.funcs impor...
diff --git a/.github/workflows/pypi_publish.yml b/.github/workflows/pypi_publish.yml index 578201ed8..2c220e552 100644 --- a/.github/workflows/pypi_publish.yml +++ b/.github/workflows/pypi_publish.yml @@ -22,7 +22,7 @@ jobs: pip install build python -m build - name: Upload artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: dist path: dist @@ -36,7 +36,7 @@ jobs: id-token: write # IMPORTANT: this permission is mandatory for trusted publishing steps: - name: Download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: dist path: dist diff --git a/src/hydra_zen/structured_configs/_type_guards.py b/src/hydra_zen/structured_configs/_type_guards.py index b7adb4f9c..6ae1a289f 100644 --- a/src/hydra_zen/structured_configs/_type_guards.py +++ b/src/hydra_zen/structured_configs/_type_guards.py @@ -103,8 +103,7 @@ def is_old_partial_builds(x: Any) -> bool: # pragma: no cover safe_getattr(x, "_partial_target_") ): return True - else: - # ensures we cover this branch in tests + else: # pragma: no cover return False return False
kivy__python-for-android-2399
Pymunk,kivy apk crashing on Android 5.1 <!-- The issue tracker is a tool to address bugs NOT a support platform. Please use the Discord community or Stack Overflow for support questions, more information at https://github.com/kivy/python-for-android#support --> ### Checklist - [ ] the issue is indeed a bug and not a support request - [ ] issue doesn't already exist: https://github.com/kivy/python-for-android/issues - [ ] I have a short, runnable example that reproduces the issue - [ ] I reproduced the problem with the latest development version (`p4a.branch = develop`) - [ ] I used the grave accent (aka backticks) to format code or logs when appropriated ### Versions - Python:3.8.1 - OS:Android 5.1 - Kivy:2.0.2 - Cython: - OpenJDK:8 ### Description pymunk,kivy apk crashing on Android 5.1 // REPLACE ME: What are you trying to get done, what has happened, what went wrong, and what did you expect? ### buildozer.spec [app] # (str) Title of your application title = Tone # (str) Package name package.name = tone # (str) Package domain (needed for android/ios packaging) package.domain = org.test # (str) Source code where the main.py live source.dir = . # (list) Source files to include (let empty to include all the files) source.include_exts = py,png,jpg,kv,atlas # (list) List of inclusions using pattern matching #source.include_patterns = assets/*,images/*.png # (list) Source files to exclude (let empty to not exclude anything) #source.exclude_exts = spec # (list) List of directory to exclude (let empty to not exclude anything) source.exclude_dirs = tests, bin # (list) List of exclusions using pattern matching #source.exclude_patterns = license,images/*/*.jpg # (str) Application versioning (method 1) version = 0.1 # (str) Application versioning (method 2) # version.regex = __version__ = ['"](.*)['"] # version.filename = %(source.dir)s/main.py # (list) Application requirements # comma separated e.g. requirements = sqlite3,kivy requirements = python3,kivy==2.0.0,plyer,android,pyjnius,pymunk,cffi,pycparser,setuptools # (str) Custom source folders for requirements # Sets custom source for any requirements with recipes # requirements.source.kivy = ../../kivy # (list) Garden requirements #garden_requirements = # (str) Presplash of the application #presplash.filename = %(source.dir)s/data/presplash.png # (str) Icon of the application #icon.filename = %(source.dir)s/data/icon.png # (str) Supported orientation (one of landscape, sensorLandscape, portrait or all) orientation = portrait # (list) List of service to declare #services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY # # OSX Specific # # # author = © Copyright Info # change the major version of python used by the app osx.python_version = 3 # Kivy version to use osx.kivy_version = 1.9.1 # # Android specific # # (bool) Indicate if the application should be fullscreen or not fullscreen = 0 # (string) Presplash background color (for new android toolchain) # Supported formats are: #RRGGBB #AARRGGBB or one of the following names: # red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray, # darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy, # olive, purple, silver, teal. #android.presplash_color = #FFFFFF # (list) Permissions android.permissions = INTERNET # (int) Target Android API, should be as high as possible. #android.api = 27 # (int) Minimum API your APK will support. #android.minapi = 21 # (int) Android SDK version to use #android.sdk = 20 # (str) Android NDK version to use #android.ndk = 19b # (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi. #android.ndk_api = 21 # (bool) Use --private data storage (True) or --dir public storage (False) #android.private_storage = True # (str) Android NDK directory (if empty, it will be automatically downloaded.) #android.ndk_path = # (str) Android SDK directory (if empty, it will be automatically downloaded.) #android.sdk_path = # (str) ANT directory (if empty, it will be automatically downloaded.) #android.ant_path = # (bool) If True, then skip trying to update the Android sdk # This can be useful to avoid excess Internet downloads or save time # when an update is due and you just want to test/build your package # android.skip_update = False # (bool) If True, then automatically accept SDK license # agreements. This is intended for automation only. If set to False, # the default, you will be shown the license when first running # buildozer. # android.accept_sdk_license = False # (str) Android entry point, default is ok for Kivy-based app #android.entrypoint = org.renpy.android.PythonActivity # (str) Android app theme, default is ok for Kivy-based app # android.apptheme = "@android:style/Theme.NoTitleBar" # (list) Pattern to whitelist for the whole project #android.whitelist = # (str) Path to a custom whitelist file #android.whitelist_src = # (str) Path to a custom blacklist file #android.blacklist_src = # (list) List of Java .jar files to add to the libs so that pyjnius can access # their classes. Don't add jars that you do not need, since extra jars can slow # down the build process. Allows wildcards matching, for example: # OUYA-ODK/libs/*.jar #android.add_jars = foo.jar,bar.jar,path/to/more/*.jar # (list) List of Java files to add to the android project (can be java or a # directory containing the files) #android.add_src = # (list) Android AAR archives to add (currently works only with sdl2_gradle # bootstrap) #android.add_aars = # (list) Gradle dependencies to add (currently works only with sdl2_gradle # bootstrap) #android.gradle_dependencies = # (list) add java compile options # this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option # see https://developer.android.com/studio/write/java8-support for further information # android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8" # (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies} # please enclose in double quotes # e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }" #android.add_gradle_repositories = # (list) packaging options to add # see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html # can be necessary to solve conflicts in gradle_dependencies # please enclose in double quotes # e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'" #android.add_gradle_repositories = # (list) Java classes to add as activities to the manifest. #android.add_activities = com.example.ExampleActivity # (str) OUYA Console category. Should be one of GAME or APP # If you leave this blank, OUYA support will not be enabled #android.ouya.category = GAME # (str) Filename of OUYA Console icon. It must be a 732x412 png image. #android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png # (str) XML file to include as an intent filters in <activity> tag #android.manifest.intent_filters = # (str) launchMode to set for the main activity #android.manifest.launch_mode = standard # (list) Android additional libraries to copy into libs/armeabi #android.add_libs_armeabi = libs/android/*.so #android.add_libs_armeabi_v7a = libs/android-v7/*.so #android.add_libs_arm64_v8a = libs/android-v8/*.so #android.add_libs_x86 = libs/android-x86/*.so #android.add_libs_mips = libs/android-mips/*.so # (bool) Indicate whether the screen should stay on # Don't forget to add the WAKE_LOCK permission if you set this to True #android.wakelock = False # (list) Android application meta-data to set (key=value format) #android.meta_data = # (list) Android library project to add (will be added in the # project.properties automatically.) #android.library_references = # (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag #android.uses_library = # (str) Android logcat filters to use #android.logcat_filters = *:S python:D # (bool) Copy library instead of making a libpymodules.so #android.copy_libs = 1 # (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64 android.arch = armeabi-v7a # (int) overrides automatic versionCode computation (used in build.gradle) # this is not the same as app version and should only be edited if you know what you're doing # android.numeric_version = 1 # # Python for android (p4a) specific # # (str) python-for-android fork to use, defaults to upstream (kivy) #p4a.fork = kivy # (str) python-for-android branch to use, defaults to master #p4a.branch = master # (str) python-for-android git clone directory (if empty, it will be automatically cloned from github) #p4a.source_dir = # (str) The directory in which python-for-android should look for your own build recipes (if any) #p4a.local_recipes = # (str) Filename to the hook for p4a #p4a.hook = # (str) Bootstrap to use for android builds # p4a.bootstrap = sdl2 # (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask) #p4a.port = # # iOS specific # # (str) Path to a custom kivy-ios folder #ios.kivy_ios_dir = ../kivy-ios # Alternately, specify the URL and branch of a git checkout: ios.kivy_ios_url = https://github.com/kivy/kivy-ios ios.kivy_ios_branch = master # Another platform dependency: ios-deploy # Uncomment to use a custom checkout #ios.ios_deploy_dir = ../ios_deploy # Or specify URL and branch ios.ios_deploy_url = https://github.com/phonegap/ios-deploy ios.ios_deploy_branch = 1.7.0 # (str) Name of the certificate to use for signing the debug version # Get a list of available identities: buildozer ios list_identities #ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)" # (str) Name of the certificate to use for signing the release version #ios.codesign.release = %(ios.codesign.debug)s [buildozer] # (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) log_level = 2 # (int) Display warning if buildozer is run as root (0 = False, 1 = True) warn_on_root = 1 # (str) Path to build artifact storage, absolute or relative to spec file # build_dir = ./.buildozer # (str) Path to build output (i.e. .apk, .ipa) storage # bin_dir = ./bin # ----------------------------------------------------------------------------- # List as sections # # You can define all the "list" as [section:key]. # Each line will be considered as a option to the list. # Let's take [app] / source.exclude_patterns. # Instead of doing: # #[app] #source.exclude_patterns = license,data/audio/*.wav,data/images/original/* # # This can be translated into: # #[app:source.exclude_patterns] #license #data/audio/*.wav #data/images/original/* # # ----------------------------------------------------------------------------- # Profiles # # You can extend section / key with a profile # For example, you want to deploy a demo version of your application without # HD content. You could first change the title to add "(demo)" in the name # and extend the excluded directories to remove the HD content. # #[app@demo] #title = My Application (demo) # #[app:source.exclude_patterns@demo] #images/hd/* # # Then, invoke the command line with the "demo" profile: # #buildozer --profile demo android debug Command: ```sh // REPLACE ME: buildozer command ran? e.g. buildozer android debug // Keep the triple grave accent (aka backquote/backtick) to have the code formatted ``` Spec file: ``` // REPLACE ME: Paste your buildozer.spec file here ``` ### Logs I/python (17703): [INFO ] [GL ] Backend used <sdl2> I/python (17703): [INFO ] [GL ] OpenGL version <b'OpenGL ES 2.0'> I/python (17703): [INFO ] [GL ] OpenGL vendor <b'ARM'> I/python (17703): [INFO ] [GL ] OpenGL renderer <b'Mali-400 MP'> I/python (17703): [INFO ] [GL ] OpenGL parsed version: 2, 0 I/python (17703): [INFO ] [GL ] Texture max size <4096> I/python (17703): [INFO ] [GL ] Texture max units <8> I/python (17703): [INFO ] [Window ] auto add sdl2 input provider I/python (17703): [INFO ] [Window ] virtual keyboard not allowed, single mode, not docked I/python (17703): [INFO ] [Text ] Provider: sdl2 I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBNewForExtents' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBNewForCircle' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBIntersects' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBContainsBB' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBContainsVect' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBMerge' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBExpand' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBCenter' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBArea' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBMergedArea' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBSegmentQuery' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBIntersectsSegment' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): /home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/cparser.py:162: UserWarning: Global variable '_cpBBClampVect' in cdef(): for consistency with C it should have a storage class specifier (usually 'extern') I/python (17703): Loading chipmunk for Linux (32bit) [/data/data/org.test.tone/files/app/_python_bundle/site-packages/pymunk/libchipmunk.so] I/python (17703): Failed to load Pymunk library. I/python (17703): This error usually means that you don't have a compiled version of Chipmunk in I/python (17703): the correct spot where Pymunk can find it. If you tried to run Pymunk without I/python (17703): installing it properly this can be the result. I/python (17703): The good news is that it is usually enough (at least on *nix and OS X) to I/python (17703): run the build command: I/python (17703): You compile Chipmunk with I/python (17703): > python setup.py build_ext --inplace I/python (17703): and then verify with I/python (17703): > python -m pymunk.test I/python (17703): (for complete instructions please see the readme file) I/python (17703): Another cause of this problem could be if you didnt included the Chipmunk I/python (17703): library when using a freeze tool such as Py2exe or PyInstaller. Please see the I/python (17703): examples for how to include the library file when freezing a binary. I/python (17703): If it still doesnt work, please report as a bug on the issue tracker at I/python (17703): https://github.com/viblo/pymunk/issues I/python (17703): Remember to include information about your OS, which version of python you use I/python (17703): and the version of pymunk you tried to run. A description of what you did to I/python (17703): trigger the error is also good. Please include the exception traceback if any I/python (17703): (usually found below this message). I/python (17703): Traceback (most recent call last): I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/app/main.py", line 33, in <module> I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/pymunk/__init__.py", line 58, in <module> I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/pymunk/_chipmunk_cffi.py", line 3, in <module> I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/pymunk/_chipmunk_cffi_abi.py", line 1475, in <module> I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/pymunk/_libload.py", line 50, in load_library I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/api.py", line 146, in dlopen I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/api.py", line 828, in _make_ffi_library I/python (17703): File "/home/sahil/app_test_kivy/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/tone/cffi/api.py", line 823, in _load_backend_lib I/python (17703): OSError: cannot load library '/data/data/org.test.tone/files/app/_python_bundle/site-packages/pymunk/libchipmunk.so': dlopen failed: cannot locate symbol "__sF" referenced by "libchipmunk.so".... Additionally, ctypes.util.find_library() did not manage to locate a library called '/data/data/org.test.tone/files/app/_python_bundle/site-packages/pymunk/libchipmunk.so' I/python (17703): Python for android ended. ``` // REPLACE ME: Paste the build output containing the error // Keep the triple grave accent (a.k.a. backquote/backtick) to have the code formatted ```
[ { "content": "from pythonforandroid.recipe import CompiledComponentsPythonRecipe\n\n\nclass PymunkRecipe(CompiledComponentsPythonRecipe):\n name = \"pymunk\"\n version = \"6.0.0\"\n url = \"https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip\"\n depends = [\"cffi\", \"setuptools\"]...
[ { "content": "from pythonforandroid.recipe import CompiledComponentsPythonRecipe\n\n\nclass PymunkRecipe(CompiledComponentsPythonRecipe):\n name = \"pymunk\"\n version = \"6.0.0\"\n url = \"https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip\"\n depends = [\"cffi\", \"setuptools\"]...
diff --git a/pythonforandroid/recipes/pymunk/__init__.py b/pythonforandroid/recipes/pymunk/__init__.py index bf7cb5541c..a982098f26 100644 --- a/pythonforandroid/recipes/pymunk/__init__.py +++ b/pythonforandroid/recipes/pymunk/__init__.py @@ -10,7 +10,8 @@ class PymunkRecipe(CompiledComponentsPythonRecipe): def get_recipe_env(self, arch): env = super().get_recipe_env(arch) - env["LDFLAGS"] += " -llog" + env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage + env["LDFLAGS"] += " -lm" # For older versions of Android return env
hpcaitech__ColossalAI-2777
[tensor] fix some unittests [tensor] fix some unittests [tensor] fix some unittests [BUG]: Wrong import in `zero/sharded_optim/_utils.py` ### 🐛 Describe the bug In issue #2774 , thanks @malfet for pointing out that we should not use `torch._six` to import `inf` and use `torch` to import `inf` instead, however, there is a small mistake in PR #2775 use an invalid `torch.six` module to import `inf`. We should fix this typo. ### Environment _No response_
[ { "content": "import math\nfrom typing import Optional\n\nimport torch\nimport torch.distributed as dist\nfrom torch.six import inf\nfrom torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors\n\nfrom colossalai.tensor import ColoParameter\nfrom colossalai.utils import is_model_parallel_parameter\...
[ { "content": "import math\nfrom typing import Optional\n\nimport torch\nimport torch.distributed as dist\nfrom torch import inf\nfrom torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors\n\nfrom colossalai.tensor import ColoParameter\nfrom colossalai.utils import is_model_parallel_parameter\n\n\...
diff --git a/colossalai/zero/sharded_optim/_utils.py b/colossalai/zero/sharded_optim/_utils.py index 68928b232660..9ca2fdf5aa06 100644 --- a/colossalai/zero/sharded_optim/_utils.py +++ b/colossalai/zero/sharded_optim/_utils.py @@ -3,7 +3,7 @@ import torch import torch.distributed as dist -from torch.six import inf +from torch import inf from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from colossalai.tensor import ColoParameter
systemd__mkosi-1956
[Meta] declare a policy about adding new distributions Before people start creating issues asking to support their favorite distribution, I think that mkosi should declare its policy regarding new distributions support. The policy should state in which terms (if any) you will be willing to support a new distributions.
[ { "content": "# SPDX-License-Identifier: LGPL-2.1+\n\nimport enum\nimport importlib\nimport re\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING, Optional, cast\n\nfrom mkosi.architecture import Architecture\nfrom mkosi.util import StrEnum, read_os_release\n\nif TYPE_CHECKING:\n from mk...
[ { "content": "# SPDX-License-Identifier: LGPL-2.1+\n\nimport enum\nimport importlib\nimport re\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING, Optional, cast\n\nfrom mkosi.architecture import Architecture\nfrom mkosi.util import StrEnum, read_os_release\n\nif TYPE_CHECKING:\n from mk...
diff --git a/docs/distribution-policy.md b/docs/distribution-policy.md new file mode 100644 index 000000000..458b5d57d --- /dev/null +++ b/docs/distribution-policy.md @@ -0,0 +1,32 @@ +# Adding new distributions + +Merging support for a new distribution in mkosi depends on a few +factors. Not all of these are required but depending on how many of +these requirements are satisfied, the chances of us merging support for +your distribution will improve: + +1. Is the distribution somewhat popular? mkosi's goal is not to support + every distribution under the sun, the distribution should have a + substantial amount of users. +2. Does the distribution differentiate itself somehow from the + distributions that are already supported? We're generally not + interested in supporting distributions that only consist of minimal + configuration changes to another distribution. +3. Is there a long-term maintainer for the distribution in mkosi? When + proposing support for a new distribution, we expect you to be the + maintainer for the distribution and to respond when pinged for + support on distribution specific issues. +4. Does the distribution use a custom package manager or one of the + already supported ones (apt, dnf, pacman, zypper)? Supporting new + package managers in mkosi is generally a lot of work. We can support + new ones if needed for a new distribution, but we will insist on the + package manager having a somewhat sane design, with official support + for building in a chroot and running unprivileged in a user namespace + being the bare minimum features we expect from any new package + manager. + +We will only consider new distributions that satisfy all or most of +these requirements. However, you can still use mkosi with the +distribution by setting the `Distribution` setting to `custom` and +implementing either providing the rootfs via a skeleton tree or base +tree, or by providing the rootfs via a prepare script. diff --git a/mkosi/distributions/__init__.py b/mkosi/distributions/__init__.py index 8169983ae..839d6ec13 100644 --- a/mkosi/distributions/__init__.py +++ b/mkosi/distributions/__init__.py @@ -72,6 +72,8 @@ def tools_tree_packages(cls) -> list[str]: class Distribution(StrEnum): + # Please consult docs/distribution-policy.md and contact one + # of the mkosi maintainers before implementing a new distribution. fedora = enum.auto() debian = enum.auto() ubuntu = enum.auto()
activeloopai__deeplake-1447
[BUG] hub.read failing with h265 videos Hi, hub.read() fails to decompress h265 videos right. I get unreadable videos with a higher number of frames (x10). When converting it to h264 first, hub.read() seems to work fine.
[ { "content": "import hub\nfrom hub.util.exceptions import (\n SampleCompressionError,\n SampleDecompressionError,\n UnsupportedCompressionError,\n CorruptedSampleError,\n)\nfrom hub.compression import (\n get_compression_type,\n BYTE_COMPRESSION,\n IMAGE_COMPRESSION,\n VIDEO_COMPRESSION,...
[ { "content": "import hub\nfrom hub.util.exceptions import (\n SampleCompressionError,\n SampleDecompressionError,\n UnsupportedCompressionError,\n CorruptedSampleError,\n)\nfrom hub.compression import (\n get_compression_type,\n BYTE_COMPRESSION,\n IMAGE_COMPRESSION,\n VIDEO_COMPRESSION,...
diff --git a/hub/core/compression.py b/hub/core/compression.py index b2bff7a6d1..52528e9d70 100644 --- a/hub/core/compression.py +++ b/hub/core/compression.py @@ -827,7 +827,7 @@ def _get_video_info(file: Union[bytes, memoryview, str]) -> dict: "-select_streams", "v:0", "-show_entries", - "stream=width,height,duration,r_frame_rate", + "stream=width,height,duration,avg_frame_rate", "-of", "default=noprint_wrappers=1", "pipe:",
plone__Products.CMFPlone-690
adding site with default language 'de-at' breaks With current Plone 5 beta 1 and the merged language control panel, adding a site with a language like 'de-at' breaks and gives the following traceback: ``` 2015-04-01 20:25:30 ERROR Zope.SiteErrorLog 1427912730.490.962488456232 http://localhost:8888/@@plone-addsite Traceback (innermost last): Module ZPublisher.Publish, line 138, in publish Module ZPublisher.mapply, line 77, in mapply Module ZPublisher.Publish, line 48, in call_object Module Products.CMFPlone.browser.admin, line 232, in __call__ Module Products.CMFPlone.factory, line 95, in addPloneSite Module plone.registry.registry, line 47, in __setitem__ Module plone.registry.record, line 83, in _set_value Module zope.schema._bootstrapfields, line 182, in validate Module zope.schema._field, line 389, in _validate ConstraintNotSatisfied: de-at ``` Please note, 'de-at' is selected by default, as reported by my browser. - `Products.CMFPlone.browser.admin.AddPloneSite.languages` uses `plone.i18n.locales.interfaces.IContentLanguageAvailability` and constructs a list of languages with combined language codes, if the default language as reported by the browser contains a "-". - `Products.CMFPlone.interfaces.controlpanel.ILanguageSchema.use_combined_language_codes` as a default value of False. - `plone.app.vocabularies.language.AvailableContentLanguageVocabulary` constructs it's language list via `plone.i18n.utility.LanguageUtility.getAvailableLanguages` according to the setting `use_combined_language_codes`, which is False by default. I guess, we have to set `use_combined_language_codes` to True in CMFPlone/factory, if CMFPlone/admin/AddPloneSite decides to use combined language codes...
[ { "content": "# -*- coding: utf-8 -*-\nfrom plone.supermodel import model\nfrom Products.CMFPlone import PloneMessageFactory as _ # NOQA\nfrom Products.CMFPlone.utils import validate_json\nfrom basetool import IPloneBaseTool\nfrom plone.locking.interfaces import ILockSettings\nfrom zope import schema\nfrom zop...
[ { "content": "# -*- coding: utf-8 -*-\nfrom plone.supermodel import model\nfrom Products.CMFPlone import PloneMessageFactory as _ # NOQA\nfrom Products.CMFPlone.utils import validate_json\nfrom basetool import IPloneBaseTool\nfrom plone.locking.interfaces import ILockSettings\nfrom zope import schema\nfrom zop...
diff --git a/CHANGES.rst b/CHANGES.rst index 5cf42666d3..9e7842d370 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -8,6 +8,9 @@ Changelog 5.0b3 (unreleased) ------------------ +- Fix adding a new Plone site with country specific language. Refs #411. + [jaroel] + - fix plone-logged-in bundle not using global jquery for requirejs dependency and in weird cases causing select2 load errors in patterns(especially resource registry) [vangheem] diff --git a/Products/CMFPlone/controlpanel/README.rst b/Products/CMFPlone/controlpanel/README.rst index 7d9a7a4b4d..f3ba7c66c6 100644 --- a/Products/CMFPlone/controlpanel/README.rst +++ b/Products/CMFPlone/controlpanel/README.rst @@ -68,7 +68,7 @@ Language Control Panel ['en'] >>> language_settings.use_combined_language_codes - False + True >>> language_settings.display_flags False diff --git a/Products/CMFPlone/controlpanel/tests/test_controlpanel_bbb_language_adapter.py b/Products/CMFPlone/controlpanel/tests/test_controlpanel_bbb_language_adapter.py index 75fd6fe837..a96d998680 100644 --- a/Products/CMFPlone/controlpanel/tests/test_controlpanel_bbb_language_adapter.py +++ b/Products/CMFPlone/controlpanel/tests/test_controlpanel_bbb_language_adapter.py @@ -74,24 +74,24 @@ def test_get_use_combined_language_codes(self): self.assertEqual( getAdapter( self.portal, ILanguageSchema).use_combined_language_codes, - False + True ) - self.settings.use_combined_language_codes = True + self.settings.use_combined_language_codes = False self.assertEquals( getAdapter(self.portal, ILanguageSchema).use_combined_language_codes, - True + False ) def test_set_use_combined_language_codes(self): self.assertEquals( self.settings.use_combined_language_codes, - False + True ) getAdapter( - self.portal, ILanguageSchema).use_combined_language_codes = True + self.portal, ILanguageSchema).use_combined_language_codes = False self.assertEquals( self.settings.use_combined_language_codes, - True + False ) def test_get_display_flags(self): diff --git a/Products/CMFPlone/controlpanel/tests/test_controlpanel_browser_language.py b/Products/CMFPlone/controlpanel/tests/test_controlpanel_browser_language.py index 1e0bda00eb..eb32c75fa8 100644 --- a/Products/CMFPlone/controlpanel/tests/test_controlpanel_browser_language.py +++ b/Products/CMFPlone/controlpanel/tests/test_controlpanel_browser_language.py @@ -108,25 +108,26 @@ def test_default_language(self): # self.assertEqual(settings.available_languages, ['en', 'de']) def test_use_combined_language_codes(self): + """This checks swithing combined languages codes support off/on.""" registry = getUtility(IRegistry) settings = registry.forInterface(ILanguageSchema, prefix='plone') self.browser.open( "%s/@@language-controlpanel" % self.portal_url) - self.assertEqual(settings.use_combined_language_codes, False) + self.assertEqual(settings.use_combined_language_codes, True) self.assertEqual( self.browser.getControl( 'Show country-specific language variants' ).selected, - False + True ) self.browser.getControl( 'Show country-specific language variants' - ).selected = True + ).selected = False self._inject_available_languages_field('en') self.browser.getControl('Save').click() - self.assertEqual(settings.use_combined_language_codes, True) + self.assertEqual(settings.use_combined_language_codes, False) def test_display_flags(self): registry = getUtility(IRegistry) diff --git a/Products/CMFPlone/interfaces/controlpanel.py b/Products/CMFPlone/interfaces/controlpanel.py index cb97f5319f..cd3e13c412 100644 --- a/Products/CMFPlone/interfaces/controlpanel.py +++ b/Products/CMFPlone/interfaces/controlpanel.py @@ -147,7 +147,7 @@ class ILanguageSchema(Interface): default=u"Examples: pt-br (Brazilian Portuguese), " u"en-us (American English) etc." ), - default=False, + default=True, required=False )
netbox-community__netbox-1403
Device interface shows twice on IP Addresses page Python version: 2.7.5 NetBox version: 2.1.2 On the "IP addresses" page the device interface is showing up in both the "Device" column and the Interface Column. I am able to replicate this issue with any link to the "IP Addresses" page. I dont see any purpose in listing the interface twice. It just clutters the page. ![2017-08-07 17_06_32-ip addresses - netbox](https://user-images.githubusercontent.com/29483942/29045848-0982b5bc-7b93-11e7-8a3e-15c657e51bb7.png)
[ { "content": "from __future__ import unicode_literals\n\nimport django_tables2 as tables\nfrom django_tables2.utils import Accessor\n\nfrom utilities.tables import BaseTable, ToggleColumn\nfrom .models import Aggregate, IPAddress, Prefix, RIR, Role, VLAN, VLANGroup, VRF\n\n\nRIR_UTILIZATION = \"\"\"\n<div class...
[ { "content": "from __future__ import unicode_literals\n\nimport django_tables2 as tables\nfrom django_tables2.utils import Accessor\n\nfrom utilities.tables import BaseTable, ToggleColumn\nfrom .models import Aggregate, IPAddress, Prefix, RIR, Role, VLAN, VLANGroup, VRF\n\n\nRIR_UTILIZATION = \"\"\"\n<div class...
diff --git a/netbox/ipam/tables.py b/netbox/ipam/tables.py index 65ab5b2e407..af82042dd00 100644 --- a/netbox/ipam/tables.py +++ b/netbox/ipam/tables.py @@ -80,7 +80,6 @@ IPADDRESS_DEVICE = """ {% if record.interface %} <a href="{{ record.interface.device.get_absolute_url }}">{{ record.interface.device }}</a> - ({{ record.interface.name }}) {% else %} &mdash; {% endif %}
google__flax-628
After update from 0.2.0: AttributeError: module 'jax.core' has no attribute 'eval_context' After updating from flax 0.2.0 to flax 0.2.2 I get the above error message. Downgrading to 0.2.0 solves this, so the error source is located. I'm working with the now deprecated flax.nn package if backward-compatibility might be the reason for this issue. The Issue is encountered in a custom RNN, when using the init_by_shape function in conjunction with jax.lax.scan.
[ { "content": "# Copyright 2020 The Flax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by ap...
[ { "content": "# Copyright 2020 The Flax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by ap...
diff --git a/setup.py b/setup.py index 58bfe451a..7a6cf9292 100644 --- a/setup.py +++ b/setup.py @@ -26,7 +26,7 @@ install_requires = [ "numpy>=1.12", - "jax>=0.1.59", + "jax>=0.1.77", "matplotlib", # only needed for tensorboard export "dataclasses;python_version<'3.7'", # will only install on py3.6 "msgpack",
django-haystack__django-haystack-1831
Update extras_require in setup.py to support Elasticsearch 7 Pipenv failed to generate lock file with `elasticsearch>=7.0.0` due to the bounded version in `setup.py`. Should adjust bounded version in `extras_require` so that `Pipfile.lock` can be generated ![](https://user-images.githubusercontent.com/16464044/149522995-848940d1-bc6e-4e90-b06d-947b6cdd115b.png)
[ { "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\ninstall_requires = [\"Django>=2.2\"]\n\ntests_require = [\n \"pysolr>=3.7.0\",\n \"whoosh>=2.5.4,<3.0\",\n \"python-dateutil\",\n \"geopy==2.0.0\",\n \"nose\",\n \"coverage\",\n \"requests\",\n]\n\nsetup(\n name=\"djang...
[ { "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\ninstall_requires = [\"Django>=2.2\"]\n\ntests_require = [\n \"pysolr>=3.7.0\",\n \"whoosh>=2.5.4,<3.0\",\n \"python-dateutil\",\n \"geopy==2.0.0\",\n \"nose\",\n \"coverage\",\n \"requests\",\n]\n\nsetup(\n name=\"djang...
diff --git a/setup.py b/setup.py index 6033e8dfd..3224ed2a1 100644 --- a/setup.py +++ b/setup.py @@ -55,7 +55,7 @@ install_requires=install_requires, tests_require=tests_require, extras_require={ - "elasticsearch": ["elasticsearch>=5,<6"], + "elasticsearch": ["elasticsearch>=5,<8"], }, test_suite="test_haystack.run_tests.run_all", )
Gallopsled__pwntools-1660
SSL Timeout Error immediately when switching to interactive #### PoC ``` from pwn import * r = remote('google.com', 443, ssl=True) r.interactive() r.close() ``` It immediately results in: ``` [+] Opening connection to google.com on port 443: Done [*] Switching to interactive mode Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/home/hopkins/.local/lib/python2.7/site-packages/pwnlib/tubes/tube.py", line 784, in recv_thread cur = self.recv(timeout = 0.05) File "/home/hopkins/.local/lib/python2.7/site-packages/pwnlib/tubes/tube.py", line 78, in recv return self._recv(numb, timeout) or '' File "/home/hopkins/.local/lib/python2.7/site-packages/pwnlib/tubes/tube.py", line 156, in _recv if not self.buffer and not self._fillbuffer(timeout): File "/home/hopkins/.local/lib/python2.7/site-packages/pwnlib/tubes/tube.py", line 126, in _fillbuffer data = self.recv_raw(self.buffer.get_fill_size()) File "/home/hopkins/.local/lib/python2.7/site-packages/pwnlib/tubes/sock.py", line 37, in recv_raw data = self.sock.recv(numb, *a) File "/usr/lib/python2.7/ssl.py", line 772, in recv return self.read(buflen) File "/usr/lib/python2.7/ssl.py", line 659, in read v = self._sslobj.read(len) SSLError: ('The read operation timed out',) ``` Note that doing so on a non-SSL server doesn't have this issue: ``` from pwn import * r = remote('google.com', 80, ssl=False) r.interactive() r.close() ``` It allows you to type in HTTP Request in interactive mode, and return the server response without any issues. ``` GET / ``` ``` <HTTP Responses> ``` Is the SSL feature is broken in pwntools?
[ { "content": "from __future__ import absolute_import\nfrom __future__ import division\n\nimport errno\nimport select\nimport six\nimport socket\n\nfrom pwnlib.log import getLogger\nfrom pwnlib.tubes.tube import tube\n\nlog = getLogger(__name__)\n\nclass sock(tube):\n \"\"\"Base type used for :class:`.tubes.r...
[ { "content": "from __future__ import absolute_import\nfrom __future__ import division\n\nimport errno\nimport select\nimport six\nimport socket\n\nfrom pwnlib.log import getLogger\nfrom pwnlib.tubes.tube import tube\n\nlog = getLogger(__name__)\n\nclass sock(tube):\n \"\"\"Base type used for :class:`.tubes.r...
diff --git a/pwnlib/tubes/sock.py b/pwnlib/tubes/sock.py index f25419836..f2a4adf54 100644 --- a/pwnlib/tubes/sock.py +++ b/pwnlib/tubes/sock.py @@ -48,6 +48,8 @@ def recv_raw(self, numb, *a): raise EOFError elif e.errno == errno.EINTR: continue + elif 'timed out' in e.message: + return None else: raise
pymodbus-dev__pymodbus-1443
StartAsyncSerialServer doesn't work pymodbus version 3.2 ### Discussed in https://github.com/pymodbus-dev/pymodbus/discussions/1433 <sup>Originally posted by **dlmoffett** March 13, 2023</sup> ### Versions - Python: 3.9 - OS: Windows - Pymodbus: 3.2.0 - Modbus Hardware (if used): USB to RS458 ### Pymodbus Specific - Server: `StartAsyncSerialServer` ### Description `StartAsyncSerialServer` no longer actually starts the server. ### Code and Logs ```python import asyncio import logging from pymodbus.framer.rtu_framer import ModbusRtuFramer from pymodbus.server import StartAsyncSerialServer logging.basicConfig( format="[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S %z", level=logging.INFO, ) log = logging.getLogger(__name__) async def modbus_slave(): return await StartAsyncSerialServer( framer=ModbusRtuFramer, port="COM10", baudrate=19200, ) def sanity(): log.info(f"✅ Here I am!") asyncio.run(modbus_slave()) log.info(f"❌ I'm going insane!") ``` Per the [example documentation](https://pymodbus.readthedocs.io/en/dev/source/examples.html#asynchronous-server-example) I would expect to only see my first log statement and for the server to be up and running indefinitely until I send a keyboard interrupt. However, that's not the case and I see the following output when running the above code, which exits immediately after making the logs: ``` [2023-03-13 16:07:53 -0600] [INFO] [fix_pymodbus.sanity] ✅ Here I am! [2023-03-13 16:07:53 -0600] [INFO] [fix_pymodbus.sanity] ❌ I'm going insane! ``` ### Working Monkey Patch If I make the following monkey patch everything works as expected: ```python async def StartAsyncSerialServer( # pylint: disable=invalid-name,dangerous-default-value context=None, identity=None, custom_functions=[], **kwargs, ): # pragma: no cover """Start and run a serial modbus server. :param context: The ModbusServerContext datastore :param identity: An optional identify structure :param custom_functions: An optional list of custom function classes supported by server instance. :param kwargs: The rest """ server = ModbusSerialServer( context, kwargs.pop("framer", ModbusAsciiFramer), identity=identity, **kwargs ) await server.start() # <----------------------Adding this makes it work 🤔 await _serverList.run(server, custom_functions) ``` ### Expected Behavior I expect the sample code above to to run until a keyboard interrupt.
[ { "content": "\"\"\"Implementation of a Threaded Modbus Server.\"\"\"\n# pylint: disable=missing-type-doc\nimport asyncio\nimport ssl\nimport time\nimport traceback\nfrom typing import Union\n\nfrom pymodbus.client.serial_asyncio import create_serial_connection\nfrom pymodbus.constants import Defaults\nfrom pym...
[ { "content": "\"\"\"Implementation of a Threaded Modbus Server.\"\"\"\n# pylint: disable=missing-type-doc\nimport asyncio\nimport ssl\nimport time\nimport traceback\nfrom typing import Union\n\nfrom pymodbus.client.serial_asyncio import create_serial_connection\nfrom pymodbus.constants import Defaults\nfrom pym...
diff --git a/pymodbus/server/async_io.py b/pymodbus/server/async_io.py index 11024fc9f..ce78ec446 100644 --- a/pymodbus/server/async_io.py +++ b/pymodbus/server/async_io.py @@ -1225,6 +1225,7 @@ async def StartAsyncSerialServer( # pylint: disable=invalid-name,dangerous-defa server = ModbusSerialServer( context, kwargs.pop("framer", ModbusAsciiFramer), identity=identity, **kwargs ) + server.start() await _serverList.run(server, custom_functions)
gratipay__gratipay.com-2699
support@gittip.com still linked several places Should be support@gratipay.com, right? ;-)
[ { "content": "\"\"\"\nThis module contains exceptions shared across application code.\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\n\nclass ProblemChangingUsername(Exception):\n def __str__(self):\n return self.msg.format(self.args[0])\n\nclass UsernameIsEmpty(ProblemChangingUs...
[ { "content": "\"\"\"\nThis module contains exceptions shared across application code.\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\n\nclass ProblemChangingUsername(Exception):\n def __str__(self):\n return self.msg.format(self.args[0])\n\nclass UsernameIsEmpty(ProblemChangingUs...
diff --git a/gratipay/exceptions.py b/gratipay/exceptions.py index 9e1bd1d340..9695ad9ef4 100644 --- a/gratipay/exceptions.py +++ b/gratipay/exceptions.py @@ -30,7 +30,7 @@ def __str__(self): return self.msg class HasBigTips(ProblemChangingNumber): - msg = "You receive tips too large for an individual. Please contact support@gittip.com." + msg = "You receive tips too large for an individual. Please contact support@gratipay.com." class TooGreedy(Exception): pass diff --git a/www/%username/account/close.spt b/www/%username/account/close.spt index 73a41382ad..ff3aece7d0 100644 --- a/www/%username/account/close.spt +++ b/www/%username/account/close.spt @@ -66,7 +66,7 @@ if POST: by Thursday, and then you'll be able to have your funds deposited to your bank account on file. To expedite the review, please <a - href="mailto:support@gittip.com?subject=review%20for%20closing%20account">contact + href="mailto:support@gratipay.com?subject=review%20for%20closing%20account">contact support</a>.</label></li> {% endif %} @@ -91,7 +91,7 @@ if POST: </ul> <p>If neither option works for you, please <a - href="mailto:support@gittip.com?subject=close%20account">contact + href="mailto:support@gratipay.com?subject=close%20account">contact support</a> to otherwise deal with your balance before closing your account.</p> diff --git a/www/about/faq.html.spt b/www/about/faq.html.spt index 7cebbd7884..f4290ade6c 100644 --- a/www/about/faq.html.spt +++ b/www/about/faq.html.spt @@ -60,7 +60,7 @@ title = "Frequently Asked Questions" expect additional fees from non-U.S. banks).</li> <li><a - href="mailto:support@gittip.com?subject=bitcoin%20payin">Email + href="mailto:support@gratipay.com?subject=bitcoin%20payin">Email us</a> to request a one-time bitcoin payin (1% + 15&cent; fee).</li> @@ -80,12 +80,12 @@ title = "Frequently Asked Questions" U.S.-only).</li> <li><a - href="mailto:support@gittip.com?subject=configuring%20PayPal">Email + href="mailto:support@gratipay.com?subject=configuring%20PayPal">Email us</a> to set up a weekly PayPal payout (unlimited payout; 2% fee capped at $20).</li> <li><a - href="mailto:support@gittip.com?subject=bitcoin%20payout">Email + href="mailto:support@gratipay.com?subject=bitcoin%20payout">Email us</a> to request a one-time bitcoin payout (1% + 15&cent; fee).</li> diff --git a/www/about/index.html.spt b/www/about/index.html.spt index fbac93f0bc..243c68e2aa 100644 --- a/www/about/index.html.spt +++ b/www/about/index.html.spt @@ -22,7 +22,7 @@ title = "About" the equation are rewarded publicly for their participation. (You can opt out of publicly displaying your total giving.)</p> - + </div> @@ -85,7 +85,7 @@ title = "About" Ambridge, PA 15003<br /> USA<br /> <br /> - Email: <a href="mailto:support@gittip.com">support@gittip.com</a><br /> + Email: <a href="mailto:support@gratipay.com">support@gratipay.com</a><br /> Twitter: <a href="https://twitter.com/Gratipay">@Gratipay</a><br /> Facebook: <a href="https://www.facebook.com/Gratipay">Gratipay</a><br /> Freenode: <a href="http://inside.gratipay.com/appendices/chat">#gratipay</a><br />
getpelican__pelican-2065
Quickstart locale error: 'NoneType' object has no attribute 'split' Pelican version: 594b9c96 (installed with `pip install -e "git+https://github.com/getpelican/pelican.git#egg=pelican"`) Python: 2.7.12 Windows x64 (within a virtual environment) Using: > blinker (1.4) docutils (0.12) feedgenerator (1.9) Jinja2 (2.8) Markdown (2.6.7) MarkupSafe (0.23) pelican (3.6.4.dev0, d:\documents\pelican\src\pelican) pip (8.1.2) Pygments (2.1.3) python-dateutil (2.5.3) pytz (2016.7) setuptools (28.7.1) six (1.10.0) smartypants (1.8.6) typogrify (2.0.7) Unidecode (0.4.19) wheel (0.30.0a0) When invoking `pelican-quickstart`, I am getting the following stacktrace: >(Pelican) D:\Documents\Pelican>pelican-quickstart Traceback (most recent call last): File "D:\Documents\Pelican\Scripts\pelican-quickstart-script.py", line 11, in <module> load_entry_point('pelican', 'console_scripts', 'pelican-quickstart')() File "d:\documents\pelican\lib\site-packages\pkg_resources\__init__.py", line 564, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "d:\documents\pelican\lib\site-packages\pkg_resources\__init__.py", line 2608, in load_entry_point return ep.load() File "d:\documents\pelican\lib\site-packages\pkg_resources\__init__.py", line 2268, in load return self.resolve() File "d:\documents\pelican\lib\site-packages\pkg_resources\__init__.py", line 2274, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "d:\documents\pelican\src\pelican\pelican\tools\pelican_quickstart.py", line 52, in <module> 'lang': locale.getlocale()[0].split('_')[0], AttributeError: 'NoneType' object has no attribute 'split'
[ { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\n\nimport argparse\nimport codecs\nimport locale\nimport os\nimport string\nimport sys\n\nimport pytz\n\ntry:\n import tzlocal\n _DEFAULT_TIMEZONE = tzlocal.get_localzone().zone\nexcept:\n...
[ { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\n\nimport argparse\nimport codecs\nimport locale\nimport os\nimport string\nimport sys\n\nimport pytz\n\ntry:\n import tzlocal\n _DEFAULT_TIMEZONE = tzlocal.get_localzone().zone\nexcept:\n...
diff --git a/pelican/tools/pelican_quickstart.py b/pelican/tools/pelican_quickstart.py index 6b4eb5a56..ecbc35103 100755 --- a/pelican/tools/pelican_quickstart.py +++ b/pelican/tools/pelican_quickstart.py @@ -21,6 +21,8 @@ from pelican import __version__ +if (sys.version_info.major == 2): + locale.setlocale(locale.LC_ALL, '') _TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
aio-libs__aiohttp-4057
TypeError: 'ABCMeta' aiohttp==3.6.0, Python 3.6.9 ## Long story short Cant import aiohttp pip freeze gives: aiohttp==3.6.0 python3 version: Python 3.6.9 import aiohttp Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/aiohttp/__init__.py", line 6, in <module> from .client import BaseConnector as BaseConnector File "/usr/local/lib/python3.6/site-packages/aiohttp/client.py", line 63, in <module> from .client_reqrep import ClientRequest as ClientRequest File "/usr/local/lib/python3.6/site-packages/aiohttp/client_reqrep.py", line 29, in <module> from . import hdrs, helpers, http, multipart, payload File "/usr/local/lib/python3.6/site-packages/aiohttp/multipart.py", line 703, in <module> class MultipartWriter(Payload): File "/usr/local/lib/python3.6/site-packages/aiohttp/multipart.py", line 786, in MultipartWriter headers: Optional[MultiMapping[str]]=None TypeError: 'ABCMeta' object is not subscriptable Any known restriction, what I am missing?
[ { "content": "import codecs\nimport os\nimport pathlib\nimport re\nimport sys\nfrom distutils.command.build_ext import build_ext\nfrom distutils.errors import (CCompilerError, DistutilsExecError,\n DistutilsPlatformError)\n\nfrom setuptools import Extension, setup\n\n\nif sys.versio...
[ { "content": "import codecs\nimport os\nimport pathlib\nimport re\nimport sys\nfrom distutils.command.build_ext import build_ext\nfrom distutils.errors import (CCompilerError, DistutilsExecError,\n DistutilsPlatformError)\n\nfrom setuptools import Extension, setup\n\n\nif sys.versio...
diff --git a/CHANGES/4057.bugfix b/CHANGES/4057.bugfix new file mode 100644 index 00000000000..990694930eb --- /dev/null +++ b/CHANGES/4057.bugfix @@ -0,0 +1 @@ +Update multidict requirement to >= 4.5 diff --git a/setup.py b/setup.py index 6d87f90b991..2cff742fd67 100644 --- a/setup.py +++ b/setup.py @@ -78,7 +78,7 @@ def build_extension(self, ext): install_requires = [ 'attrs>=17.3.0', 'chardet>=2.0,<4.0', - 'multidict>=4.0,<5.0', + 'multidict>=4.5,<5.0', 'async_timeout>=3.0,<4.0', 'yarl>=1.0,<2.0', 'idna-ssl>=1.0; python_version<"3.7"',
falconry__falcon-1946
Deprecate falcon.api_helpers See https://github.com/falconry/falcon/issues/1902. Starting with 3.1, mark `falcon.api_helpers` as deprecated. We could employ module-level `__getattr__` or redecorate re-imported functions.
[ { "content": "from .app_helpers import * # NOQA\n\n# TODO deprecate\n# import warnings\n# from .util.deprecation import DeprecatedWarning\n\n# warnings.warn('The api_helpers module was renamed to app_helpers.', DeprecatedWarning)\n", "path": "falcon/api_helpers.py" } ]
[ { "content": "import warnings\n\nfrom .app_helpers import * # NOQA\nfrom .util.deprecation import DeprecatedWarning\n\nwarnings.warn('The api_helpers module was renamed to app_helpers.', DeprecatedWarning)\n", "path": "falcon/api_helpers.py" } ]
diff --git a/falcon/api_helpers.py b/falcon/api_helpers.py index 3093856e1..23328b347 100644 --- a/falcon/api_helpers.py +++ b/falcon/api_helpers.py @@ -1,7 +1,6 @@ -from .app_helpers import * # NOQA +import warnings -# TODO deprecate -# import warnings -# from .util.deprecation import DeprecatedWarning +from .app_helpers import * # NOQA +from .util.deprecation import DeprecatedWarning -# warnings.warn('The api_helpers module was renamed to app_helpers.', DeprecatedWarning) +warnings.warn('The api_helpers module was renamed to app_helpers.', DeprecatedWarning) diff --git a/tests/test_deprecations.py b/tests/test_deprecations.py index 95dd5bb81..d33917f11 100644 --- a/tests/test_deprecations.py +++ b/tests/test_deprecations.py @@ -2,7 +2,7 @@ from falcon import app_helpers, request_helpers, stream -# from _util import has_cython +from _util import has_cython # NOQA def test_bounded_stream(): @@ -18,17 +18,16 @@ def test_imports(self): for name in app_helpers.__all__: assert getattr(api_helpers, name) is getattr(app_helpers, name) - # TODO enable test of deprecation - # @pytest.mark.skipif( - # has_cython, - # reason='Reloading modules on Cython does not work', - # ) - # def test_warning(self): - # import importlib + @pytest.mark.skipif( + has_cython, + reason='Reloading modules on Cython does not work', + ) + def test_warning(self): + import importlib - # from falcon.util.deprecation import DeprecatedWarning + from falcon.util.deprecation import DeprecatedWarning - # with pytest.warns(DeprecatedWarning, match='The api_helpers'): - # from falcon import api_helpers + with pytest.warns(DeprecatedWarning, match='The api_helpers'): + from falcon import api_helpers - # importlib.reload(api_helpers) + importlib.reload(api_helpers)
ansible-collections__community.aws-389
UnboundLocalError in sqs_queue <!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Copied the "Create FIFO queue" example from documentation, and it fails to run with an UnboundLocalError. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME sqs_queue ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.9.10 config file = /home/mstudd/.ansible.cfg configured module search path = ['/home/mstudd/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.8/site-packages/ansible executable location = /usr/bin/ansible python version = 3.8.3 (default, May 29 2020, 00:00:00) [GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` DEFAULT_VAULT_IDENTITY_LIST(env: ANSIBLE_VAULT_IDENTITY_LIST) = ['ops@~/.vault/ops', 'dev@~/.vault/dev'] ``` ##### OS / ENVIRONMENT Fedora 32 x86_64 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ``` --- - hosts: localhost tasks: - community.aws.sqs_queue: name: fifo-queue region: us-east-1 queue_type: fifo content_based_deduplication: yes ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS ansible-playbook creates the SQS queue as described (or reports relevant auth error if AWS creds aren't correct). ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` config file = /home/mstudd/dev/git/ansible/ansible.cfg configured module search path = ['/home/mstudd/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.8/site-packages/ansible executable location = /usr/bin/ansible-playbook python version = 3.8.3 (default, May 29 2020, 00:00:00) [GCC 10.1.1 20200507 (Red Hat 10.1.1-1)] Using /home/mstudd/dev/git/ansible/ansible.cfg as config file setting up inventory plugins host_list declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method script declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method auto declined parsing /home/mstudd/dev/git/ansible/inventories/dev/hosts as it did not pass its verify_file() method Set default localhost to localhost Parsed /home/mstudd/dev/git/ansible/inventories/dev/hosts inventory source with ini plugin [WARNING]: Found both group and host with same name: api-charts Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.8/site-packages/ansible/plugins/callback/default.py PLAYBOOK: test.yml ********************************************************************************************************************************************************************************************************************************************************************************************************** Positional arguments: test.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo tags: ('all',) inventory: ('/home/mstudd/dev/git/ansible/inventories/dev/hosts',) forks: 5 1 plays in test.yml PLAY [localhost] ************************************************************************************************************************************************************************************************************************************************************************************************************ Trying secret FileVaultSecret(filename='/home/mstudd/.vault/ops') for vault_id=ops Tried to use the vault secret (ops) to decrypt (/home/mstudd/dev/git/ansible/inventories/dev/group_vars/all/secrets.yml) but it failed. Error: HMAC verification failed: Signature did not match digest. Trying secret FileVaultSecret(filename='/home/mstudd/.vault/dev') for vault_id=dev TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/mstudd/dev/git/ansible/test.yml:3 <localhost.dev> ESTABLISH LOCAL CONNECTION FOR USER: mstudd <localhost.dev> EXEC /bin/sh -c 'echo ~mstudd && sleep 0' <localhost.dev> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/mstudd/.ansible/tmp `"&& mkdir /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479 && echo ansible-tmp-1596227662.5343304-234250-22361424934479="` echo /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479 `" ) && sleep 0' <localhost> Attempting python interpreter discovery <localhost.dev> EXEC /bin/sh -c 'echo PLATFORM; uname; echo FOUND; command -v '"'"'/usr/bin/python'"'"'; command -v '"'"'python3.7'"'"'; command -v '"'"'python3.6'"'"'; command -v '"'"'python3.5'"'"'; command -v '"'"'python2.7'"'"'; command -v '"'"'python2.6'"'"'; command -v '"'"'/usr/libexec/platform-python'"'"'; command -v '"'"'/usr/bin/python3'"'"'; command -v '"'"'python'"'"'; echo ENDFOUND && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python && sleep 0' Using module file /usr/lib/python3.8/site-packages/ansible/modules/system/setup.py <localhost.dev> PUT /home/mstudd/.ansible/tmp/ansible-local-234246mzlywzby/tmphl8okmrr TO /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py <localhost.dev> EXEC /bin/sh -c 'chmod u+x /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/ /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python3 /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/AnsiballZ_setup.py && sleep 0' <localhost.dev> EXEC /bin/sh -c 'rm -f -r /home/mstudd/.ansible/tmp/ansible-tmp-1596227662.5343304-234250-22361424934479/ > /dev/null 2>&1 && sleep 0' ok: [localhost] META: ran handlers TASK [community.aws.sqs_queue] ********************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/mstudd/dev/git/ansible/test.yml:5 <localhost.dev> ESTABLISH LOCAL CONNECTION FOR USER: mstudd <localhost.dev> EXEC /bin/sh -c 'echo ~mstudd && sleep 0' <localhost.dev> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/mstudd/.ansible/tmp `"&& mkdir /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761 && echo ansible-tmp-1596227663.4545841-234299-215745550363761="` echo /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761 `" ) && sleep 0' Using module file /home/mstudd/dev/git/ansible/galaxy-roles/ansible_collections/community/aws/plugins/modules/sqs_queue.py <localhost.dev> PUT /home/mstudd/.ansible/tmp/ansible-local-234246mzlywzby/tmpifp2ngt5 TO /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py <localhost.dev> EXEC /bin/sh -c 'chmod u+x /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/ /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py && sleep 0' <localhost.dev> EXEC /bin/sh -c '/usr/bin/python3 /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py && sleep 0' <localhost.dev> EXEC /bin/sh -c 'rm -f -r /home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 102, in <module> _ansiballz_main() File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 94, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py", line 40, in invoke_module runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.sqs_queue', init_globals=None, run_name='__main__', alter_sys=True) File "/usr/lib64/python3.8/runpy.py", line 207, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib64/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib64/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 474, in <module> File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 464, in main File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 311, in create_or_update_sqs_queue File "/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py", line 377, in update_sqs_queue UnboundLocalError: local variable 'existing_value' referenced before assignment fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 102, in <module>\n _ansiballz_main()\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 94, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/mstudd/.ansible/tmp/ansible-tmp-1596227663.4545841-234299-215745550363761/AnsiballZ_sqs_queue.py\", line 40, in invoke_module\n runpy.run_module(mod_name='ansible_collections.community.aws.plugins.modules.sqs_queue', init_globals=None, run_name='__main__', alter_sys=True)\n File \"/usr/lib64/python3.8/runpy.py\", line 207, in run_module\n return _run_module_code(code, init_globals, run_name, mod_spec)\n File \"/usr/lib64/python3.8/runpy.py\", line 97, in _run_module_code\n _run_code(code, mod_globals, init_globals,\n File \"/usr/lib64/python3.8/runpy.py\", line 87, in _run_code\n exec(code, run_globals)\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 474, in <module>\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 464, in main\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 311, in create_or_update_sqs_queue\n File \"/tmp/ansible_community.aws.sqs_queue_payload_vm5yiveu/ansible_community.aws.sqs_queue_payload.zip/ansible_collections/community/aws/plugins/modules/sqs_queue.py\", line 377, in update_sqs_queue\nUnboundLocalError: local variable 'existing_value' referenced before assignment\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } PLAY RECAP ****************************************************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ```
[ { "content": "#!/usr/bin/python\n# Copyright: Ansible Project\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: sqs_queue\nversion_added: 1...
[ { "content": "#!/usr/bin/python\n# Copyright: Ansible Project\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: sqs_queue\nversion_added: 1...
diff --git a/changelogs/fragments/389-sqs-queue-UnboundLocalError.yml b/changelogs/fragments/389-sqs-queue-UnboundLocalError.yml new file mode 100644 index 00000000000..8b1b371428f --- /dev/null +++ b/changelogs/fragments/389-sqs-queue-UnboundLocalError.yml @@ -0,0 +1,2 @@ +bugfixes: +- sqs_queue - fix UnboundLocalError when passing a boolean parameter (https://github.com/ansible-collections/community.aws/issues/172). diff --git a/plugins/modules/sqs_queue.py b/plugins/modules/sqs_queue.py index b0565c6c8d0..b76cdb31410 100644 --- a/plugins/modules/sqs_queue.py +++ b/plugins/modules/sqs_queue.py @@ -375,7 +375,7 @@ def update_sqs_queue(module, client, queue_url): if isinstance(new_value, bool): new_value = str(new_value).lower() - existing_value = str(existing_value).lower() + value = str(value).lower() if new_value == value: continue diff --git a/tests/integration/targets/sqs_queue/tasks/main.yml b/tests/integration/targets/sqs_queue/tasks/main.yml index b689c9eb2b9..483f17bb298 100644 --- a/tests/integration/targets/sqs_queue/tasks/main.yml +++ b/tests/integration/targets/sqs_queue/tasks/main.yml @@ -104,3 +104,25 @@ with_items: - { name: "{{ create_result.name }}" } - { name: "{{ dead_letter_queue.name }}" } + - name: Test FIFO queue + block: + - name: Creating FIFO queue + sqs_queue: + name: "{{ resource_prefix }}{{ 1000 | random }}" + queue_type: fifo + content_based_deduplication: yes + register: create_result + - name: Assert queue created with configuration + assert: + that: + - create_result.changed + always: + - name: Cleaning up queue + sqs_queue: + name: "{{ item.name }}" + state: absent + register: delete_result + retries: 3 + delay: 3 + with_items: + - { name: "{{ create_result.name }}" }
roboflow__supervision-430
Fix `sv.ByteTrack.tracker_id` return value when `sv.Detections` is empty ### Bug When `sv.Detections` is empty (`len(detections) == 0`) `sv.ByteTrack` returns `tracker_id` equal `None`. Correct that behavior, make it more consistent, and return `np.array([], dtype=int)`. ### Fix Add `else` statement here: https://github.com/roboflow/supervision/blob/89c1b63979d43f8ed651a9701ca8333034d0bc07/supervision/tracker/byte_tracker/core.py#L239
[ { "content": "from typing import List, Tuple\n\nimport numpy as np\n\nfrom supervision.detection.core import Detections\nfrom supervision.tracker.byte_tracker import matching\nfrom supervision.tracker.byte_tracker.basetrack import BaseTrack, TrackState\nfrom supervision.tracker.byte_tracker.kalman_filter import...
[ { "content": "from typing import List, Tuple\n\nimport numpy as np\n\nfrom supervision.detection.core import Detections\nfrom supervision.tracker.byte_tracker import matching\nfrom supervision.tracker.byte_tracker.basetrack import BaseTrack, TrackState\nfrom supervision.tracker.byte_tracker.kalman_filter import...
diff --git a/supervision/tracker/byte_tracker/core.py b/supervision/tracker/byte_tracker/core.py index 466b587ea..34a901385 100644 --- a/supervision/tracker/byte_tracker/core.py +++ b/supervision/tracker/byte_tracker/core.py @@ -249,6 +249,8 @@ def update_with_detections(self, detections: Detections) -> Detections: detections.confidence = np.array( [t.score for t in tracks], dtype=np.float32 ) + else: + detections.tracker_id = np.array([], dtype=int) return detections
safe-global__safe-config-service-23
Set port numbers in docker compose via environment variables To provide more flexibility when setting up the ports for a given environment, we should not use static ports in `docker-compose`. Instead those ports should be extracted to the `.env` file.
[ { "content": "import multiprocessing\nimport os\nfrom distutils.util import strtobool\n\nbind = f\"0.0.0.0:{os.getenv('PORT', '8000')}\"\naccesslog = \"-\"\n\nworkers = int(os.getenv(\"WEB_CONCURRENCY\", multiprocessing.cpu_count() * 2))\nthreads = int(os.getenv(\"PYTHON_MAX_THREADS\", 1))\n\nreload = bool(strt...
[ { "content": "import multiprocessing\nimport os\nfrom distutils.util import strtobool\n\nbind = f\"0.0.0.0:{os.getenv('GUNICORN_BIND_PORT', '8000')}\"\naccesslog = \"-\"\n\nworkers = int(os.getenv(\"WEB_CONCURRENCY\", multiprocessing.cpu_count() * 2))\nthreads = int(os.getenv(\"PYTHON_MAX_THREADS\", 1))\n\nrelo...
diff --git a/.env.example b/.env.example index 00e52f0e..77bb7992 100644 --- a/.env.example +++ b/.env.example @@ -28,7 +28,14 @@ ALLOWED_HOSTS=".localhost,127.0.0.1,[::1]" # Be warned that if you change this value you'll need to change 8000 in both # your Dockerfile and in a few spots in docker-compose.yml due to the nature of # how this value can be set (Docker Compose doesn't support nested ENV vars). -#PORT=8000 +GUNICORN_BIND_PORT=8000 + +# The port exposed to the host by the nginx image. +NGINX_HOST_PORT=8080 + +# A directory where the result of executing envsubst is output (default: /etc/nginx/conf.d) +# Used by the nginx docker image in the templating system in order to use the environment variables set +NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx/ # Should the Webpack watcher use polling? Not all Docker hosts support inotify. # If you find your assets aren't updating in development then set this to true. diff --git a/docker-compose.yml b/docker-compose.yml index 12d7f920..cbe6898d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,13 +3,14 @@ version: "3.9" services: nginx: image: nginx:1.20-alpine - hostname: nginx links: - web:web + env_file: + - .env ports: - - "8080:80" + - "${NGINX_HOST_PORT}:80" volumes: - - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + - ./nginx/templates:/etc/nginx/templates depends_on: - web db: @@ -19,13 +20,13 @@ services: volumes: - ./data/db:/var/lib/postgresql/data ports: - - "5432:5432" + - "${POSTGRES_PORT}:${POSTGRES_PORT}" web: build: . tty: true env_file: - .env - command: gunicorn -c python:config.gunicorn config.wsgi -b 0.0.0.0:8000 + command: gunicorn -c python:config.gunicorn config.wsgi -b 0.0.0.0:${GUNICORN_BIND_PORT} working_dir: /app/src depends_on: - db diff --git a/nginx/nginx.conf b/nginx/templates/nginx.conf.template similarity index 97% rename from nginx/nginx.conf rename to nginx/templates/nginx.conf.template index 65b2fdc8..fe7bb236 100644 --- a/nginx/nginx.conf +++ b/nginx/templates/nginx.conf.template @@ -25,7 +25,7 @@ http { # server unix:/run/gunicorn.sock fail_timeout=0; # for a TCP configuration - server web:8000 fail_timeout=0; + server web:${GUNICORN_BIND_PORT} fail_timeout=0; keepalive 32; } diff --git a/src/config/gunicorn.py b/src/config/gunicorn.py index 2bcf450b..e5197757 100644 --- a/src/config/gunicorn.py +++ b/src/config/gunicorn.py @@ -2,7 +2,7 @@ import os from distutils.util import strtobool -bind = f"0.0.0.0:{os.getenv('PORT', '8000')}" +bind = f"0.0.0.0:{os.getenv('GUNICORN_BIND_PORT', '8000')}" accesslog = "-" workers = int(os.getenv("WEB_CONCURRENCY", multiprocessing.cpu_count() * 2))
freqtrade__freqtrade-2082
plot_dataframe.py ## Step 1: Have you search for this issue before posting it? Couldn't find similar issue, so starting a new issue. ## Step 2: Describe your environment * Python Version: Python 3.6.8 * CCXT version: ccxt==1.18.992 * Branch: Master * Last Commit ID: b8713a515e960f1ffadcf1c7ee62c4bee80b506c ## Step 3: Describe the problem: Unable to plot my backtest results. *Explain the problem you have encountered* Executing the following command results in error. Error ### Steps to reproduce: ` Command: python3 scripts/plot_dataframe.py -s EMACrossHTF1h --export EMACrossHTF1h_results.json -p BTC/USDT --datadir user_data/data/binance/ ` ### Observed Results: Error is thrown. ### Relevant code exceptions or logs: ` File "scripts/plot_dataframe.py", line 113, in <module> main(sys.argv[1:]) File "scripts/plot_dataframe.py", line 107, in main plot_parse_args(sysargv) File "scripts/plot_dataframe.py", line 58, in analyse_and_plot_pairs plot_elements = init_plotscript(config) File "/home/ubuntu/freqtrade/freqtrade/plot/plotting.py", line 57, in init_plotscript trades = load_trades(config) File "/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py", line 113, in load_trades return load_backtest_data(Path(config["exportfilename"])) File "/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py", line 33, in load_backtest_data raise ValueError("File {filename} does not exist.") ValueError: File {filename} does not exist. `
[ { "content": "\"\"\"\nHelpers when analyzing backtest data\n\"\"\"\nimport logging\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytz\n\nfrom freqtrade import persistence\nfrom freqtrade.misc import json_load\nfrom freqtrade.persistence import Trade\n\nlog...
[ { "content": "\"\"\"\nHelpers when analyzing backtest data\n\"\"\"\nimport logging\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytz\n\nfrom freqtrade import persistence\nfrom freqtrade.misc import json_load\nfrom freqtrade.persistence import Trade\n\nlog...
diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py index f2356c34b0f..5865d56a7fb 100644 --- a/freqtrade/data/btanalysis.py +++ b/freqtrade/data/btanalysis.py @@ -30,7 +30,7 @@ def load_backtest_data(filename) -> pd.DataFrame: filename = Path(filename) if not filename.is_file(): - raise ValueError("File {filename} does not exist.") + raise ValueError(f"File {filename} does not exist.") with filename.open() as file: data = json_load(file)
projectmesa__mesa-1844
jupyterviz checkbox input change is not propagated
[ { "content": "import threading\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport reacton.ipywidgets as widgets\nimport solara\nfrom matplotlib.figure import Figure\nfrom matplotlib.ticker import MaxNLocator\n\nimport mesa\n\n# Avoid interactive backend\nplt.switch_backend(\"agg\")\n\n\n@solara.c...
[ { "content": "import threading\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport reacton.ipywidgets as widgets\nimport solara\nfrom matplotlib.figure import Figure\nfrom matplotlib.ticker import MaxNLocator\n\nimport mesa\n\n# Avoid interactive backend\nplt.switch_backend(\"agg\")\n\n\n@solara.c...
diff --git a/mesa/experimental/jupyter_viz.py b/mesa/experimental/jupyter_viz.py index 3408ba11c6a..de207bf2926 100644 --- a/mesa/experimental/jupyter_viz.py +++ b/mesa/experimental/jupyter_viz.py @@ -228,6 +228,7 @@ def change_handler(value, name=name): elif input_type == "Checkbox": solara.Checkbox( label=label, + on_value=change_handler, value=options.get("value"), ) else:
hylang__hy-885
Exclamation mark ! is not mangled I noticed that https://github.com/hylang/hyway/blob/master/conway.hy uses "!" in `set!` and `get!`, but Hy doesn't mangle "!" into something else. The variable is added to the module as-is. That means it'll be hard to reach it from normal Python code. Also, hy2py on Hy code with `set!` returns invalid syntax: `def set!(`.
[ { "content": "# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without lim...
[ { "content": "# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without lim...
diff --git a/hy/lex/parser.py b/hy/lex/parser.py index a63be3e33..22aaf26b3 100644 --- a/hy/lex/parser.py +++ b/hy/lex/parser.py @@ -308,6 +308,9 @@ def mangle(p): if p.endswith("?") and p != "?": p = "is_%s" % (p[:-1]) + if p.endswith("!") and p != "!": + p = "%s_bang" % (p[:-1]) + return p obj = ".".join([mangle(part) for part in obj.split(".")]) diff --git a/tests/lex/test_lex.py b/tests/lex/test_lex.py index cc956752c..56ed52ad2 100644 --- a/tests/lex/test_lex.py +++ b/tests/lex/test_lex.py @@ -326,6 +326,24 @@ def test_lex_mangling_qmark(): assert entry == [HySymbol(".is_foo.bar.is_baz")] +def test_lex_mangling_bang(): + """Ensure that identifiers ending with a bang get mangled ok""" + entry = tokenize("foo!") + assert entry == [HySymbol("foo_bang")] + entry = tokenize("!") + assert entry == [HySymbol("!")] + entry = tokenize("im!foo") + assert entry == [HySymbol("im!foo")] + entry = tokenize(".foo!") + assert entry == [HySymbol(".foo_bang")] + entry = tokenize("foo.bar!") + assert entry == [HySymbol("foo.bar_bang")] + entry = tokenize("foo!.bar") + assert entry == [HySymbol("foo_bang.bar")] + entry = tokenize(".foo!.bar.baz!") + assert entry == [HySymbol(".foo_bang.bar.baz_bang")] + + def test_simple_cons(): """Check that cons gets tokenized correctly""" entry = tokenize("(a . b)")[0]
mozilla__bugbug-598
Use new 'everchanged' operator instead of changedafter 1970 Depends on https://bugzilla.mozilla.org/show_bug.cgi?id=1546624.
[ { "content": "# -*- coding: utf-8 -*-\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport argparse\nimport csv\nimport sys\n\nimport requests\n\n\ndef p...
[ { "content": "# -*- coding: utf-8 -*-\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport argparse\nimport csv\nimport sys\n\nimport requests\n\n\ndef p...
diff --git a/scripts/get_type_labels.py b/scripts/get_type_labels.py index 83d482c571..a7a179d95a 100644 --- a/scripts/get_type_labels.py +++ b/scripts/get_type_labels.py @@ -27,8 +27,7 @@ def main(args): "order": "bug_id", "j_top": "OR", "f1": "bug_type", - "o1": "changedafter", - "v1": "1970-01-01", + "o1": "everchanged", "f2": "OP", "f3": "bug_type", "o3": "anyexact",
nipy__nipype-2827
Python 3.4 tests failing on Travis ### Summary Looks like either a pytest or a pytest-xdist problem. Perhaps one of them stopped supporting 3.4. From [#6217.17](https://travis-ci.org/nipy/nipype/jobs/467617939): ``` $ py.test -v --cov nipype --cov-config .coveragerc --cov-report xml:cov.xml -c nipype/pytest.ini --doctest-modules nipype Traceback (most recent call last): File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 510, in load_setuptools_entrypoints plugin = ep.load() File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/pkg_resources/__init__.py", line 2301, in load self.require(*args, **kwargs) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/pkg_resources/__init__.py", line 2324, in require items = working_set.resolve(reqs, env, installer, extras=self.extras) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/pkg_resources/__init__.py", line 859, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.VersionConflict: (pytest 3.0.7 (/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages), Requirement.parse('pytest>=3.6.0')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/virtualenv/python3.4.6/bin/py.test", line 11, in <module> sys.exit(main()) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/config.py", line 47, in main config = _prepareconfig(args, plugins) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/config.py", line 156, in _prepareconfig pluginmanager=pluginmanager, args=args) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 334, in <lambda> _MultiCall(methods, kwargs, hook.spec_opts).execute() File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 613, in execute return _wrapped_call(hook_impl.function(*args), self.execute) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 250, in _wrapped_call wrap_controller.send(call_outcome) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/helpconfig.py", line 32, in pytest_cmdline_parse config = outcome.get_result() File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 279, in get_result raise ex[1].with_traceback(ex[2]) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 265, in __init__ self.result = func() File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute res = hook_impl.function(*args) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/config.py", line 924, in pytest_cmdline_parse self.parse(args) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/config.py", line 1082, in parse self._preparse(args, addopts=addopts) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/config.py", line 1044, in _preparse self.pluginmanager.load_setuptools_entrypoints(entrypoint_name) File "/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages/_pytest/vendored_packages/pluggy.py", line 515, in load_setuptools_entrypoints "Plugin %r could not be loaded: %s!" % (ep.name, e)) _pytest.vendored_packages.pluggy.PluginValidationError: Plugin 'xdist' could not be loaded: (pytest 3.0.7 (/home/travis/virtualenv/python3.4.6/lib/python3.4/site-packages), Requirement.parse('pytest>=3.6.0'))! ``` ### Platform details: Travis. Python 3.4. ### Execution environment Choose one - Travis environment (Python 3.4)
[ { "content": "\"\"\" This file contains defines parameters for nipy that we use to fill\nsettings in setup.py, the nipy top-level docstring, and for building the\ndocs. In setup.py in particular, we exec this file, so it cannot import nipy\n\"\"\"\nfrom __future__ import (print_function, division, unicode_lite...
[ { "content": "\"\"\" This file contains defines parameters for nipy that we use to fill\nsettings in setup.py, the nipy top-level docstring, and for building the\ndocs. In setup.py in particular, we exec this file, so it cannot import nipy\n\"\"\"\nfrom __future__ import (print_function, division, unicode_lite...
diff --git a/nipype/info.py b/nipype/info.py index 1cf361c40c..be6edb713f 100644 --- a/nipype/info.py +++ b/nipype/info.py @@ -108,7 +108,7 @@ def get_nipype_gitversion(): SCIPY_MIN_VERSION = '0.14' TRAITS_MIN_VERSION = '4.6' DATEUTIL_MIN_VERSION = '2.2' -PYTEST_MIN_VERSION = '3.0' +PYTEST_MIN_VERSION = '3.6' FUTURE_MIN_VERSION = '0.16.0' SIMPLEJSON_MIN_VERSION = '3.8.0' PROV_VERSION = '1.5.2'
Chia-Network__chia-blockchain-14904
[Bug] Windows CLI waits for passphrase input but no longer prompts for it in 1.7.1 ### What happened? When using the CLI to start the wallet (or indeed any service) - the prompt `(Unlock Keyring) Passphrase:` is no longer shown until *after* the passphrase is entered. The daemon will display `Starting daemon` and then wait there for the passphrase input. Once the passphrase is entered, the following is shown `(Unlock Keyring) Passphrase: Unlocking daemon keyring` This is a regression in 1.7.1 as it works as expected in 1.7.0 Tested in both cmd and powershell 7.3.2 ### Version 1.7.1 ### What platform are you using? Windows ### What ui mode are you using? CLI ### Relevant log output ```shell N/A ```
[ { "content": "from __future__ import annotations\n\nimport os\nimport sys\nimport time\nfrom getpass import getpass\nfrom io import TextIOWrapper\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple\n\nimport colorama\n\nfrom chia.daemon.client import acquire_connection_to_daemon\nfrom chia....
[ { "content": "from __future__ import annotations\n\nimport os\nimport sys\nimport time\nfrom getpass import getpass\nfrom io import TextIOWrapper\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple\n\nimport colorama\n\nfrom chia.daemon.client import acquire_connection_to_daemon\nfrom chia....
diff --git a/chia/cmds/passphrase_funcs.py b/chia/cmds/passphrase_funcs.py index 98c5fe243c8c..69ca4f14059e 100644 --- a/chia/cmds/passphrase_funcs.py +++ b/chia/cmds/passphrase_funcs.py @@ -91,7 +91,7 @@ def verify_passphrase_meets_requirements( def prompt_for_passphrase(prompt: str) -> str: if sys.platform == "win32" or sys.platform == "cygwin": - print(prompt, end="") + print(prompt, end="", flush=True) prompt = "" return getpass(prompt)
ivy-llc__ivy-18252
broadcast_to
[ { "content": "# global\nimport ivy\nfrom ivy.functional.frontends.paddle.func_wrapper import (\n to_ivy_arrays_and_back,\n)\nfrom ivy.func_wrapper import (\n with_unsupported_dtypes,\n with_supported_dtypes,\n)\n\n\n@to_ivy_arrays_and_back\ndef reshape(x, shape):\n return ivy.reshape(x, shape)\n\n\n...
[ { "content": "# global\nimport ivy\nfrom ivy.functional.frontends.paddle.func_wrapper import (\n to_ivy_arrays_and_back,\n)\nfrom ivy.func_wrapper import (\n with_unsupported_dtypes,\n with_supported_dtypes,\n)\n\n\n@to_ivy_arrays_and_back\ndef reshape(x, shape):\n return ivy.reshape(x, shape)\n\n\n...
diff --git a/ivy/functional/frontends/paddle/tensor/manipulation.py b/ivy/functional/frontends/paddle/tensor/manipulation.py index adb24100b6e7c..7ef098a2c71d3 100644 --- a/ivy/functional/frontends/paddle/tensor/manipulation.py +++ b/ivy/functional/frontends/paddle/tensor/manipulation.py @@ -78,3 +78,12 @@ def squeeze(x, axis=None, name=None): @to_ivy_arrays_and_back def cast(x, dtype): return ivy.astype(x, dtype) + + +@with_supported_dtypes( + {"2.5.0 and below": ("bool", "float32", "float64", "int32", "int64")}, + "paddle", +) +@to_ivy_arrays_and_back +def broadcast_to(x, shape, name=None): + return ivy.broadcast_to(x, shape) diff --git a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_paddle_manipulation.py b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_paddle_manipulation.py index 38fd74caf3c2f..4547de5df1c9a 100644 --- a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_paddle_manipulation.py +++ b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_paddle_manipulation.py @@ -362,3 +362,46 @@ def test_paddle_cast( x=x[0], dtype=dtype[0], ) + + +@st.composite +def _broadcast_to_helper(draw): + dtype_and_x = draw( + helpers.dtype_and_values( + available_dtypes=helpers.get_dtypes("valid"), + min_num_dims=1, + max_num_dims=6, + ) + ) + + dtype, x = dtype_and_x + input_shape = x[0].shape + + max_num_dims = 6 - len(input_shape) + shape = draw(helpers.get_shape(max_num_dims=max_num_dims)) + input_shape + + return dtype, x, shape + + +@handle_frontend_test( + fn_tree="paddle.broadcast_to", + dtype_x_and_shape=_broadcast_to_helper(), +) +def test_paddle_broadcast_to( + *, + dtype_x_and_shape, + on_device, + fn_tree, + frontend, + test_flags, +): + input_dtype, x, shape = dtype_x_and_shape + helpers.test_frontend_function( + input_dtypes=input_dtype, + frontend=frontend, + test_flags=test_flags, + fn_tree=fn_tree, + on_device=on_device, + x=x[0], + shape=shape, + )
cobbler__cobbler-1265
build_reporting fails if empty string in ignorelist The default configuration in the ubuntu 12.04 cobbler 2.6.5 package has the following in `/etc/settings`: ``` build_reporting_ignorelist = [""] ``` The code that reads this value is in `install_post_report.py`, and the condition that determines whether to send a build report email is: ``` for prefix in settings.build_reporting_ignorelist: if name.lower().startswith(prefix) == True: sendmail = False ``` With the default configuration, this check always succeeds, and **mail is not sent**. Fix the issue by modifying the condition to: ``` if prefix != '' and name.lower().startswith(prefix): ```
[ { "content": "# (c) 2008-2009\n# Jeff Schroeder <jeffschroeder@computer.org>\n# Michael DeHaan <michael.dehaan AT gmail>\n#\n# License: GPLv2+\n\n# Post install trigger for cobbler to\n# send out a pretty email report that\n# contains target information.\n\nimport distutils.sysconfig\nimport sys\nimport os\nimp...
[ { "content": "# (c) 2008-2009\n# Jeff Schroeder <jeffschroeder@computer.org>\n# Michael DeHaan <michael.dehaan AT gmail>\n#\n# License: GPLv2+\n\n# Post install trigger for cobbler to\n# send out a pretty email report that\n# contains target information.\n\nimport distutils.sysconfig\nimport sys\nimport os\nimp...
diff --git a/cobbler/modules/install_post_report.py b/cobbler/modules/install_post_report.py index 052dfb149e..4f9401bbfc 100755 --- a/cobbler/modules/install_post_report.py +++ b/cobbler/modules/install_post_report.py @@ -91,7 +91,7 @@ def run(api, args, logger): sendmail = True for prefix in settings.build_reporting_ignorelist: - if name.lower().startswith(prefix) == True: + if prefix != '' and name.lower().startswith(prefix): sendmail = False if sendmail == True:
mathesar-foundation__mathesar-673
IndexError when deleting a column ## Description <!-- A clear and concise description of what the bug is. --> An indexError occurs when deleting a column through the API. Most of the time the error occurs when deleting the first or second column of a table. Deleting the last columns in a table does not seem to produce this error. ## Expected behavior <!-- A clear and concise description of what you expected to happen. --> - A column should be deleted ## To Reproduce <!-- How can we recreate this bug? Please try to provide a Minimal, Complete, and Verifiable (http://stackoverflow.com/help/mcve) example if code-related. --> 1. Delete the first or second column of a table via API. Example: api/v0/tables/1/columns/1/ 2. Delete the first or second column of another table via API. Example: api/v0/tables/2/columns/0/ ## Screenshots ![Screenshot (35)](https://user-images.githubusercontent.com/66047479/133317146-3e4aa024-afc2-4370-9a79-1007549edccd.png) ![Screenshot (36)](https://user-images.githubusercontent.com/66047479/133317195-0da1725a-9895-4ee3-8b18-90b83eda90c4.png) ## Environment - OS: (_eg._ macOS 10.14.6; Fedora 32) - Browser: (_eg._ Safari; Firefox) - Browser Version: (_eg._ 13; 73) - Other info: ## Additional context <!-- Add any other context about the problem or screenshots here. -->
[ { "content": "import warnings\n\nfrom sqlalchemy import Table, MetaData, and_, select, text, func\n\nfrom db.tables.operations.select import reflect_table_from_oid\nfrom db.utils import execute_statement\n\n\ndef get_column_index_from_name(table_oid, column_name, engine, connection_to_use=None):\n with warni...
[ { "content": "import warnings\n\nfrom sqlalchemy import Table, MetaData, and_, select, text, func\n\nfrom db.tables.operations.select import reflect_table_from_oid\nfrom db.utils import execute_statement\n\n\ndef get_column_index_from_name(table_oid, column_name, engine, connection_to_use=None):\n with warni...
diff --git a/db/columns/operations/select.py b/db/columns/operations/select.py index 8b60cc1d2d..800fc2fc88 100644 --- a/db/columns/operations/select.py +++ b/db/columns/operations/select.py @@ -22,6 +22,7 @@ def get_column_index_from_name(table_oid, column_name, engine, connection_to_use sel = ( select(func.count()) .where(and_( + pg_attribute.c.attrelid == table_oid, pg_attribute.c.attisdropped.is_(True), pg_attribute.c.attnum < result, )) diff --git a/db/tests/columns/operations/test_select.py b/db/tests/columns/operations/test_select.py index 2ac469ce1b..2b9aec8790 100644 --- a/db/tests/columns/operations/test_select.py +++ b/db/tests/columns/operations/test_select.py @@ -1,3 +1,5 @@ +from alembic.migration import MigrationContext +from alembic.operations import Operations import pytest from sqlalchemy import String, Integer, Column, Table, MetaData, Sequence, DateTime, func @@ -23,6 +25,63 @@ def test_get_column_index_from_name(engine_with_schema): assert get_column_index_from_name(table_oid, one_name, engine) == 1 +def test_get_column_index_from_name_after_delete(engine_with_schema): + engine, schema = engine_with_schema + table_name = "table_with_columns" + zero_name = "colzero" + one_name = "colone" + two_name = "coltwo" + table = Table( + table_name, + MetaData(bind=engine, schema=schema), + Column(zero_name, Integer), + Column(one_name, String), + Column(two_name, String), + ) + table.create() + with engine.begin() as conn: + op = Operations(MigrationContext.configure(conn)) + op.drop_column(table.name, one_name, schema=schema) + + table_oid = get_oid_from_table(table_name, schema, engine) + assert get_column_index_from_name(table_oid, zero_name, engine) == 0 + assert get_column_index_from_name(table_oid, two_name, engine) == 1 + + +def test_get_column_index_from_name_after_delete_two_tables(engine_with_schema): + engine, schema = engine_with_schema + table_name = "table_with_columns" + zero_name = "colzero" + one_name = "colone" + two_name = "coltwo" + + for suffix in ["1", "2"]: + table = Table( + table_name + suffix, + MetaData(bind=engine, schema=schema), + Column(zero_name + suffix, Integer), + Column(one_name + suffix, String), + Column(two_name + suffix, String), + ) + table.create() + + with engine.begin() as conn: + op = Operations(MigrationContext.configure(conn)) + op.drop_column(table_name + "1", one_name + "1", schema=schema) + + table_oid1 = get_oid_from_table(table_name + "1", schema, engine) + table_oid2 = get_oid_from_table(table_name + "2", schema, engine) + assert all( + [ + get_column_index_from_name(table_oid1, zero_name + "1", engine) == 0, + get_column_index_from_name(table_oid1, two_name + "1", engine) == 1, + get_column_index_from_name(table_oid2, zero_name + "2", engine) == 0, + get_column_index_from_name(table_oid2, one_name + "2", engine) == 1, + get_column_index_from_name(table_oid2, two_name + "2", engine) == 2, + ] + ) + + @pytest.mark.parametrize("filler", [True, False]) @pytest.mark.parametrize("col_type", column_test_dict.keys()) def test_get_column_default(engine_with_schema, filler, col_type):
falconry__falcon-676
Request.client_accepts_msgpack only supports 'application/x-msgpack' The use of the 'x-' prefix is now discouraged for media types. We should update this Request property to also return True for 'application/msgpack', and verify the change with additional tests.
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, so...
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, so...
diff --git a/falcon/request.py b/falcon/request.py index 54be8c069..bd832279b 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -353,7 +353,8 @@ def client_accepts_json(self): @property def client_accepts_msgpack(self): - return self.client_accepts('application/x-msgpack') + return (self.client_accepts('application/x-msgpack') + or self.client_accepts('application/msgpack')) @property def client_accepts_xml(self): diff --git a/tests/test_req_vars.py b/tests/test_req_vars.py index 9e8875448..c71f02e07 100644 --- a/tests/test_req_vars.py +++ b/tests/test_req_vars.py @@ -348,6 +348,12 @@ def test_client_accepts_props(self): self.assertFalse(req.client_accepts_json) self.assertTrue(req.client_accepts_msgpack) + headers = {'Accept': 'application/msgpack'} + req = Request(testing.create_environ(headers=headers)) + self.assertFalse(req.client_accepts_xml) + self.assertFalse(req.client_accepts_json) + self.assertTrue(req.client_accepts_msgpack) + headers = { 'Accept': 'application/json,application/xml,application/x-msgpack' }
frappe__frappe-14120
Problems while using translations via Globe Symbol ## Description / Context information (for bug reports) There are 2 issues - **Issue - 1** While updating translations using Globe Symbol, system generates duplicate rows of translations for records added in Description https://user-images.githubusercontent.com/16986940/132095963-9b747145-cdb8-4972-8cd9-e2dc907b45a3.mp4 <hr/> **Issue - 2** When clicking on the globe button of Item-2, values from the prev edited item (Item-1) are displayed.In order to refresh the correct values of Item-2, page reload is required. https://user-images.githubusercontent.com/16986940/132095967-caefab6a-ff84-45dc-b1ad-50a0ba60e84f.mp4 **Output of `bench version`** We Checked on version-12 and version-13 Problem is consistent for versions ``` Bench 5.5.0 ERPNext: v13.10.0 (version-13) Frappe Framework: v13.10.0 (version-13) ``` ``` Bench 5.5.0 ERPNext: v12.23.0 (version-12) Frappe Framework: v12.20.0 (version-12) ``` ## Steps to reproduce the issue Check Translate On Description field for Item master. <hr/> - vamagithub@gmail.com - seanthankur20@gmail.com
[ { "content": "# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals, print_function\n\nfrom six import iteritems, text_type, string_types, PY2\n\nfrom frappe.utils import cstr\n\n\"\"\"\n\tfrappe.translate\n\t~~~~~~~~~~~~~...
[ { "content": "# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals, print_function\n\nfrom six import iteritems, text_type, string_types, PY2\n\nfrom frappe.utils import cstr\n\n\"\"\"\n\tfrappe.translate\n\t~~~~~~~~~~~~~...
diff --git a/frappe/public/js/frappe/form/controls/base_control.js b/frappe/public/js/frappe/form/controls/base_control.js index 8c2c5c433866..2ee6246393ab 100644 --- a/frappe/public/js/frappe/form/controls/base_control.js +++ b/frappe/public/js/frappe/form/controls/base_control.js @@ -131,7 +131,7 @@ frappe.ui.form.Control = Class.extend({ if (!this.doc.__islocal) { new frappe.views.TranslationManager({ 'df': this.df, - 'source_text': value, + 'source_text': this.value, 'target_language': this.doc.language, 'doc': this.doc }); diff --git a/frappe/translate.py b/frappe/translate.py index 2a27c0361f3d..a600951db907 100644 --- a/frappe/translate.py +++ b/frappe/translate.py @@ -846,6 +846,9 @@ def update_translations_for_source(source=None, translation_dict=None): translation_dict = json.loads(translation_dict) + if is_html(source): + source = strip_html_tags(source) + # for existing records translation_records = frappe.db.get_values('Translation', { 'source_text': source
goauthentik__authentik-3299
Get username from mailcow source **Is your feature request related to a problem? Please describe.** I like to get a username from mailcow. With username the enrollment for new users is more simple. **Describe the solution you'd like** Set username to full_name provided by mailcow oauths source. **Additional context** For other sources the username is also set redundant to another attribute if there is no special source attribute: azure_ad.py: ``` "username": info.get("displayName"), "name": info.get("displayName"), ``` discord.py: ``` "username": info.get("username"), "name": info.get("username"), ``` facebook.py: ``` "username": info.get("name"), "name": info.get("name"), ``` reddit.py ``` "username": info.get("name"), "name": info.get("name"), ```
[ { "content": "\"\"\"Mailcow OAuth Views\"\"\"\nfrom typing import Any, Optional\n\nfrom requests.exceptions import RequestException\nfrom structlog.stdlib import get_logger\n\nfrom authentik.sources.oauth.clients.oauth2 import OAuth2Client\nfrom authentik.sources.oauth.types.manager import MANAGER, SourceType\n...
[ { "content": "\"\"\"Mailcow OAuth Views\"\"\"\nfrom typing import Any, Optional\n\nfrom requests.exceptions import RequestException\nfrom structlog.stdlib import get_logger\n\nfrom authentik.sources.oauth.clients.oauth2 import OAuth2Client\nfrom authentik.sources.oauth.types.manager import MANAGER, SourceType\n...
diff --git a/authentik/sources/oauth/types/mailcow.py b/authentik/sources/oauth/types/mailcow.py index a296b9efaf7b..93999f5d254e 100644 --- a/authentik/sources/oauth/types/mailcow.py +++ b/authentik/sources/oauth/types/mailcow.py @@ -52,6 +52,7 @@ def get_user_enroll_context( info: dict[str, Any], ) -> dict[str, Any]: return { + "username": info.get("full_name"), "email": info.get("email"), "name": info.get("full_name"), }
bookwyrm-social__bookwyrm-1855
Let admins set default interface language Right now, BookWyrm's interface language is determined by, in order of preference: 1. The language selected in the user's settings 2. The language requested by the browser, if it's available in the app 3. English Admin should be able to set the default display language of the interface for logged out viewers and users that don't have a preference saved.
[ { "content": "\"\"\" bookwyrm settings and configuration \"\"\"\nimport os\nfrom environs import Env\n\nimport requests\nfrom django.utils.translation import gettext_lazy as _\n\n\nenv = Env()\nenv.read_env()\nDOMAIN = env(\"DOMAIN\")\nVERSION = \"0.2.0\"\n\nPAGE_LENGTH = env(\"PAGE_LENGTH\", 15)\nDEFAULT_LANGU...
[ { "content": "\"\"\" bookwyrm settings and configuration \"\"\"\nimport os\nfrom environs import Env\n\nimport requests\nfrom django.utils.translation import gettext_lazy as _\n\n\nenv = Env()\nenv.read_env()\nDOMAIN = env(\"DOMAIN\")\nVERSION = \"0.2.0\"\n\nPAGE_LENGTH = env(\"PAGE_LENGTH\", 15)\nDEFAULT_LANGU...
diff --git a/.env.example b/.env.example index 2000a7165c..ca6f65bb78 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,8 @@ USE_HTTPS=true DOMAIN=your.domain.here EMAIL=your@email.here +# Instance defualt language (see options at bookwyrm/settings.py "LANGUAGES" +LANGUAGE_CODE="en-us" # Used for deciding which editions to prefer DEFAULT_LANGUAGE="English" diff --git a/bookwyrm/settings.py b/bookwyrm/settings.py index 197e672c10..e86d279289 100644 --- a/bookwyrm/settings.py +++ b/bookwyrm/settings.py @@ -243,7 +243,7 @@ # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ -LANGUAGE_CODE = "en-us" +LANGUAGE_CODE = env("LANGUAGE_CODE", "en-us") LANGUAGES = [ ("en-us", _("English")), ("de-de", _("Deutsch (German)")),
pytest-dev__pytest-django-820
Test re-ordering breaks Pytest's --failed-first and --stepwise options The test re-ordering introduced in response to #214 seems to execute after pytest's own `--failed-first`, `--new-first`, `--stepwise`, etc. ordering options, breaking them. We ran across this in mdn/kuma#6531, where even with `--failed-first` pytest was running dozens of known good tests before executing the failed tests. Removing the `pytest_collection_modifyitems` function or decorating it with `@pytest.hookimpl(tryfirst=True)` seems to resolve this, though I'm not familiar enough with pytest to know if that's an appropriate solution, or if there's something we should be doing on our end instead.
[ { "content": "\"\"\"A pytest plugin which helps testing Django applications\n\nThis plugin handles creating and destroying the test environment and\ntest database and provides some useful text fixtures.\n\"\"\"\n\nimport contextlib\nimport inspect\nfrom functools import reduce\nimport os\nimport sys\nimport typ...
[ { "content": "\"\"\"A pytest plugin which helps testing Django applications\n\nThis plugin handles creating and destroying the test environment and\ntest database and provides some useful text fixtures.\n\"\"\"\n\nimport contextlib\nimport inspect\nfrom functools import reduce\nimport os\nimport sys\nimport typ...
diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index e54a900ee..4deca87f3 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -415,6 +415,7 @@ def pytest_runtest_setup(item): _disable_class_methods(item.cls) +@pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items): def get_order_number(test): marker_db = test.get_closest_marker('django_db')
CTFd__CTFd-1800
Invalid model identifier https://github.com/CTFd/CTFd/blob/master/CTFd/themes/core/templates/scoreboard.html#L26 This should change depending on the mode of the CTF
[ { "content": "import glob\nimport importlib\nimport os\nfrom collections import namedtuple\n\nfrom flask import current_app as app\nfrom flask import send_file, send_from_directory, url_for\n\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.decorators import admins_only as admins_only_wrapper\nfr...
[ { "content": "import glob\nimport importlib\nimport os\nfrom collections import namedtuple\n\nfrom flask import current_app as app\nfrom flask import send_file, send_from_directory, url_for\n\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.decorators import admins_only as admins_only_wrapper\nfr...
diff --git a/CTFd/plugins/__init__.py b/CTFd/plugins/__init__.py index a53892450..889002d16 100644 --- a/CTFd/plugins/__init__.py +++ b/CTFd/plugins/__init__.py @@ -151,7 +151,6 @@ def get_user_page_menu_bar(): route = p.route else: route = url_for("views.static_html", route=p.route) - print(route) pages.append(Menu(title=p.title, route=route)) return pages diff --git a/CTFd/themes/admin/templates/scoreboard.html b/CTFd/themes/admin/templates/scoreboard.html index 8ff0cc9d0..74f0ad7b1 100644 --- a/CTFd/themes/admin/templates/scoreboard.html +++ b/CTFd/themes/admin/templates/scoreboard.html @@ -29,7 +29,7 @@ <h1>Scoreboard</h1> </div> </th> <th class="sort-col text-center"><b>Place</b></th> - <th class="sort-col"><b>Team</b></th> + <th class="sort-col"><b>{{ get_mode_as_word(capitalize=True) }}</b></th> <th class="sort-col"><b>Score</b></th> <th class="sort-col"><b>Visibility</b></th> </tr> diff --git a/CTFd/themes/core/templates/scoreboard.html b/CTFd/themes/core/templates/scoreboard.html index d657409f9..b0e8ce014 100644 --- a/CTFd/themes/core/templates/scoreboard.html +++ b/CTFd/themes/core/templates/scoreboard.html @@ -23,7 +23,7 @@ <h1>Scoreboard</h1> <thead> <tr> <td scope="col" width="10px"><b>Place</b></td> - <td scope="col"><b>Team</b></td> + <td scope="col"><b>{{ get_mode_as_word(capitalize=True) }}</b></td> <td scope="col"><b>Score</b></td> </tr> </thead>
svthalia__concrexit-2710
Cannot create new shifts: ValueError: 'Shift' instance needs to have a primary key value before this relationship can be used. Sentry Issue: [CONCREXIT-KK](https://sentry.io/organizations/thalia/issues/3788518453/?referrer=github_integration) ``` ValueError: 'Shift' instance needs to have a primary key value before this relationship can be used. (14 additional frame(s) were not displayed) ... File "django/forms/models.py", line 492, in _post_clean self.instance.full_clean(exclude=exclude, validate_unique=False) File "django/db/models/base.py", line 1452, in full_clean self.clean() File "sales/models/shift.py", line 69, in clean if self.orders.filter(created_at__lt=self.start): File "django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "django/db/models/fields/related_descriptors.py", line 687, in get_queryset raise ValueError( ```
[ { "content": "from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count, Q, Sum\nfrom django.db.models.expressions import Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils import timezone\nfrom django.utils.translation import get...
[ { "content": "from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count, Q, Sum\nfrom django.db.models.expressions import Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils import timezone\nfrom django.utils.translation import get...
diff --git a/website/sales/models/shift.py b/website/sales/models/shift.py index 7d71aed94..261990639 100644 --- a/website/sales/models/shift.py +++ b/website/sales/models/shift.py @@ -66,7 +66,7 @@ def clean(self): super().clean() errors = {} - if self.orders.filter(created_at__lt=self.start): + if self.pk is not None and self.orders.filter(created_at__lt=self.start): errors.update( { "start": _(
ivy-llc__ivy-22632
amin
[ { "content": "# global\nimport ivy\nfrom ivy.func_wrapper import with_unsupported_dtypes, with_supported_dtypes\nfrom ivy.functional.frontends.paddle.func_wrapper import to_ivy_arrays_and_back\n\n\n@with_unsupported_dtypes({\"2.5.1 and below\": (\"float16\", \"bfloat16\")}, \"paddle\")\n@to_ivy_arrays_and_back\...
[ { "content": "# global\nimport ivy\nfrom ivy.func_wrapper import with_unsupported_dtypes, with_supported_dtypes\nfrom ivy.functional.frontends.paddle.func_wrapper import to_ivy_arrays_and_back\n\n\n@with_unsupported_dtypes({\"2.5.1 and below\": (\"float16\", \"bfloat16\")}, \"paddle\")\n@to_ivy_arrays_and_back\...
diff --git a/ivy/functional/frontends/paddle/tensor/math.py b/ivy/functional/frontends/paddle/tensor/math.py index 75242ca8e62a4..4df4724f52019 100644 --- a/ivy/functional/frontends/paddle/tensor/math.py +++ b/ivy/functional/frontends/paddle/tensor/math.py @@ -502,3 +502,10 @@ def tanh(x, name=None): @to_ivy_arrays_and_back def trunc(x, name=None): return ivy.trunc(x) + +@with_supported_dtypes( + {"2.5.1 and below": ("float32", "float64", "int32", "int64")}, "paddle" +) +@to_ivy_arrays_and_back +def amin(x, axis=None, keepdim=False, name=None): + return ivy.min(x, axis=axis, keepdims=keepdim) diff --git a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_math.py b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_math.py index 50b4e48de810d..2bac85f674262 100644 --- a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_math.py +++ b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_math.py @@ -2137,3 +2137,36 @@ def test_paddle_stanh( scale_a=scale_a, scale_b=scale_b, ) + + +# amin +@handle_frontend_test( + fn_tree="paddle.tensor.math.amin", + dtype_and_x=helpers.dtype_values_axis( + available_dtypes=helpers.get_dtypes("valid"), + valid_axis=True, + ), + keepdim=st.booleans(), +) +def test_paddle_amin( + *, + dtype_and_x, + keepdim, + on_device, + fn_tree, + backend_fw, + frontend, + test_flags, +): + input_dtype, x, axis = dtype_and_x + helpers.test_frontend_function( + input_dtypes=input_dtype, + frontend=frontend, + backend_to_test=backend_fw, + fn_tree=fn_tree, + test_flags=test_flags, + on_device=on_device, + x=x[0], + axis = axis, + keepdim = keepdim, + )
spack__spack-5099
spack find : always prompt 0 installed packages On a clean `develop` checkout : ``` $ git clone https://github.com/LLNL/spack.git Cloning into 'spack'... remote: Counting objects: 25613, done. remote: Compressing objects: 100% (42/42), done. remote: Total 25613 (delta 12), reused 3 (delta 3), pack-reused 25557 Receiving objects: 100% (25613/25613), 6.65 MiB | 6.46 MiB/s, done. Resolving deltas: 100% (13031/13031), done. Checking connectivity... done. $ cd spack $ . share/spack/setup-env.sh $ spack compilers ==> Available compilers -- gcc ---------------------------------------------------------- gcc@4.8 $ spack install zlib ==> Installing zlib ==> Trying to fetch from file:///home/mculpo/production/spack-mirror/zlib/zlib-1.2.8.tar.gz ######################################################################## 100,0% ==> Staging archive: /home/mculpo/tmp/spack/var/spack/stage/zlib-1.2.8-d6pdl6xvnvap6ihrqcqtgvweghbszmix/zlib-1.2.8.tar.gz ==> Created stage in /home/mculpo/tmp/spack/var/spack/stage/zlib-1.2.8-d6pdl6xvnvap6ihrqcqtgvweghbszmix ==> No patches needed for zlib ==> Building zlib ==> Successfully installed zlib Fetch: 0.01s. Build: 3.69s. Total: 3.70s. [+] /home/mculpo/tmp/spack/opt/spack/linux-x86_64/gcc-4.8/zlib-1.2.8-d6pdl6xvnvap6ihrqcqtgvweghbszmix $ spack find ==> 0 installed packages. $ spack install szip ==> Installing szip ==> Trying to fetch from file:///home/mculpo/production/spack-mirror/szip/szip-2.1.tar.gz ######################################################################## 100,0% ==> Staging archive: /home/mculpo/tmp/spack/var/spack/stage/szip-2.1-esfmhl54wbdb7nnnip6y6jbxlbmxs2jq/szip-2.1.tar.gz ==> Created stage in /home/mculpo/tmp/spack/var/spack/stage/szip-2.1-esfmhl54wbdb7nnnip6y6jbxlbmxs2jq ==> No patches needed for szip ==> Building szip ==> Successfully installed szip Fetch: 0.01s. Build: 8.09s. Total: 8.10s. [+] /home/mculpo/tmp/spack/opt/spack/linux-x86_64/gcc-4.8/szip-2.1-esfmhl54wbdb7nnnip6y6jbxlbmxs2jq $ spack find ==> 0 installed packages. ``` The db seems to be written correctly : ``` database: installs: d6pdl6xvnvap6ihrqcqtgvweghbszmix: explicit: true installed: true path: /home/mculpo/tmp/spack/opt/spack/linux-x86_64/gcc-4.8/zlib-1.2.8-d6pdl6xvnvap6ihrqcqtgvweghbszmix ref_count: 0 spec: zlib: arch: linux-x86_64 compiler: name: gcc version: '4.8' dependencies: {} namespace: builtin parameters: cflags: [] cppflags: [] cxxflags: [] fflags: [] ldflags: [] ldlibs: [] version: 1.2.8 esfmhl54wbdb7nnnip6y6jbxlbmxs2jq: explicit: true installed: true path: /home/mculpo/tmp/spack/opt/spack/linux-x86_64/gcc-4.8/szip-2.1-esfmhl54wbdb7nnnip6y6jbxlbmxs2jq ref_count: 0 spec: szip: arch: linux-x86_64 compiler: name: gcc version: '4.8' dependencies: {} namespace: builtin parameters: cflags: [] cppflags: [] cxxflags: [] fflags: [] ldflags: [] ldlibs: [] version: '2.1' version: 0.9.1 ```
[ { "content": "##############################################################################\n# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n#\n# This file is part of Spack.\n# Created by Todd Gamblin, tgamblin@llnl.gov, All righ...
[ { "content": "##############################################################################\n# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n#\n# This file is part of Spack.\n# Created by Todd Gamblin, tgamblin@llnl.gov, All righ...
diff --git a/var/spack/repos/builtin/packages/h5z-zfp/package.py b/var/spack/repos/builtin/packages/h5z-zfp/package.py index 0063c2fd37d3c1..ddb03c64e0cbaa 100644 --- a/var/spack/repos/builtin/packages/h5z-zfp/package.py +++ b/var/spack/repos/builtin/packages/h5z-zfp/package.py @@ -38,8 +38,7 @@ class H5zZfp(MakefilePackage): variant('fortran', default=True, description='Enable Fortran support') depends_on('hdf5') -# depends_on('zfp bsws=8') - depends_on('zfp') + depends_on('zfp bsws=8') @property def make_defs(self):
buildbot__buildbot-5970
lazylogfiles broken on 3.0.2 I'm upgrading from 0.8.x to 3.0.2, and have this: ```python test_factory = util.BuildFactory() test_factory.addStep(ShellCommand( env={'PATH' : bin_path}, command=["runurl", bb_url + "bb-dependencies.sh"], decodeRC={0 : SUCCESS, 1 : FAILURE, 2 : WARNINGS, 3 : SKIPPED }, haltOnFailure=True, logEnviron=False, lazylogfiles=True, description=["installing dependencies"], descriptionDone=["installed dependencies"])) ``` Which gives me: ``` 2021-03-26 18:38:03+0000 [-] Invalid argument(s) passed to ShellCommand: lazylogfiles ``` According to the 3.0.2 documentation, `lazylogfiles` is a valid parameter for `ShellCommand` http://docs.buildbot.net/3.0.2/manual/configuration/steps/shell_command.html I originally opened a question for this (https://github.com/buildbot/buildbot/discussions/5954) but was told to open a bug instead.
[ { "content": "# This file is part of Buildbot. Buildbot is free software: you can\n# redistribute it and/or modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation, version 2.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n...
[ { "content": "# This file is part of Buildbot. Buildbot is free software: you can\n# redistribute it and/or modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation, version 2.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n...
diff --git a/master/buildbot/newsfragments/shellcommand-lazylogfiles.bugfix b/master/buildbot/newsfragments/shellcommand-lazylogfiles.bugfix new file mode 100644 index 000000000000..d813bd65ddf1 --- /dev/null +++ b/master/buildbot/newsfragments/shellcommand-lazylogfiles.bugfix @@ -0,0 +1 @@ +Re-added support for ``lazylogfiles`` argument of ``ShellCommand`` that was available in old style steps. diff --git a/master/buildbot/steps/shell.py b/master/buildbot/steps/shell.py index d983d4daa4db..8099c030e635 100644 --- a/master/buildbot/steps/shell.py +++ b/master/buildbot/steps/shell.py @@ -182,6 +182,7 @@ def __init__(self, **kwargs): 'maxTime', 'sigtermTime', 'logfiles', + 'lazylogfiles', 'usePTY', 'logEnviron', 'collectStdout', diff --git a/master/buildbot/test/fake/remotecommand.py b/master/buildbot/test/fake/remotecommand.py index dd2487b8f405..152390e25990 100644 --- a/master/buildbot/test/fake/remotecommand.py +++ b/master/buildbot/test/fake/remotecommand.py @@ -21,7 +21,6 @@ from buildbot.process.results import CANCELLED from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS -from buildbot.test.fake import logfile class FakeRemoteCommand: @@ -75,12 +74,47 @@ def run(self, step, conn, builder_name): def useLog(self, log_, closeWhenFinished=False, logfileName=None): if not logfileName: logfileName = log_.getName() + assert logfileName not in self.logs + assert logfileName not in self.delayedLogs self.logs[logfileName] = log_ self._log_close_when_finished[logfileName] = closeWhenFinished def useLogDelayed(self, logfileName, activateCallBack, closeWhenFinished=False): + assert logfileName not in self.logs + assert logfileName not in self.delayedLogs self.delayedLogs[logfileName] = (activateCallBack, closeWhenFinished) + def addStdout(self, data): + if self.collectStdout: + self.stdout += data + if self.stdioLogName is not None and self.stdioLogName in self.logs: + self.logs[self.stdioLogName].addStdout(data) + + def addStderr(self, data): + if self.collectStderr: + self.stderr += data + if self.stdioLogName is not None and self.stdioLogName in self.logs: + self.logs[self.stdioLogName].addStderr(data) + + def addHeader(self, data): + if self.stdioLogName is not None and self.stdioLogName in self.logs: + self.logs[self.stdioLogName].addHeader(data) + + @defer.inlineCallbacks + def addToLog(self, logname, data): + # Activate delayed logs on first data. + if logname in self.delayedLogs: + (activate_callback, close_when_finished) = self.delayedLogs[logname] + del self.delayedLogs[logname] + loog = yield activate_callback(self) + self.logs[logname] = loog + self._log_close_when_finished[logname] = close_when_finished + + if logname in self.logs: + self.logs[logname].addStdout(data) + else: + raise Exception("{}.addToLog: no such log {}".format(self, logname)) + def interrupt(self, why): if not self._waiting_for_interrupt: raise RuntimeError("Got interrupt, but FakeRemoteCommand was not expecting it") @@ -97,12 +131,6 @@ def results(self): def didFail(self): return self.results() == FAILURE - def fakeLogData(self, step, log, header='', stdout='', stderr=''): - # note that this should not be used in the same test as useLog(Delayed) - self.logs[log] = fakelog = logfile.FakeLogFile(log) - self._log_close_when_finished[log] = False - fakelog.fakeData(header=header, stdout=stdout, stderr=stderr) - def set_run_interrupt(self): self._waiting_for_interrupt = True @@ -128,6 +156,9 @@ def __init__(self, workdir, command, env=None, initial_stdin=initialStdin, timeout=timeout, maxTime=maxTime, logfiles=logfiles, usePTY=usePTY, logEnviron=logEnviron) + + if interruptSignal is not None and interruptSignal != 'KILL': + args['interruptSignal'] = interruptSignal super().__init__("shell", args, collectStdout=collectStdout, collectStderr=collectStderr, @@ -235,16 +266,21 @@ def runBehavior(self, behavior, args, command): command.updates.setdefault(args[0], []).append(args[1]) elif behavior == 'log': name, streams = args - if 'header' in streams: - command.logs[name].addHeader(streams['header']) - if 'stdout' in streams: - command.logs[name].addStdout(streams['stdout']) - if command.collectStdout: - command.stdout += streams['stdout'] - if 'stderr' in streams: - command.logs[name].addStderr(streams['stderr']) - if command.collectStderr: - command.stderr += streams['stderr'] + for stream in streams: + if stream not in ['header', 'stdout', 'stderr']: + raise Exception('Log stream {} is not recognized'.format(stream)) + + if name == command.stdioLogName: + if 'header' in streams: + command.addHeader(streams['header']) + if 'stdout' in streams: + command.addStdout(streams['stdout']) + if 'stderr' in streams: + command.addStderr(streams['stderr']) + else: + if 'header' in streams or 'stderr' in streams: + raise Exception('Non stdio streams only support stdout') + return command.addToLog(name, streams['stdout']) elif behavior == 'callable': return defer.maybeDeferred(lambda: args[0](command)) else: @@ -325,7 +361,7 @@ class ExpectShell(Expect): def __init__(self, workdir, command, env=None, want_stdout=1, want_stderr=1, initialStdin=None, timeout=20 * 60, maxTime=None, logfiles=None, - usePTY=None, logEnviron=True): + usePTY=None, logEnviron=True, interruptSignal=None): if env is None: env = {} if logfiles is None: @@ -335,6 +371,8 @@ def __init__(self, workdir, command, env=None, initial_stdin=initialStdin, timeout=timeout, maxTime=maxTime, logfiles=logfiles, usePTY=usePTY, logEnviron=logEnviron) + if interruptSignal is not None: + args['interruptSignal'] = interruptSignal super().__init__("shell", args) def __repr__(self): diff --git a/master/buildbot/test/unit/process/test_buildstep.py b/master/buildbot/test/unit/process/test_buildstep.py index 2836b4ca457d..578e9e3ca981 100644 --- a/master/buildbot/test/unit/process/test_buildstep.py +++ b/master/buildbot/test/unit/process/test_buildstep.py @@ -998,38 +998,17 @@ def test_glob_fail(self): return self.runStep() -class ShellMixinExample(buildstep.ShellMixin, buildstep.BuildStep): - # note that this is straight out of cls-buildsteps.rst - - def __init__(self, cleanupScript='./cleanup.sh', **kwargs): - self.cleanupScript = cleanupScript - kwargs = self.setupShellMixin(kwargs, prohibitArgs=['command']) - super().__init__(**kwargs) - - @defer.inlineCallbacks - def run(self): - cmd = yield self.makeRemoteShellCommand( - command=[self.cleanupScript]) - yield self.runCommand(cmd) - if cmd.didFail(): - cmd = yield self.makeRemoteShellCommand( - command=[self.cleanupScript, '--force'], - logEnviron=False) - yield self.runCommand(cmd) - return cmd.results() - - class SimpleShellCommand(buildstep.ShellMixin, buildstep.BuildStep): - def __init__(self, makeRemoteShellCommandKwargs=None, **kwargs): - self.makeRemoteShellCommandKwargs = makeRemoteShellCommandKwargs or {} + def __init__(self, make_cmd_kwargs=None, prohibit_args=None, **kwargs): + self.make_cmd_kwargs = make_cmd_kwargs or {} - kwargs = self.setupShellMixin(kwargs) + kwargs = self.setupShellMixin(kwargs, prohibitArgs=prohibit_args) super().__init__(**kwargs) @defer.inlineCallbacks def run(self): - cmd = yield self.makeRemoteShellCommand(**self.makeRemoteShellCommandKwargs) + cmd = yield self.makeRemoteShellCommand(**self.make_cmd_kwargs) yield self.runCommand(cmd) return cmd.results() @@ -1048,20 +1027,18 @@ def tearDown(self): return self.tearDownBuildStep() def test_setupShellMixin_bad_arg(self): - mixin = ShellMixinExample() - with self.assertRaisesConfigError( - "invalid ShellMixinExample argument invarg"): + mixin = SimpleShellCommand() + with self.assertRaisesConfigError("invalid SimpleShellCommand argument invarg"): mixin.setupShellMixin({'invarg': 13}) def test_setupShellMixin_prohibited_arg(self): - mixin = ShellMixinExample() - with self.assertRaisesConfigError( - "invalid ShellMixinExample argument logfiles"): + mixin = SimpleShellCommand() + with self.assertRaisesConfigError("invalid SimpleShellCommand argument logfiles"): mixin.setupShellMixin({'logfiles': None}, prohibitArgs=['logfiles']) def test_constructor_defaults(self): - class MySubclass(ShellMixinExample): + class MySubclass(SimpleShellCommand): timeout = 9999 # ShellMixin arg self.assertEqual(MySubclass().timeout, 9999) @@ -1075,121 +1052,180 @@ class MySubclass(ShellMixinExample): ['charming']) @defer.inlineCallbacks - def test_example(self): - self.setupStep(ShellMixinExample(), wantDefaultWorkdir=False) + def test_prohibit_args(self): + self.setupStep(SimpleShellCommand(prohibit_args=['command'], + make_cmd_kwargs={'command': ['cmd', 'arg']})) self.expectCommands( - ExpectShell(workdir='build', command=['./cleanup.sh']) + - Expect.log('stdio', stderr="didn't go so well\n") + - 1, - ExpectShell(workdir='build', command=['./cleanup.sh', '--force'], - logEnviron=False) + + ExpectShell(workdir='wkdir', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_extra_logfile(self): - self.setupStep(ShellMixinExample( - logfiles={'cleanup': 'cleanup.log'}), wantDefaultWorkdir=False) + def test_no_default_workdir(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg']), wantDefaultWorkdir=False) self.expectCommands( - ExpectShell(workdir='build', command=['./cleanup.sh'], - logfiles={'cleanup': 'cleanup.log'}) + - Expect.log('cleanup', stdout='cleaning\ncleaned\n') + + ExpectShell(workdir='build', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() - self.assertEqual(self.step.getLog('cleanup').stdout, - 'cleaning\ncleaned\n') @defer.inlineCallbacks - def test_example_build_workdir(self): - self.setupStep(ShellMixinExample(), wantDefaultWorkdir=False) + def test_build_workdir(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg']), wantDefaultWorkdir=False) self.build.workdir = '/alternate' self.expectCommands( - ExpectShell(workdir='/alternate', command=['./cleanup.sh']) + + ExpectShell(workdir='/alternate', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_build_workdir_callable(self): - self.setupStep(ShellMixinExample(), wantDefaultWorkdir=False) + def test_build_workdir_callable(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg']), wantDefaultWorkdir=False) self.build.workdir = lambda x: '/alternate' self.expectCommands( - ExpectShell(workdir='/alternate', command=['./cleanup.sh']) + + ExpectShell(workdir='/alternate', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_build_workdir_rendereable(self): - self.setupStep(ShellMixinExample(), wantDefaultWorkdir=False) + def test_build_workdir_callable_error(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg']), wantDefaultWorkdir=False) + self.build.workdir = lambda x: x.nosuchattribute # will raise AttributeError + self.expectException(buildstep.CallableAttributeError) + yield self.runStep() + + @defer.inlineCallbacks + def test_build_workdir_renderable(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg']), wantDefaultWorkdir=False) self.build.workdir = properties.Property("myproperty") self.properties.setProperty("myproperty", "/myproperty", "test") self.expectCommands( - ExpectShell(workdir='/myproperty', command=['./cleanup.sh']) + + ExpectShell(workdir='/myproperty', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_build_workdir_callable_attribute_error(self): - self.setupStep(ShellMixinExample(), wantDefaultWorkdir=False) - self.build.workdir = lambda x: x.p # will raise AttributeError - self.expectException(buildstep.CallableAttributeError) + def test_step_workdir(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], workdir='/stepdir')) + self.build.workdir = '/builddir' + self.expectCommands( + ExpectShell(workdir='/stepdir', command=['cmd', 'arg']) + + 0, + ) + self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_step_workdir(self): - self.setupStep(ShellMixinExample(workdir='/alternate')) - self.build.workdir = '/overridden' + def test_step_renderable_workdir(self): + @renderer + def rendered_workdir(_): + return '/stepdir' + + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], workdir=rendered_workdir)) + self.build.workdir = '/builddir' self.expectCommands( - ExpectShell(workdir='/alternate', command=['./cleanup.sh']) + + ExpectShell(workdir='/stepdir', command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() @defer.inlineCallbacks - def test_example_step_renderable_workdir(self): - @renderer - def rendered_workdir(_): - return '/alternate' + def test_step_workdir_overridden(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], workdir='/stepdir', + make_cmd_kwargs={'workdir': '/overridden'})) + self.build.workdir = '/builddir' + self.expectCommands( + ExpectShell(workdir='/overridden', command=['cmd', 'arg']) + + 0, + ) + self.expectOutcome(result=SUCCESS) + yield self.runStep() - self.setupStep(ShellMixinExample(workdir=rendered_workdir)) - self.build.workdir = '/overridden' + @defer.inlineCallbacks + def test_extra_logfile(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], + logfiles={'logname': 'logpath.log'})) self.expectCommands( - ExpectShell(workdir='/alternate', command=['./cleanup.sh']) + + ExpectShell(workdir='wkdir', command=['cmd', 'arg'], + logfiles={'logname': 'logpath.log'}) + + Expect.log('logname', stdout='logline\nlogline2\n') + + Expect.log('stdio', stdout="some log\n") + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() + self.assertEqual(self.step.getLog('logname').stdout, + 'logline\nlogline2\n') @defer.inlineCallbacks - def test_example_override_workdir(self): - # Test that makeRemoteShellCommand(workdir=X) works. - self.setupStep(SimpleShellCommand( - makeRemoteShellCommandKwargs={'workdir': '/alternate'}, - command=['foo', properties.Property('bar', 'BAR')])) + def test_lazy_logfiles_stdout_has_stdout(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], lazylogfiles=True)) self.expectCommands( - ExpectShell(workdir='/alternate', command=['foo', 'BAR']) + + ExpectShell(workdir='wkdir', command=['cmd', 'arg']) + + Expect.log('stdio', stdout="some log\n") + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() + self.assertEqual(self.step.getLog('stdio').stdout, 'some log\n') @defer.inlineCallbacks - def test_example_env(self): - self.setupStep( - ShellMixinExample(env={'BAR': 'BAR'}), wantDefaultWorkdir=False) + def test_lazy_logfiles_stdout_no_stdout(self): + # lazy log files do not apply to stdout + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], lazylogfiles=True)) + self.expectCommands( + ExpectShell(workdir='wkdir', command=['cmd', 'arg']) + + 0, + ) + self.expectOutcome(result=SUCCESS) + yield self.runStep() + self.assertEqual(self.step.getLog('stdio').stdout, '') + + @defer.inlineCallbacks + def test_lazy_logfiles_logfile(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], lazylogfiles=True, + logfiles={'logname': 'logpath.log'})) + self.expectCommands( + ExpectShell(workdir='wkdir', command=['cmd', 'arg'], + logfiles={'logname': 'logpath.log'}) + + Expect.log('logname', stdout='logline\nlogline2\n') + + 0, + ) + self.expectOutcome(result=SUCCESS) + yield self.runStep() + self.assertEqual(self.step.getLog('logname').stdout, + 'logline\nlogline2\n') + + @defer.inlineCallbacks + def test_lazy_logfiles_no_logfile(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], lazylogfiles=True, + logfiles={'logname': 'logpath.log'})) + self.expectCommands( + ExpectShell(workdir='wkdir', command=['cmd', 'arg'], + logfiles={'logname': 'logpath.log'}) + + 0, + ) + self.expectOutcome(result=SUCCESS) + yield self.runStep() + with self.assertRaises(KeyError): + self.step.getLog('logname') + + @defer.inlineCallbacks + def test_env(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], env={'BAR': 'BAR'})) self.build.builder.config.env = {'FOO': 'FOO'} self.expectCommands( - ExpectShell(workdir='build', command=['./cleanup.sh'], + ExpectShell(workdir='wkdir', command=['cmd', 'arg'], env={'FOO': 'FOO', 'BAR': 'BAR'}) + 0, ) @@ -1197,11 +1233,12 @@ def test_example_env(self): yield self.runStep() @defer.inlineCallbacks - def test_example_old_worker(self): - self.setupStep(ShellMixinExample(usePTY=False, interruptSignal='DIE'), - worker_version={'*': "1.1"}, wantDefaultWorkdir=False) + def test_old_worker_args(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], usePTY=False, + interruptSignal='DIE'), + worker_version={'*': "1.1"}) self.expectCommands( - ExpectShell(workdir='build', command=['./cleanup.sh']) + + ExpectShell(workdir='wkdir', command=['cmd', 'arg']) + # note missing parameters 0, ) @@ -1212,25 +1249,24 @@ def test_example_old_worker(self): 'NOTE: worker does not allow master to specify interruptSignal\n') @defer.inlineCallbacks - def test_example_new_worker(self): - self.setupStep(ShellMixinExample(usePTY=False, interruptSignal='DIE'), - worker_version={'*': "3.0"}, wantDefaultWorkdir=False) + def test_new_worker_args(self): + self.setupStep(SimpleShellCommand(command=['cmd', 'arg'], usePTY=False, + interruptSignal='DIE'), + worker_version={'*': "3.0"}) self.expectCommands( - ExpectShell(workdir='build', usePTY=False, command=['./cleanup.sh']) + - # note missing parameters + ExpectShell(workdir='wkdir', usePTY=False, interruptSignal='DIE', + command=['cmd', 'arg']) + 0, ) self.expectOutcome(result=SUCCESS) yield self.runStep() - self.assertEqual(self.step.getLog('stdio').header, - '') + self.assertEqual(self.step.getLog('stdio').header, '') @defer.inlineCallbacks def test_description(self): - self.setupStep(SimpleShellCommand( - command=['foo', properties.Property('bar', 'BAR')]), wantDefaultWorkdir=False) + self.setupStep(SimpleShellCommand(command=['foo', properties.Property('bar', 'BAR')])) self.expectCommands( - ExpectShell(workdir='build', command=['foo', 'BAR']) + + ExpectShell(workdir='wkdir', command=['foo', 'BAR']) + 0, ) self.expectOutcome(result=SUCCESS, state_string="'foo BAR'") diff --git a/master/buildbot/test/unit/steps/test_shell.py b/master/buildbot/test/unit/steps/test_shell.py index 7f84a9a265c2..9cf870b95fb4 100644 --- a/master/buildbot/test/unit/steps/test_shell.py +++ b/master/buildbot/test/unit/steps/test_shell.py @@ -228,7 +228,7 @@ def test_run_misparsed(self): self.expectCommands( ExpectShell(workdir='wkdir', command=['du', '-s', '-k', '.']) - + ExpectShell.log('stdio', stdio='abcdef\n') + + ExpectShell.log('stdio', stdout='abcdef\n') + 0 ) self.expectOutcome(result=WARNINGS, diff --git a/master/buildbot/test/unit/steps/test_shellsequence.py b/master/buildbot/test/unit/steps/test_shellsequence.py index f644256a5830..0463715ea2a5 100644 --- a/master/buildbot/test/unit/steps/test_shellsequence.py +++ b/master/buildbot/test/unit/steps/test_shellsequence.py @@ -21,7 +21,6 @@ from buildbot.process.results import SUCCESS from buildbot.process.results import WARNINGS from buildbot.steps import shellsequence -from buildbot.test.fake.remotecommand import Expect from buildbot.test.fake.remotecommand import ExpectShell from buildbot.test.util import config as configmixin from buildbot.test.util import steps @@ -76,14 +75,12 @@ def testShellArgInput(self): arg.validateAttributes() def testShellArgsAreRendered(self): - arg1 = shellsequence.ShellArg(command=WithProperties('make %s', 'project'), - logname=WithProperties('make %s', 'project')) + arg1 = shellsequence.ShellArg(command=WithProperties('make %s', 'project')) self.setupStep( shellsequence.ShellSequence(commands=[arg1], workdir='build')) self.properties.setProperty("project", "BUILDBOT-TEST", "TEST") - self.expectCommands(ExpectShell(workdir='build', command='make BUILDBOT-TEST') - + 0 + Expect.log('stdio make BUILDBOT-TEST')) + self.expectCommands(ExpectShell(workdir='build', command='make BUILDBOT-TEST') + 0) # TODO: need to factor command-summary stuff into a utility method and # use it here self.expectOutcome(result=SUCCESS, state_string="'make BUILDBOT-TEST'") @@ -114,13 +111,12 @@ def testSanityChecksAreDoneInRuntimeWhenDynamicCmdIsInvalidShellArg(self): def testMultipleCommandsAreRun(self): arg1 = shellsequence.ShellArg(command='make p1') - arg2 = shellsequence.ShellArg(command='deploy p1', logname='deploy') + arg2 = shellsequence.ShellArg(command='deploy p1') self.setupStep( shellsequence.ShellSequence(commands=[arg1, arg2], workdir='build')) self.expectCommands(ExpectShell(workdir='build', command='make p1') + 0, - ExpectShell(workdir='build', command='deploy p1') + 0 + - Expect.log('stdio deploy p1')) + ExpectShell(workdir='build', command='deploy p1') + 0) self.expectOutcome(result=SUCCESS, state_string="'deploy p1'") return self.runStep() @@ -166,16 +162,13 @@ def testShellArgsAreRenderedAnewAtEachBuild(self): This unit test makes sure that ShellArg instances are rendered anew at each new build. """ - arg = shellsequence.ShellArg(command=WithProperties('make %s', 'project'), - logname=WithProperties('make %s', 'project')) + arg = shellsequence.ShellArg(command=WithProperties('make %s', 'project')) step = shellsequence.ShellSequence(commands=[arg], workdir='build') # First "build" self.setupStep(step) self.properties.setProperty("project", "BUILDBOT-TEST-1", "TEST") - self.expectCommands(ExpectShell(workdir='build', - command='make BUILDBOT-TEST-1') + 0 + - Expect.log('stdio make BUILDBOT-TEST-1')) + self.expectCommands(ExpectShell(workdir='build', command='make BUILDBOT-TEST-1') + 0) self.expectOutcome(result=SUCCESS, state_string="'make BUILDBOT-TEST-1'") self.runStep() @@ -183,9 +176,7 @@ def testShellArgsAreRenderedAnewAtEachBuild(self): # Second "build" self.setupStep(step) self.properties.setProperty("project", "BUILDBOT-TEST-2", "TEST") - self.expectCommands(ExpectShell(workdir='build', - command='make BUILDBOT-TEST-2') + 0 + - Expect.log('stdio make BUILDBOT-TEST-2')) + self.expectCommands(ExpectShell(workdir='build', command='make BUILDBOT-TEST-2') + 0) self.expectOutcome(result=SUCCESS, state_string="'make BUILDBOT-TEST-2'") diff --git a/master/buildbot/test/unit/steps/test_source_git.py b/master/buildbot/test/unit/steps/test_source_git.py index 9be4fcb4a46c..8058e897b073 100644 --- a/master/buildbot/test/unit/steps/test_source_git.py +++ b/master/buildbot/test/unit/steps/test_source_git.py @@ -1674,7 +1674,7 @@ def test_mode_incremental_oldworker(self): mode='incremental', progress=True)) self.step.build.getWorkerCommandVersion = lambda cmd, oldversion: "2.15" self.expectCommands( - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', '--version']) + ExpectShell.log('stdio', stdout='git version 1.7.5') @@ -1685,15 +1685,15 @@ def test_mode_incremental_oldworker(self): Expect('stat', dict(file='wkdir/.git', logEnviron=True)) + 0, - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', 'fetch', '-f', '-t', 'http://github.com/buildbot/buildbot.git', 'HEAD', '--progress']) + 0, - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', 'checkout', '-f', 'FETCH_HEAD']) + 0, - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', 'rev-parse', 'HEAD']) + ExpectShell.log('stdio', stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') @@ -2675,7 +2675,7 @@ def test_mode_incremental_no_existing_repo_oldworker(self): mode='incremental')) self.step.build.getWorkerCommandVersion = lambda cmd, oldversion: "2.15" self.expectCommands( - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', '--version']) + ExpectShell.log('stdio', stdout='git version 1.7.5') @@ -2686,12 +2686,12 @@ def test_mode_incremental_no_existing_repo_oldworker(self): Expect('stat', dict(file='wkdir/.git', logEnviron=True)) + 1, - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', 'clone', 'http://github.com/buildbot/buildbot.git', '.', '--progress']) + 0, - ExpectShell(workdir='wkdir', + ExpectShell(workdir='wkdir', interruptSignal='TERM', command=['git', 'rev-parse', 'HEAD']) + ExpectShell.log('stdio', stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d')
googleapis__python-bigquery-745
missing docs for enums: switch to module-based reference docs for enums module There are several enums in https://github.com/googleapis/python-bigquery/blob/master/google/cloud/bigquery/enums.py which are undocumented. I recall we were doing class-based docs mostly because the "jobs" module was too huge to properly browse. It should be safe to use module-based docs for the smaller modules like enums, so we don't have to keep remembering to keep `reference.rst` in sync.
[ { "content": "# -*- coding: utf-8 -*-\n# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless ...
[ { "content": "# -*- coding: utf-8 -*-\n# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless ...
diff --git a/docs/conf.py b/docs/conf.py index cb347160d..09f7ea414 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -110,6 +110,7 @@ # directories to ignore when looking for source files. exclude_patterns = [ "_build", + "**/.nox/**/*", "samples/AUTHORING_GUIDE.md", "samples/CONTRIBUTING.md", "samples/snippets/README.rst", diff --git a/docs/enums.rst b/docs/enums.rst new file mode 100644 index 000000000..57608968a --- /dev/null +++ b/docs/enums.rst @@ -0,0 +1,6 @@ +BigQuery Enums +============== + +.. automodule:: google.cloud.bigquery.enums + :members: + :undoc-members: diff --git a/docs/reference.rst b/docs/reference.rst index 52d916f96..694379cd2 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -173,10 +173,11 @@ Magics Enums ===== -.. autosummary:: - :toctree: generated +.. toctree:: + :maxdepth: 2 + + enums - enums.StandardSqlDataTypes Encryption Configuration ========================
avocado-framework__avocado-4585
Empty distro file with `avocado distro` When running `avocado distro` to generate a definition file as indicated in the manpage, there is a problem and the resulting distro file is empty. ``` $ avocado distro --distro-def-create --distro-def-name avocadix --distro-def-version 1 --distro-def-arch x86_64 --distro-def-type rpm --distro-def-path /mnt/dvd Loading distro information from tree... Please wait... Avocado crashed unexpectedly: a bytes-like object is required, not 'str' You can find details in /home/anguerre/avocado/data/crashes/avocado-traceback-2021-05-12_22:29:25-3_t5qeh8.log ``` ``` $ cat /home/anguerre/avocado/data/crashes/avocado-traceback-2021-05-12_22:29:25-3_t5qeh8.log Avocado crashed: Traceback (most recent call last): File "/usr/bin/avocado", line 11, in <module> load_entry_point('avocado-framework==85.0', 'console_scripts', 'avocado')() File "/usr/lib/python3.6/site-packages/avocado/core/main.py", line 76, in main return app.run() File "/usr/lib/python3.6/site-packages/avocado/core/app.py", line 112, in run return method(self.parser.config) File "/usr/lib/python3.6/site-packages/avocado/plugins/distro.py", line 403, in run save_distro(distro, output_file_name) File "/usr/lib/python3.6/site-packages/avocado/plugins/distro.py", line 237, in save_distro output.write(bz2.compress(linux_distro.to_json())) File "/usr/lib64/python3.6/bz2.py", line 338, in compress return comp.compress(data) + comp.flush() TypeError: a bytes-like object is required, not 'str' ``` And the file `avocadix-1-x86_64.distro` is created empty.
[ { "content": "# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope t...
[ { "content": "# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope t...
diff --git a/avocado/plugins/distro.py b/avocado/plugins/distro.py index ffe339c9a5..15478d031e 100644 --- a/avocado/plugins/distro.py +++ b/avocado/plugins/distro.py @@ -233,8 +233,9 @@ def save_distro(linux_distro, path): :type path: str :return: None """ - with open(path, 'w') as output: - output.write(bz2.compress(linux_distro.to_json())) + with open(path, 'wb') as output: + buff = linux_distro.to_json() + output.write(bz2.compress(buff.encode('utf-8'))) def load_distro(path):
ivy-llc__ivy-23588
ifft2
[ { "content": "# local\nimport ivy\nfrom ivy.functional.frontends.jax.func_wrapper import to_ivy_arrays_and_back\nfrom ivy.func_wrapper import with_unsupported_dtypes\n\n\n@to_ivy_arrays_and_back\ndef fft(a, n=None, axis=-1, norm=None):\n if norm is None:\n norm = \"backward\"\n return ivy.fft(a, ax...
[ { "content": "# local\nimport ivy\nfrom ivy.functional.frontends.jax.func_wrapper import to_ivy_arrays_and_back\nfrom ivy.func_wrapper import with_unsupported_dtypes\n\n\n@to_ivy_arrays_and_back\ndef fft(a, n=None, axis=-1, norm=None):\n if norm is None:\n norm = \"backward\"\n return ivy.fft(a, ax...
diff --git a/ivy/functional/frontends/jax/numpy/fft.py b/ivy/functional/frontends/jax/numpy/fft.py index 0ba0fa31f9c94..8b2d0e17aebf6 100644 --- a/ivy/functional/frontends/jax/numpy/fft.py +++ b/ivy/functional/frontends/jax/numpy/fft.py @@ -41,3 +41,10 @@ def ifft(a, n=None, axis=-1, norm=None): if norm is None: norm = "backward" return ivy.ifft(a, axis, norm=norm, n=n) + + +@to_ivy_arrays_and_back +def ifft2(a, s=None, axes=(-2, -1), norm=None): + if norm is None: + norm = "backward" + return ivy.array(ivy.ifft2(a, s=s, dim=axes, norm=norm), dtype=ivy.dtype(a)) diff --git a/ivy_tests/test_ivy/test_frontends/test_jax/test_numpy/test_fft.py b/ivy_tests/test_ivy/test_frontends/test_jax/test_numpy/test_fft.py index f4fc0911ae534..a13ea4f44bb6d 100644 --- a/ivy_tests/test_ivy/test_frontends/test_jax/test_numpy/test_fft.py +++ b/ivy_tests/test_ivy/test_frontends/test_jax/test_numpy/test_fft.py @@ -163,3 +163,54 @@ def test_jax_numpy_ifft( atol=1e-02, rtol=1e-02, ) + + +# ifft2 +@handle_frontend_test( + fn_tree="jax.numpy.fft.ifft2", + dtype_values=helpers.dtype_and_values( + available_dtypes=helpers.get_dtypes("valid"), + num_arrays=1, + min_value=-1e5, + max_value=1e5, + min_num_dims=2, + max_num_dims=5, + min_dim_size=2, + max_dim_size=5, + allow_inf=False, + large_abs_safety_factor=2.5, + small_abs_safety_factor=2.5, + safety_factor_scale="log", + ), + axes=st.sampled_from([(0, 1), (-1, -2), (1, 0)]), + s=st.tuples( + st.integers(min_value=2, max_value=256), st.integers(min_value=2, max_value=256) + ), + norm=st.sampled_from(["backward", "ortho", "forward", None]), +) +def test_jax_numpy_ifft2( + dtype_values, + s, + axes, + norm, + frontend, + backend_fw, + test_flags, + fn_tree, + on_device, +): + dtype, values = dtype_values + helpers.test_frontend_function( + input_dtypes=dtype, + frontend=frontend, + backend_to_test=backend_fw, + test_flags=test_flags, + fn_tree=fn_tree, + on_device=on_device, + a=values[0], + s=s, + axes=axes, + norm=norm, + atol=1e-02, + rtol=1e-02, + )
PrefectHQ__prefect-2959
Undefined name: make_env in ./server/src/prefect_server/cli/dev.py ## Description *A clear description of the bug* An _undefined name_ like #2235 and #1199 https://github.com/PrefectHQ/prefect/blob/master/server/src/prefect_server/cli/dev.py#L88 `make_env` is an undefined name in this context which will raise a `NameError` at runtime. Should this be `make_dev_env()` defined on line 36 or is `from prefect.cli.server import make_env` the right solution? [flake8](http://flake8.pycqa.org) testing of https://github.com/PrefectHQ/prefect on Python 3.8.3 $ __flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics__ ``` ./server/src/prefect_server/cli/dev.py:88:11: F821 undefined name 'make_env' env = make_env() ^ 1 F821 undefined name 'make_env' 1 ``` https://flake8.pycqa.org/en/latest/user/error-codes.html On the flake8 test selection, this PR does _not_ focus on "_style violations_" (the majority of flake8 error codes that [__psf/black__](https://github.com/psf/black) can autocorrect). Instead these tests are focus on runtime safety and correctness: * E9 tests are about Python syntax errors usually raised because flake8 can not build an Abstract Syntax Tree (AST). Often these issues are a sign of unused code or code that has not been ported to Python 3. These would be compile-time errors in a compiled language but in a dynamic language like Python they result in the script halting/crashing on the user. * F63 tests are usually about the confusion between identity and equality in Python. Use ==/!= to compare str, bytes, and int literals is the classic case. These are areas where __a == b__ is True but __a is b__ is False (or vice versa). Python >= 3.8 will raise SyntaxWarnings on these instances. * F7 tests logic errors and syntax errors in type hints * F82 tests are almost always _undefined names_ which are usually a sign of a typo, missing imports, or code that has not been ported to Python 3. These also would be compile-time errors in a compiled language but in Python a __NameError__ is raised which will halt/crash the script on the user. ## Expected Behavior *What did you expect to happen instead?* ## Reproduction *A minimal example that exhibits the behavior.* ## Environment *Any additional information about your environment* *Optionally run `prefect diagnostics` from the command line and paste the information here*
[ { "content": "# Licensed under the Prefect Community License, available at\n# https://www.prefect.io/legal/prefect-community-license\n\n\nimport glob\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport time\nfrom pathlib import Path\n\nimport click\n\nimport prefect\nimport prefect_server\nfrom ...
[ { "content": "# Licensed under the Prefect Community License, available at\n# https://www.prefect.io/legal/prefect-community-license\n\n\nimport glob\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport time\nfrom pathlib import Path\n\nimport click\n\nimport prefect\nimport prefect_server\nfrom ...
diff --git a/server/src/prefect_server/cli/dev.py b/server/src/prefect_server/cli/dev.py index 440f96e6e5e8..2a6a4fdee5fb 100644 --- a/server/src/prefect_server/cli/dev.py +++ b/server/src/prefect_server/cli/dev.py @@ -85,7 +85,7 @@ def build(version): """ docker_dir = Path(prefect_server.__file__).parents[2] / "docker" - env = make_env() + env = make_dev_env() if "PREFECT_SERVER_TAG" not in env: env.update(PREFECT_SERVER_TAG=version)
gwastro__pycbc-3663
Bug in command line option of pycbc_multi_inspiral code Hi, So I was trying running pycbc_multi_inspiral code with command line option of `injection-f-ref 10 ` and I get this error. ``` ValueError: Issue with option: injection_f_ref Received value: 1 0 If you are supplying a value for all ifos, you must only supply one value. ``` Probing further it turns out this command line option if removed the code did get run. I also pasted the full error below. Just to mention what I was trying is to use pycbc_multi_inspiral code given an injection parameter file. So, I created an injection.hdf file using pycbc_create_injections and I am using templatebank files from previous pygrb successful runs. If further information is needed please tell me. This was full error I received ``` File "pycbc_multi_inspiral", line 118, in <module> opt = parser.parse_args() File "/usr/lib64/python3.6/argparse.py", line 1734, in parse_args args, argv = self.parse_known_args(args, namespace) File "/usr/lib64/python3.6/argparse.py", line 1766, in parse_known_args namespace, args = self._parse_known_args(args, namespace) File "/usr/lib64/python3.6/argparse.py", line 1972, in _parse_known_args start_index = consume_optional(start_index) File "/usr/lib64/python3.6/argparse.py", line 1912, in consume_optional take_action(action, args, option_string) File "/usr/lib64/python3.6/argparse.py", line 1840, in take_action action(self, namespace, argument_values, option_string) File "/home/jam.sadiq/SearchPipeline/env/lib/python3.6/site-packages/PyCBC-0.0a8053-py3.6-linux-x86_64.egg/pycbc/types/optparse.py", line 102, in __call__ raise ValueError(err_msg) ValueError: Issue with option: injection_f_ref Received value: 1 0 If you are supplying a value for all ifos, you must only supply one value. ```
[ { "content": "# Copyright (C) 2015 Ian Harry\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 3 of the License, or (at your\n# option) any later version.\n#\n# This p...
[ { "content": "# Copyright (C) 2015 Ian Harry\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 3 of the License, or (at your\n# option) any later version.\n#\n# This p...
diff --git a/pycbc/types/optparse.py b/pycbc/types/optparse.py index c8299bcfcc2..1ff934c827e 100644 --- a/pycbc/types/optparse.py +++ b/pycbc/types/optparse.py @@ -43,7 +43,7 @@ class MultiDetOptionAction(argparse.Action): def __init__(self, option_strings, dest, - nargs=None, + nargs='+', const=None, default=None, type=None,
scikit-hep__pyhf-941
use short URL for better help message The current help msg has a long url, but this includes line breaks which makes it hard to copy. ``` pyhf cls --help Usage: pyhf cls [OPTIONS] [WORKSPACE] Compute CLs value(s) for a given pyhf workspace. Example: .. code-block:: shell $ curl -sL https://raw.githubusercontent.com/scikit- hep/pyhf/master/docs/examples/json/2-bin_1-channel.json | pyhf cls { "CLs_exp": [ 0.07807427911686156, 0.17472571775474618, 0.35998495263681285, 0.6343568235898907, 0.8809947004472013 ], "CLs_obs": 0.3599845631401915 } Options: --output-file TEXT The location of the output json file. If not specified, prints to screen. --measurement TEXT -p, --patch TEXT --testpoi FLOAT --teststat [q|qtilde] --backend [numpy|pytorch|tensorflow|jax|np|torch|tf] The tensor backend used for the calculation. --optimizer TEXT --optconf EQUAL-DELIMITED OPTION -h, --help Show this message and exit. ```
[ { "content": "\"\"\"The inference CLI group.\"\"\"\nimport logging\n\nimport click\nimport json\n\nfrom ..utils import EqDelimStringParamType\nfrom ..infer import hypotest\nfrom ..workspace import Workspace\nfrom .. import tensor, get_backend, set_backend, optimize\n\nlog = logging.getLogger(__name__)\n\n\n@cli...
[ { "content": "\"\"\"The inference CLI group.\"\"\"\nimport logging\n\nimport click\nimport json\n\nfrom ..utils import EqDelimStringParamType\nfrom ..infer import hypotest\nfrom ..workspace import Workspace\nfrom .. import tensor, get_backend, set_backend, optimize\n\nlog = logging.getLogger(__name__)\n\n\n@cli...
diff --git a/src/pyhf/cli/infer.py b/src/pyhf/cli/infer.py index f6381131b0..db7f624068 100644 --- a/src/pyhf/cli/infer.py +++ b/src/pyhf/cli/infer.py @@ -54,7 +54,9 @@ def cls( .. code-block:: shell - $ curl -sL https://raw.githubusercontent.com/scikit-hep/pyhf/master/docs/examples/json/2-bin_1-channel.json | pyhf cls + $ curl -sL https://git.io/JJYDE | pyhf cls + + \b { "CLs_exp": [ 0.07807427911686156,
roboflow__supervision-901
[Detections] - `from_inference` should include `'class_name'` key in `Detections.data` even if result is empty ### Bug [`from_inference`](https://github.com/roboflow/supervision/blob/0ccb0b85adee4202f5fe96834a374a057bbbd9da/supervision/detection/core.py#L448) should include `'class_name'` key in `Detections.data` even if `roboflow` inference result is empty. ### Environment - Latest version of supervision - macOS ### Minimal Reproducible Example ```python import cv2 import roboflow import numpy as np import supervision as sv from tempfile import NamedTemporaryFile roboflow.login() rf = roboflow.Roboflow() project = rf.workspace().project("people-detection-general") model = project.version(5).model x = np.zeros((1000, 1000, 3), dtype=np.uint8) with NamedTemporaryFile(suffix=".jpeg") as f: cv2.imwrite(f.name, x) result = model.predict(f.name).json() detections = sv.Detections.from_inference(result) print(detections) ``` Here is the result: ``` Detections(xyxy=array([], shape=(0, 4), dtype=float32), mask=None, confidence=array([], dtype=float32), class_id=array([], dtype=int64), tracker_id=None, data={}) ``` Note `data={}` and it should be `data={'class_name': []}`. ### Additional - Note: Please share a Google Colab with minimal code to test the new feature. We know it's additional work, but it will speed up the review process. The reviewer must test each change. Setting up a local environment to do this is time-consuming. Please ensure that Google Colab can be accessed without any issues (make it public). Thank you! 🙏🏻
[ { "content": "from __future__ import annotations\n\nfrom contextlib import suppress\nfrom dataclasses import dataclass, field\nfrom typing import Any, Dict, Iterator, List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES\nfrom superv...
[ { "content": "from __future__ import annotations\n\nfrom contextlib import suppress\nfrom dataclasses import dataclass, field\nfrom typing import Any, Dict, Iterator, List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES\nfrom superv...
diff --git a/supervision/detection/core.py b/supervision/detection/core.py index e727426bf..f170563ca 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -487,7 +487,9 @@ def from_inference(cls, roboflow_result: Union[dict, Any]) -> Detections: ) if np.asarray(xyxy).shape[0] == 0: - return cls.empty() + empty_detection = cls.empty() + empty_detection.data = {CLASS_NAME_DATA_FIELD: np.empty(0)} + return empty_detection return cls( xyxy=xyxy,
ocf__ocfweb-72
Add "edit this page" link on docs? It would link to the GitHub editor page.
[ { "content": "from collections import namedtuple\n\n\nclass Document(namedtuple('Document', ['name', 'title', 'render'])):\n\n @property\n def category(self):\n \"\"\"Return full category path of the document.\n\n For example, \"/\" or \"/staff/backend/\".\n \"\"\"\n return sel...
[ { "content": "from collections import namedtuple\n\n\nclass Document(namedtuple('Document', ['name', 'title', 'render'])):\n\n @property\n def category(self):\n \"\"\"Return full category path of the document.\n\n For example, \"/\" or \"/staff/backend/\".\n \"\"\"\n return sel...
diff --git a/ocfweb/docs/doc.py b/ocfweb/docs/doc.py index 11cb55d6d..6a0022d89 100644 --- a/ocfweb/docs/doc.py +++ b/ocfweb/docs/doc.py @@ -25,3 +25,12 @@ def category_for_sidebar(self): return self.name + '/' else: return self.category + + @property + def edit_url(self): + """Return a GitHub edit URL for this page.""" + return ( + 'https://github.com/ocf/ocfweb/edit/master/ocfweb/docs/docs' + + self.name + + '.md' + ) diff --git a/ocfweb/docs/templates/doc.html b/ocfweb/docs/templates/doc.html index 3ed35ea31..66b06f69b 100644 --- a/ocfweb/docs/templates/doc.html +++ b/ocfweb/docs/templates/doc.html @@ -13,6 +13,13 @@ <div class="col-sm-4 ocf-sidebar"> {% block sidebar %} + <p> + <a class="edit-this-page" href="{{doc.edit_url}}"> + <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> + Edit this Page + </a> + </p> + <hr class="edit-page-border" /> {% doc_toc toc=toc %} <h3>More in this category</h3> diff --git a/ocfweb/static/scss/pages/docs.scss b/ocfweb/static/scss/pages/docs.scss index 601c9ae5e..58916db54 100644 --- a/ocfweb/static/scss/pages/docs.scss +++ b/ocfweb/static/scss/pages/docs.scss @@ -44,6 +44,27 @@ h6 .anchor { font-size: 10px; } + + .edit-this-page { + display: block; + padding: 5px; + font-size: 13px; + + &:hover { + background-color: #f7f7f7; + text-decoration: none; + } + + .glyphicon { + font-size: 10px; + margin-left: 5px; + margin-right: 2px; + } + } + + .edit-page-border { + margin-top: 0; + } } .doc-collapse-toggle {
openfun__marsha-2577
Sending a xAPI statement to a LRS not working anymore ## Bug Report **Problematic Behavior** When a LRS is configured in a consumer site, sending a xapi statement is failing https://gip-fun-mooc.sentry.io/share/issue/081e7857e01544d3bd5b5f93d573c428/ **Expected behavior/code** When a LRS is correctly configured for a given consumer site, the statement should be sent to the LRS. **Steps to Reproduce** 1. Configure a LRS in a consumer site 2. Navigate on an existing video 3. And then the bug happens!
[ { "content": "\"\"\"XAPI module.\"\"\"\n\nimport re\nimport uuid\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.utils.translation import to_locale\n\nimport requests\n\n\ndef get_xapi_statement(resource):\n \"\"\"Return the xapi object statement based on the required reso...
[ { "content": "\"\"\"XAPI module.\"\"\"\n\nimport re\nimport uuid\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.utils.translation import to_locale\n\nimport requests\n\n\ndef get_xapi_statement(resource):\n \"\"\"Return the xapi object statement based on the required reso...
diff --git a/CHANGELOG.md b/CHANGELOG.md index f577955d2f..308b97d08c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed - Remove non existing fields in PortabilityRequestAdmin +- Correctly send xapi statement to a configured LRS ## [4.9.0] - 2023-12-04 diff --git a/src/backend/marsha/core/tests/test_xapi.py b/src/backend/marsha/core/tests/test_xapi.py index 38088cf683..5d76034d08 100644 --- a/src/backend/marsha/core/tests/test_xapi.py +++ b/src/backend/marsha/core/tests/test_xapi.py @@ -1,9 +1,9 @@ """Tests for the xapi module of the Marsha project.""" -from unittest import mock - from django.test import TestCase, override_settings +import responses + from marsha.core.defaults import ENDED, RAW, READY, RUNNING from marsha.core.factories import DocumentFactory, VideoFactory from marsha.core.simple_jwt.factories import LTIPlaylistAccessTokenFactory @@ -12,10 +12,12 @@ XAPIDocumentStatement, XAPIVideoStatement, get_xapi_statement, - requests, ) +# pylint: disable=unexpected-keyword-arg,no-value-for-parameter + + class XAPIVideoStatementTest(TestCase): """Test the XAPIVideoStatement class.""" @@ -684,35 +686,69 @@ def test_xapi_statement_missing_user_id(self): class XAPITest(TestCase): """Test the xapi module.""" - @mock.patch.object(requests, "post") - def test_xapi_enrich_and_send_statement(self, mock_requests_post): + @responses.activate(assert_all_requests_are_fired=True) + def test_xapi_enrich_and_send_statement(self): """XAPI statement sent by the front application should be enriched. Before sending a statement, the xapi module is responsible for enriching it. """ - xapi = XAPI("https://lrs.example.com", "auth_token") - - mock_response = mock.MagicMock() - mock_response.raise_for_status.return_value = 200 - mock_requests_post.return_value = mock_response + xapi = XAPI("https://lrs.example.com", "Basic auth_token") - statement = {"foo": "bar"} - mock_xapi_statement = mock.MagicMock() - mock_xapi_statement.get_statement.return_value = statement + video = VideoFactory( + id="68333c45-4b8c-4018-a195-5d5e1706b838", + playlist__consumer_site__domain="example.com", + title="test video xapi", + ) - xapi.send(mock_xapi_statement) + jwt_token = LTIPlaylistAccessTokenFactory( + session_id="326c0689-48c1-493e-8d2d-9fb0c289de7f", + context_id="course-v1:ufr+mathematics+0001", + user__id="b2584aa405540758db2a6278521b6478", + ) - args, kwargs = mock_requests_post.call_args_list[0] - self.assertEqual(args[0], "https://lrs.example.com") - self.assertEqual( - kwargs["headers"], - { - "Authorization": "auth_token", - "Content-Type": "application/json", - "X-Experience-API-Version": "1.0.3", + base_statement = { + "context": { + "extensions": { + "https://w3id.org/xapi/video/extensions/session-id": "a6151456-18b7-" + "43b4-8452-2037fed588df" + } }, - ) - self.assertEqual(kwargs["json"], statement) + "result": { + "extensions": { + "https://w3id.org/xapi/video/extensions/time-from": 0, + "https://w3id.org/xapi/video/extensions/time-to": 0, + "https://w3id.org/xapi/video/extensions/length": 104.304, + "https://w3id.org/xapi/video/extensions/progress": 0, + "https://w3id.org/xapi/video/extensions/played-segments": "0", + } + }, + "verb": { + "display": {"en-US": "seeked"}, + "id": "https://w3id.org/xapi/video/verbs/seeked", + }, + "id": "17dfcd44-b3e0-403d-ab96-e3ef7da616d4", + } + + xapi_statement = XAPIVideoStatement() + statement = xapi_statement.from_lti(video, base_statement, jwt_token) + + responses.add( + responses.POST, + "https://lrs.example.com", + match=[ + responses.matchers.json_params_matcher(statement), + responses.matchers.header_matcher( + { + "Authorization": "Basic auth_token", + "Content-Type": "application/json", + "X-Experience-API-Version": "1.0.3", + } + ), + ], + status=204, + ) + + xapi.send(statement) class GetXapiStatementTest(TestCase): diff --git a/src/backend/marsha/core/xapi.py b/src/backend/marsha/core/xapi.py index c99bf91df7..dd019c6ebf 100644 --- a/src/backend/marsha/core/xapi.py +++ b/src/backend/marsha/core/xapi.py @@ -344,7 +344,7 @@ def send(self, xapi_statement): response = requests.post( self.url, - json=xapi_statement.get_statement(), + json=xapi_statement, headers=headers, timeout=settings.STAT_BACKEND_TIMEOUT, )
napari__napari-277
blending mode update error ## 🐛 Bug When viewing multiple layers with blending, I am experiencing a bug whereby changing the blending mode doesn't result in an immediate update. The update does occur when I change the opacity (at which point is happens immediately). ![bug](https://user-images.githubusercontent.com/3387500/55253093-aa80cc00-5211-11e9-828c-686595346b86.gif) ## To Reproduce Steps to reproduce the behavior: 1. Open the viewer with multiple layers (e.g. `examples/layers.py`) 2. Reduce the opacity of the top most layer to 0.5 3. Change the blending mode (e.g. `translucent` -> `opaque`) ## Expected behavior The update to what is rendered should happen immediately upon updating the blending mode. ## Environment - napari 0.18 - OS X 10.14.3 - Python version: 3.7.2
[ { "content": "# TODO: create & use our own transform class\nfrom vispy.visuals.transforms import STTransform\nfrom vispy.gloo import get_state_presets\nfrom ...util.event import EmitterGroup, Event\n\n\nclass VisualWrapper:\n \"\"\"Wrapper around ``vispy.scene.VisualNode`` objects.\n Meant to be subclasse...
[ { "content": "# TODO: create & use our own transform class\nfrom vispy.visuals.transforms import STTransform\nfrom vispy.gloo import get_state_presets\nfrom ...util.event import EmitterGroup, Event\n\n\nclass VisualWrapper:\n \"\"\"Wrapper around ``vispy.scene.VisualNode`` objects.\n Meant to be subclasse...
diff --git a/napari/layers/_base_layer/_visual_wrapper.py b/napari/layers/_base_layer/_visual_wrapper.py index 8408ff8b798..18fa23c33ac 100644 --- a/napari/layers/_base_layer/_visual_wrapper.py +++ b/napari/layers/_base_layer/_visual_wrapper.py @@ -124,6 +124,7 @@ def blending(self, blending): f'got {blending}') self._node.set_gl_state(blending) self._blending = blending + self._node.update() self.events.blending() @property
pyqtgraph__pyqtgraph-1066
AttributeError: module 'pyqtgraph.widgets' has no attribute 'RemoteGraphicsView' <!-- In the following, please describe your issue in detail! --> <!-- If some of the sections do not apply, just remove them. --> ### Short description <!-- This should summarize the issue. --> Trying to use RemoteGraphicsView throws an error, says there is no RemoteGraphicsView module ### Code to reproduce <!-- Please provide a minimal working example that reproduces the issue in the code block below. Ideally, this should be a full example someone else could run without additional setup. --> ```python import pyqtgraph as pg import numpy as np view = pg.widgets.RemoteGraphicsView() ``` ### Expected behavior <!-- What should happen? --> Create a RemoteGraphicsView object ### Real behavior <!-- What happens? --> ``` >>> view = pg.widgets.RemoteGraphicsView() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'pyqtgraph.widgets' has no attribute 'RemoteGraphicsView' ``` ### Tested environment(s) * PyQtGraph version: 0.10.0<!-- output of pyqtgraph.__version__ --> * Qt Python binding: PyQt5<!-- output of pyqtgraph.Qt.VERSION_INFO --> * Python version: 3.7.4 * NumPy version: 1.16.4 <!-- output of numpy.__version__ --> * Operating system: Windows 10 * Installation method: pip<!-- e.g. pip, conda, system packages, ... --> ### Additional context If I look in the site-packages folder for pyqtgraph, I can see the RemoteGraphicsView file in the widgets folder, and other widgets load normally
[ { "content": "# -*- coding: utf-8 -*-\n\"\"\"\nPyQtGraph - Scientific Graphics and GUI Library for Python\nwww.pyqtgraph.org\n\"\"\"\n\n__version__ = '0.11.0.dev0'\n\n### import all the goodies and add some helper functions for easy CLI use\n\n## 'Qt' is a local module; it is intended mainly to cover up the dif...
[ { "content": "# -*- coding: utf-8 -*-\n\"\"\"\nPyQtGraph - Scientific Graphics and GUI Library for Python\nwww.pyqtgraph.org\n\"\"\"\n\n__version__ = '0.11.0.dev0'\n\n### import all the goodies and add some helper functions for easy CLI use\n\n## 'Qt' is a local module; it is intended mainly to cover up the dif...
diff --git a/pyqtgraph/__init__.py b/pyqtgraph/__init__.py index aad5c3c801..d2ba61ee52 100644 --- a/pyqtgraph/__init__.py +++ b/pyqtgraph/__init__.py @@ -260,6 +260,7 @@ def renamePyc(startDir): from .widgets.TableWidget import * from .widgets.ProgressDialog import * from .widgets.GroupBox import GroupBox +from .widgets.RemoteGraphicsView import RemoteGraphicsView from .imageview import * from .WidgetGroup import *
tobymao__sqlglot-2365
Support '' to escape single quote character in a string in Redshift dialect **Fully reproducible code snippet** ```python import sqlglot sql_code = """ CREATE TABLE IF NOT EXISTS myschema.mytable ( mycolumn bigint, ) DISTKEY (mycolumn) SORTKEY (mycolumn) ; COMMENT ON COLUMN myschema.mytable.mycolumn IS 'my example = \\'working\\''; COMMENT ON COLUMN myschema.mytable.mycolumn IS 'my example = ''not working'''; """ expressions = sqlglot.parse(sql_code, read="redshift") ``` Error: ```console Traceback (most recent call last): ... raise error sqlglot.errors.ParseError: Invalid expression / Unexpected token. Line 9, Col: 75. column IS 'my example = \'working\''; COMMENT ON COLUMN myschema.mytable.mycolumn IS 'my example = ''not working'''; ``` **Official Documentation** I couldn't find the right documentation on AWS that explains this, but I ran the query on Redshift and it works perfectly.
[ { "content": "from __future__ import annotations\n\nimport typing as t\n\nfrom sqlglot import exp, transforms\nfrom sqlglot.dialects.dialect import (\n concat_to_dpipe_sql,\n concat_ws_to_dpipe_sql,\n rename_func,\n ts_or_ds_to_date_sql,\n)\nfrom sqlglot.dialects.postgres import Postgres\nfrom sqlgl...
[ { "content": "from __future__ import annotations\n\nimport typing as t\n\nfrom sqlglot import exp, transforms\nfrom sqlglot.dialects.dialect import (\n concat_to_dpipe_sql,\n concat_ws_to_dpipe_sql,\n rename_func,\n ts_or_ds_to_date_sql,\n)\nfrom sqlglot.dialects.postgres import Postgres\nfrom sqlgl...
diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py index 2145844ec7..88e4448c12 100644 --- a/sqlglot/dialects/redshift.py +++ b/sqlglot/dialects/redshift.py @@ -83,7 +83,7 @@ def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]: class Tokenizer(Postgres.Tokenizer): BIT_STRINGS = [] HEX_STRINGS = [] - STRING_ESCAPES = ["\\"] + STRING_ESCAPES = ["\\", "'"] KEYWORDS = { **Postgres.Tokenizer.KEYWORDS, diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py index 5f337b0524..ae1b987e0c 100644 --- a/tests/dialects/test_redshift.py +++ b/tests/dialects/test_redshift.py @@ -6,6 +6,11 @@ class TestRedshift(Validator): dialect = "redshift" def test_redshift(self): + self.validate_identity( + "SELECT 'a''b'", + "SELECT 'a\\'b'", + ) + self.validate_all( "x ~* 'pat'", write={
wagtail__wagtail-6433
Change code block style in the docs The colours in our existing code blocks fail WCAG AA on contrast: https://webaim.org/resources/contrastchecker/?fcolor=408090&bcolor=EEFFCC See an example here: https://docs.wagtail.io/en/stable/advanced_topics/performance.html#cache It looks like ``sphinx-rtd-theme`` uses a different style for their own docs: https://sphinx-rtd-theme.readthedocs.io/en/latest/demo/demo.html#code-blocks so maybe we should switch to that.
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Wagtail documentation build configuration file, created by\n# sphinx-quickstart on Tue Jan 14 17:38:55 2014.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in th...
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Wagtail documentation build configuration file, created by\n# sphinx-quickstart on Tue Jan 14 17:38:55 2014.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in th...
diff --git a/docs/conf.py b/docs/conf.py index fbc26a1f7f60..65bd3c605a42 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -115,7 +115,7 @@ #show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = 'default' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = []
mitmproxy__mitmproxy-6382
An error occurred when trying to open a punycode domain #### Problem Description When trying to open a punycode domain, for example https://xn--80afnfom.xn--80ahmohdapg.xn--80asehdb/login, an error occurs in mitmproxy mitmproxy log ``` [13:35:19.966][192.168.20.31:53287] client connect [13:35:20.032][192.168.20.31:53287] server connect мойгаз.смородина.онлайн:443 (194.226.55.22:443) [13:35:20.074] Addon error: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna. Traceback (most recent call last): File "mitmproxy\certs.py", line 271, in dummy_cert File "ipaddress.py", line 54, in ip_address ValueError: 'мойгаз.смородина.онлайн' does not appear to be an IPv4 or IPv6 address During handling of the above exception, another exception occurred: Traceback (most recent call last): File "cryptography\x509\general_name.py", line 84, in __init__ UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "mitmproxy\addons\tlsconfig.py", line 177, in tls_start_client File "mitmproxy\addons\tlsconfig.py", line 516, in get_cert File "mitmproxy\certs.py", line 526, in get_cert File "mitmproxy\certs.py", line 273, in dummy_cert File "cryptography\x509\general_name.py", line 86, in __init__ ValueError: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna. [13:35:20.078][192.168.20.31:53287] No TLS context was provided, failing connection. [13:35:20.079][192.168.20.31:53287] client disconnect [13:35:20.079][192.168.20.31:53287] server disconnect мойгаз.смородина.онлайн:443 (194.226.55.22:443) ``` #### Steps to reproduce the behavior: 1. Open in browser https://xn--80afnfom.xn--80ahmohdapg.xn--80asehdb/login 2. Result ![image](https://github.com/mitmproxy/mitmproxy/assets/4923679/9bf298e3-bcb2-44d9-8b22-aefe123a9be8) #### System ``` Mitmproxy: 10.0.0 binary Python: 3.11.4 OpenSSL: OpenSSL 3.0.7 1 Nov 2022 Platform: Windows-10-10.0.19045-SP0 ```
[ { "content": "import contextlib\nimport datetime\nimport ipaddress\nimport os\nimport re\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import cast\nfrom typing import NewType\nfrom typing import Optional\nfrom typing import Union\n\nimport OpenSSL\nfrom cryptography impor...
[ { "content": "import contextlib\nimport datetime\nimport ipaddress\nimport os\nimport re\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import cast\nfrom typing import NewType\nfrom typing import Optional\nfrom typing import Union\n\nimport OpenSSL\nfrom cryptography impor...
diff --git a/CHANGELOG.md b/CHANGELOG.md index 18b65ab3fd..865390d8ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased: mitmproxy next +* Fix certificate generation for punycode domains. + ([#6382](https://github.com/mitmproxy/mitmproxy/pull/6382), @mhils) ## 24 September 2023: mitmproxy 10.1.0 diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py index 7477c61f78..a260cb9811 100644 --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -270,6 +270,7 @@ def dummy_cert( try: ip = ipaddress.ip_address(x) except ValueError: + x = x.encode("idna").decode() ss.append(x509.DNSName(x)) else: ss.append(x509.IPAddress(ip)) diff --git a/test/mitmproxy/test_certs.py b/test/mitmproxy/test_certs.py index 815a84c613..e46245f1b5 100644 --- a/test/mitmproxy/test_certs.py +++ b/test/mitmproxy/test_certs.py @@ -141,11 +141,17 @@ def test_with_ca(self, tstore): tstore.default_privatekey, tstore.default_ca._cert, "foo.com", - ["one.com", "two.com", "*.three.com", "127.0.0.1"], + ["one.com", "two.com", "*.three.com", "127.0.0.1", "bücher.example"], "Foo Ltd.", ) assert r.cn == "foo.com" - assert r.altnames == ["one.com", "two.com", "*.three.com", "127.0.0.1"] + assert r.altnames == [ + "one.com", + "two.com", + "*.three.com", + "xn--bcher-kva.example", + "127.0.0.1", + ] assert r.organization == "Foo Ltd." r = certs.dummy_cert(
mitmproxy__mitmproxy-1425
Cannot clear flows ##### Steps to reproduce the problem: 1. Start mitmproxy 2. Press z ##### What is the expected behavior? No crash ##### What went wrong? ``` Traceback (most recent call last): File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 515, in run self.loop.run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/media/sf_git/mitmproxy/mitmproxy/console/window.py", line 42, in keypress k = super(self.__class__, self).keypress(size, k) File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/media/sf_git/mitmproxy/mitmproxy/console/flowlist.py", line 361, in keypress self.master.clear_flows() File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 686, in clear_flows self.state.clear() File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 185, in clear marked_flows = [f for f in self.state.view if f.marked] AttributeError: 'ConsoleState' object has no attribute 'state' ``` @dufferzafar, can you fix this? :smiley: Mitmproxy Version: master Operating System: Ubuntu 14.04 x64
[ { "content": "from __future__ import absolute_import, print_function, division\n\nimport mailcap\nimport mimetypes\nimport os\nimport os.path\nimport shlex\nimport signal\nimport stat\nimport subprocess\nimport sys\nimport tempfile\nimport traceback\nimport weakref\n\nimport urwid\nfrom typing import Optional ...
[ { "content": "from __future__ import absolute_import, print_function, division\n\nimport mailcap\nimport mimetypes\nimport os\nimport os.path\nimport shlex\nimport signal\nimport stat\nimport subprocess\nimport sys\nimport tempfile\nimport traceback\nimport weakref\n\nimport urwid\nfrom typing import Optional ...
diff --git a/mitmproxy/console/master.py b/mitmproxy/console/master.py index f7c99ecb9c..db4141471b 100644 --- a/mitmproxy/console/master.py +++ b/mitmproxy/console/master.py @@ -182,7 +182,7 @@ def disable_marked_filter(self): self.mark_filter = False def clear(self): - marked_flows = [f for f in self.state.view if f.marked] + marked_flows = [f for f in self.view if f.marked] super(ConsoleState, self).clear() for f in marked_flows:
sql-machine-learning__elasticdl-1810
Worker occasionally crashes when reports evaluation task result. The error log: ``` status = StatusCode.UNKNOWN details = "Exception calling application: 'NoneType' object has no attribute 'complete_task'" debug_error_string = "{"created":"@1582833503.778925101","description":"Error received from peer ipv4:11.253.195.11:50001","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Exception calling application: 'NoneType' object has no attribute 'complete_task'","grpc_status":2}" ```
[ { "content": "import threading\nimport time\nfrom threading import Thread\n\nfrom elasticdl.proto import elasticdl_pb2\nfrom elasticdl.python.common.evaluation_utils import EvaluationMetrics\nfrom elasticdl.python.common.log_utils import default_logger as logger\nfrom elasticdl.python.common.tensor_utils import...
[ { "content": "import threading\nimport time\nfrom threading import Thread\n\nfrom elasticdl.proto import elasticdl_pb2\nfrom elasticdl.python.common.evaluation_utils import EvaluationMetrics\nfrom elasticdl.python.common.log_utils import default_logger as logger\nfrom elasticdl.python.common.tensor_utils import...
diff --git a/elasticdl/python/master/evaluation_service.py b/elasticdl/python/master/evaluation_service.py index 310e4493a..8cd76131d 100644 --- a/elasticdl/python/master/evaluation_service.py +++ b/elasticdl/python/master/evaluation_service.py @@ -194,6 +194,8 @@ def report_evaluation_metrics(self, model_outputs, labels): ) def complete_task(self): + if self._eval_job is None: + return self._eval_job.complete_task() if self._eval_job.finished(): evaluation_metrics = (
googleapis__python-bigquery-974
Python to construct CASE WHEN update SQL statement I try to update 2K rows in BQ ``` def update_bq_ads_status_failed(self, update_ads): affected_rows = 0 for update_ads_chunk in split(update_ads, _UPDATE_CHUNK_SIZE): ad_ids = [item["ad_id"] for item in update_ads_chunk] removal_errors = [item["removal_error"] for item in update_ads_chunk] update_removal_error = "" for ad_id, removal_error in zip(ad_ids, removal_errors): update_removal_error = update_removal_error + \ f''' WHEN ad_id = '{ad_id}' Then '{removal_error}' ''' affected_rows += self.update_bq_ads_status(f""" UPDATE '{table_full_name}' SET status = 'Failed Removing' SET removal_error = CASE {update_removal_error} END WHERE ad_id IN {str(ad_ids)} """) return affected_rows ``` I'm getting this error. I know it's too vague and not possible to debug like this. > timeout=300.0, headers={'X-Server-Timeout': '300.0', > 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', > 'X-Goog-API-Client': 'gl-python/3.8.10 grpc/1.39.0 gax/2.0.0 > gapic/2.26.0 gccl/2.26.0', 'User-Agent': 'gl-python/3.8.10 grpc/1.39.0 > gax/2.0.0 gapic/2.26.0 gccl/2.26.0'})), last exception: ('Connection > aborted.', RemoteDisconnected('Remote end closed connection without > response')) I'm trying to eliminate errors. Is my BQ update syntactically correct? What's the BQ update timeout?
[ { "content": "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicabl...
[ { "content": "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicabl...
diff --git a/google/cloud/bigquery/retry.py b/google/cloud/bigquery/retry.py index 830582322..8a86973cd 100644 --- a/google/cloud/bigquery/retry.py +++ b/google/cloud/bigquery/retry.py @@ -60,7 +60,7 @@ def _should_retry(exc): pass ``retry=bigquery.DEFAULT_RETRY.with_deadline(30)``. """ -DEFAULT_TIMEOUT = 5.0 * 60.0 +DEFAULT_TIMEOUT = None """The default API timeout. This is the time to wait per request. To adjust the total wait time, set a
docker__docker-py-1709
.dockerignore does not work with patterns begin with slash docker version: ``` docker -v Docker version 17.03.1-ce, build c6d412e ``` reproduce: ``` mkdir app cd app mkdir foo touch foo/bar echo '/foo/bar' > .dockerignore printf 'FROM alpine:3.1\nWORKDIR /app\nCOPY . .\n' > Dockerfile docker build -t app . docker run --rm app find foo ``` output: ``` foo foo/bar ``` It seems the statement from [the official document](https://docs.docker.com/engine/reference/builder/#dockerignore-file) below is not correct: > For example, the patterns `/foo/bar` and `foo/bar` both exclude a file or directory named `bar` in the `foo` subdirectory of `PATH` or in the root of the git repository located at `URL`. We should either amend the document or fix the bug.
[ { "content": "import os\n\nfrom ..constants import IS_WINDOWS_PLATFORM\nfrom .fnmatch import fnmatch\nfrom .utils import create_archive\n\n\ndef tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):\n root = os.path.abspath(path)\n exclude = exclude or []\n\n return create_archive(\n ...
[ { "content": "import os\n\nfrom ..constants import IS_WINDOWS_PLATFORM\nfrom .fnmatch import fnmatch\nfrom .utils import create_archive\n\n\ndef tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):\n root = os.path.abspath(path)\n exclude = exclude or []\n\n return create_archive(\n ...
diff --git a/docker/utils/build.py b/docker/utils/build.py index 79b72495d..d4223e749 100644 --- a/docker/utils/build.py +++ b/docker/utils/build.py @@ -26,6 +26,7 @@ def exclude_paths(root, patterns, dockerfile=None): if dockerfile is None: dockerfile = 'Dockerfile' + patterns = [p.lstrip('/') for p in patterns] exceptions = [p for p in patterns if p.startswith('!')] include_patterns = [p[1:] for p in exceptions] diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 7045d23c2..4a391facb 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -768,6 +768,11 @@ def test_single_subdir_single_filename(self): self.all_paths - set(['foo/a.py']) ) + def test_single_subdir_single_filename_leading_slash(self): + assert self.exclude(['/foo/a.py']) == convert_paths( + self.all_paths - set(['foo/a.py']) + ) + def test_single_subdir_with_path_traversal(self): assert self.exclude(['foo/whoops/../a.py']) == convert_paths( self.all_paths - set(['foo/a.py'])
optuna__optuna-5056
Use `__future__.annotations` everywhere in the Optuna code base ### Motivation Optuna drops Python 3.6 from v3.1, so we can use `__future__.annotations`, which simplifies the code base. See [PEP 563](https://peps.python.org/pep-0563/), [PEP584](https://peps.python.org/pep-0584/), [PEP 585](https://peps.python.org/pep-0585/), and [PEP 604](https://peps.python.org/pep-0604/) for more details. This issue suggests to use the module and simplifies the code base. ### Suggestion Use `__future__.annotations` for each file and simplify the type annotations. The list of classes whose type annotations can be simplified is [here](https://peps.python.org/pep-0585/#implementation). The list of files where the `__future__.annotations` can be used is as follows. In order to reduce review costs and to encourage more contributors to work on it, please, as a rule, fix one file per PR. - [x] optuna/_convert_positional_args.py - [x] optuna/visualization/_optimization_history.py - [x] optuna/visualization/_hypervolume_history.py - [x] optuna/visualization/_edf.py - [x] optuna/visualization/_pareto_front.py - [x] optuna/visualization/matplotlib/_optimization_history.py - [x] optuna/visualization/matplotlib/_hypervolume_history.py - [x] optuna/visualization/matplotlib/_edf.py - [x] optuna/visualization/matplotlib/_pareto_front.py - [x] optuna/visualization/matplotlib/_contour.py - [x] optuna/visualization/_utils.py - [x] optuna/logging.py - [ ] optuna/storages/_base.py - [ ] optuna/storages/_cached_storage.py - [ ] optuna/storages/__init__.py - [ ] optuna/storages/_heartbeat.py - [ ] optuna/storages/_in_memory.py - [ ] optuna/storages/_rdb/models.py - [ ] optuna/storages/_rdb/storage.py - [ ] optuna/storages/_rdb/alembic/versions/v3.0.0.c.py - [ ] optuna/storages/_rdb/alembic/versions/v3.0.0.d.py - [ ] optuna/storages/_rdb/alembic/versions/v3.0.0.a.py - [ ] optuna/storages/_journal/file.py - [ ] optuna/storages/_journal/redis.py - [ ] optuna/storages/_journal/storage.py - [ ] optuna/storages/_journal/base.py - [ ] optuna/study/_dataframe.py - [ ] optuna/study/_optimize.py - [ ] optuna/study/_tell.py - [ ] optuna/study/_multi_objective.py - [ ] optuna/study/_frozen.py - [ ] optuna/study/study.py - [ ] optuna/study/_study_summary.py - [ ] optuna/search_space/group_decomposed.py - [ ] optuna/search_space/intersection.py - [ ] optuna/_typing.py - [ ] optuna/_deprecated.py - [ ] optuna/pruners/_hyperband.py - [ ] optuna/pruners/_patient.py - [ ] optuna/pruners/_successive_halving.py - [ ] optuna/pruners/_percentile.py - [ ] optuna/pruners/_threshold.py - [ ] optuna/trial/_base.py - [ ] optuna/trial/_fixed.py - [ ] optuna/trial/_trial.py - [ ] optuna/trial/_frozen.py - [ ] optuna/integration/cma.py - [ ] optuna/integration/shap.py - [ ] optuna/integration/lightgbm.py - [ ] optuna/integration/pytorch_distributed.py - [ ] optuna/integration/_lightgbm_tuner/optimize.py - [ ] optuna/integration/_lightgbm_tuner/alias.py - [ ] optuna/integration/mlflow.py - [ ] optuna/integration/wandb.py - [ ] optuna/integration/catboost.py - [ ] optuna/integration/skopt.py - [ ] optuna/integration/botorch.py - [ ] optuna/integration/dask.py - [x] optuna/integration/sklearn.py - [ ] optuna/integration/tensorboard.py - [ ] optuna/terminator/callback.py - [ ] optuna/terminator/terminator.py - [ ] optuna/terminator/improvement/_preprocessing.py - [ ] optuna/terminator/improvement/gp/botorch.py - [ ] optuna/terminator/improvement/gp/base.py - [ ] optuna/terminator/improvement/evaluator.py - [ ] optuna/importance/_base.py - [ ] optuna/importance/_mean_decrease_impurity.py - [ ] optuna/importance/__init__.py - [ ] optuna/importance/_fanova/_fanova.py - [ ] optuna/importance/_fanova/_evaluator.py - [ ] optuna/importance/_fanova/_tree.py - [ ] optuna/_imports.py - [ ] optuna/testing/tempfile_pool.py - [ ] optuna/testing/threading.py - [ ] optuna/testing/distributions.py - [ ] optuna/testing/samplers.py - [ ] optuna/testing/storages.py - [ ] optuna/distributions.py - [ ] optuna/cli.py - [ ] optuna/multi_objective/visualization/_pareto_front.py - [ ] optuna/multi_objective/trial.py - [ ] optuna/multi_objective/samplers/_base.py - [ ] optuna/multi_objective/samplers/_nsga2.py - [ ] optuna/multi_objective/samplers/_adapter.py - [ ] optuna/multi_objective/samplers/_random.py - [ ] optuna/multi_objective/samplers/_motpe.py - [ ] optuna/multi_objective/study.py - [ ] optuna/_experimental.py - [ ] optuna/samplers/_base.py - [ ] optuna/samplers/nsgaii/_crossovers/_undx.py - [ ] optuna/samplers/nsgaii/_crossovers/_spx.py - [ ] optuna/samplers/nsgaii/_crossovers/_sbx.py - [ ] optuna/samplers/nsgaii/_crossovers/_vsbx.py - [ ] optuna/samplers/nsgaii/_sampler.py - [ ] optuna/samplers/nsgaii/_crossover.py - [ ] optuna/samplers/_search_space/intersection.py - [ ] optuna/samplers/_qmc.py - [ ] optuna/samplers/_tpe/probability_distributions.py - [ ] optuna/samplers/_tpe/_truncnorm.py - [ ] optuna/samplers/_tpe/multi_objective_sampler.py - [ ] optuna/samplers/_tpe/parzen_estimator.py - [ ] optuna/samplers/_tpe/sampler.py - [ ] optuna/samplers/_random.py - [ ] optuna/samplers/_cmaes.py - [ ] optuna/samplers/_partial_fixed.py - [ ] optuna/samplers/_brute_force.py - [ ] optuna/samplers/_nsgaiii.py - [ ] optuna/samplers/_grid.py - [ ] optuna/_hypervolume/wfg.py - [ ] optuna/_hypervolume/hssp.py - [ ] optuna/progress_bar.py - [ ] optuna/_transform.py - [ ] optuna/_callbacks.py - [ ] tests/multi_objective_tests/test_study.py - [ ] tests/multi_objective_tests/samplers_tests/test_motpe.py - [ ] tests/multi_objective_tests/samplers_tests/test_nsga2.py - [ ] tests/multi_objective_tests/test_trial.py - [ ] tests/multi_objective_tests/visualization_tests/test_pareto_front.py - [ ] tests/trial_tests/test_frozen.py - [ ] tests/trial_tests/test_trials.py - [ ] tests/trial_tests/test_trial.py - [ ] tests/pruners_tests/test_percentile.py - [ ] tests/pruners_tests/test_median.py - [ ] tests/pruners_tests/test_patient.py - [ ] tests/pruners_tests/test_successive_halving.py - [ ] tests/study_tests/test_optimize.py - [ ] tests/study_tests/test_study.py - [ ] tests/hypervolume_tests/test_hssp.py - [x] tests/integration_tests/test_skopt.py - [x] tests/integration_tests/test_pytorch_lightning.py - [ ] tests/integration_tests/test_shap.py - [ ] tests/integration_tests/test_cma.py - [ ] tests/integration_tests/test_pytorch_distributed.py - [ ] tests/integration_tests/lightgbm_tuner_tests/test_optimize.py - [ ] tests/integration_tests/lightgbm_tuner_tests/test_alias.py - [ ] tests/integration_tests/test_botorch.py - [ ] tests/integration_tests/test_mlflow.py - [ ] tests/integration_tests/test_mxnet.py - [ ] tests/integration_tests/test_wandb.py - [ ] tests/importance_tests/fanova_tests/test_tree.py - [ ] tests/importance_tests/test_mean_decrease_impurity.py - [ ] tests/importance_tests/test_fanova.py - [ ] tests/importance_tests/test_init.py - [ ] tests/test_convert_positional_args.py - [ ] tests/test_deprecated.py - [ ] tests/storages_tests/test_journal.py - [ ] tests/storages_tests/test_heartbeat.py - [ ] tests/storages_tests/test_storages.py - [ ] tests/storages_tests/rdb_tests/test_storage.py - [ ] tests/storages_tests/rdb_tests/create_db.py - [ ] tests/storages_tests/test_with_server.py - [ ] tests/samplers_tests/test_grid.py - [ ] tests/samplers_tests/tpe_tests/test_parzen_estimator.py - [ ] tests/samplers_tests/tpe_tests/test_multi_objective_sampler.py - [ ] tests/samplers_tests/tpe_tests/test_sampler.py - [ ] tests/samplers_tests/test_cmaes.py - [ ] tests/samplers_tests/test_samplers.py - [x] tests/samplers_tests/test_nsgaii.py - [x] tests/samplers_tests/test_nsgaiii.py - [ ] tests/samplers_tests/test_qmc.py - [ ] tests/test_distributions.py - [ ] tests/test_multi_objective.py - [ ] tests/test_cli.py - [ ] tests/visualization_tests/test_hypervolume_history.py - [ ] tests/visualization_tests/test_pareto_front.py - [ ] tests/terminator_tests/improvement_tests/test_evaluator.py - [ ] benchmarks/kurobako/problems/wfg/transformation_functions.py - [ ] benchmarks/bayesmark/report_bayesmark.py - [ ] benchmarks/bayesmark/optuna_optimizer.py ### Additional context (optional) The above list is generated by the following script. <details> <summary>script</summary> ```python import os import pathlib PATTERS = [ "from typing import Union", "from typing import Optional", "from typing import Tuple", "from typing import List", "from typing import Dict", "from typing import Set", "from typing import FrozenSet", "from typing import Type", "from typing import FrozenSet", "from typing import Sequence", ] def get_filenames_to_be_simplified(dir_path): ret = [] for f in os.listdir(dir_path): file_path = os.path.join(dir_path, f) if not os.path.isfile(file_path): ret.extend(get_filenames_to_be_simplified(file_path)) else: try: with open(file_path) as fd: contents = fd.read() if any([s in contents for s in PATTERS]): ret.append(str(file_path)) except UnicodeDecodeError as e: pass return ret def main(): dirs = ["optuna", "tests", "benchmarks"] for dir_name in dirs: filenames = get_filenames_to_be_simplified(pathlib.Path(dir_name)) for filename in filenames: print(f"- [ ] {filename}") if __name__ == "__main__": main() ``` </details>
[ { "content": "from __future__ import annotations\n\nfrom typing import Callable\nfrom typing import Sequence\n\nfrom optuna._experimental import experimental_func\nfrom optuna.logging import get_logger\nfrom optuna.study import Study\nfrom optuna.trial import FrozenTrial\nfrom optuna.visualization._edf import _...
[ { "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\nfrom collections.abc import Sequence\n\nfrom optuna._experimental import experimental_func\nfrom optuna.logging import get_logger\nfrom optuna.study import Study\nfrom optuna.trial import FrozenTrial\nfrom optuna.visualiza...
diff --git a/optuna/visualization/matplotlib/_edf.py b/optuna/visualization/matplotlib/_edf.py index ee138b9149..3625dbbe70 100644 --- a/optuna/visualization/matplotlib/_edf.py +++ b/optuna/visualization/matplotlib/_edf.py @@ -1,7 +1,7 @@ from __future__ import annotations -from typing import Callable -from typing import Sequence +from collections.abc import Callable +from collections.abc import Sequence from optuna._experimental import experimental_func from optuna.logging import get_logger
ivy-llc__ivy-19363
T
[ { "content": "# global\n\n# local\nimport ivy\nimport ivy.functional.frontends.jax as jax_frontend\n\n\nclass DeviceArray:\n def __init__(self, array, weak_type=False):\n self._ivy_array = array if isinstance(array, ivy.Array) else ivy.array(array)\n self.weak_type = weak_type\n\n def __repr...
[ { "content": "# global\n\n# local\nimport ivy\nimport ivy.functional.frontends.jax as jax_frontend\n\n\nclass DeviceArray:\n def __init__(self, array, weak_type=False):\n self._ivy_array = array if isinstance(array, ivy.Array) else ivy.array(array)\n self.weak_type = weak_type\n\n def __repr...
diff --git a/ivy/functional/frontends/jax/devicearray.py b/ivy/functional/frontends/jax/devicearray.py index b04cecb8a1095..dabd2464a1f7a 100644 --- a/ivy/functional/frontends/jax/devicearray.py +++ b/ivy/functional/frontends/jax/devicearray.py @@ -41,6 +41,10 @@ def shape(self): def at(self): return jax_frontend._src.numpy.lax_numpy._IndexUpdateHelper(self.ivy_array) + @property + def T(self): + return self.ivy_array.T + # Instance Methods # # ---------------- # diff --git a/ivy_tests/test_ivy/test_frontends/test_jax/test_devicearray.py b/ivy_tests/test_ivy/test_frontends/test_jax/test_devicearray.py index a2401a4c69a30..9089fbb60a565 100644 --- a/ivy_tests/test_ivy/test_frontends/test_jax/test_devicearray.py +++ b/ivy_tests/test_ivy/test_frontends/test_jax/test_devicearray.py @@ -59,6 +59,30 @@ def test_jax_devicearray_property_shape( assert x.shape == shape +@st.composite +def _transpose_helper(draw): + dtype_x = draw( + helpers.dtype_and_values( + available_dtypes=helpers.get_dtypes("valid", prune_function=False), + min_num_dims=2, + max_num_dims=2, + min_dim_size=2, + ) + ) + + _, data = dtype_x + x = data[0] + xT = np.transpose(x) + return x, xT + + +@given(x_transpose=_transpose_helper()) +def test_jax_devicearray_property_T(x_transpose): + x, xT = x_transpose + x = DeviceArray(x) + assert np.array_equal(x.T, xT) + + @st.composite def _at_helper(draw): _, data, shape = draw(
OpenMined__PySyft-676
Implement rsqrt Functionality in FloatTensor with CPU/GPU Backend Support ### User Story: As a Data Scientist using PySyft's FloatTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the rsqrt() should be added to our FloatTensor class with the appropriate functionality, returning a new tensor. Furthermore, the function should automatically determine which backend to use (CPU/GPU) based on where the data is located. If the data is located on the CPU, a performant CPU implementation should run but if the data for a given FloatTensor is located on a GPU, it should be run using an HLSL kernel where appropriate. Obviously, if no GPU is available, it should automatically fall back to the CPU implementation. ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensor.ShaderOps](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Tensor/FloatTensor.ShaderOps.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Math/Shaders/FloatTensorShaders.compute), and [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined.Tests/Editor/FloatTensorTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] an integration test in PySyft demonstrating the correct CPU and GPU operation implemented over a FloatTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
[ { "content": "import zmq\nimport uuid\n\n\nclass FloatTensor():\n\n def __init__(self, controller, data, data_is_pointer=False, verbose=False):\n self.verbose = verbose\n self.controller = controller\n if(data is not None and not data_is_pointer):\n data = data.astype('float')...
[ { "content": "import zmq\nimport uuid\n\n\nclass FloatTensor():\n\n def __init__(self, controller, data, data_is_pointer=False, verbose=False):\n self.verbose = verbose\n self.controller = controller\n if(data is not None and not data_is_pointer):\n data = data.astype('float')...
diff --git a/syft/syft.py b/syft/syft.py index 67414ce731e..1f8b47a80f6 100644 --- a/syft/syft.py +++ b/syft/syft.py @@ -102,6 +102,9 @@ def __imul__(self, x): def neg(self): return self.no_params_func("neg", return_response=True) + def rsqrt(self): + return self.no_params_func("rsqrt",return_response=True) + def sigmoid_(self): return self.no_params_func("sigmoid_")
talonhub__community-742
'go <arrow keys>' conflicts with generic_editor 'go left/right/up/down' This is really only a problem if the edit actions are overridden, but one might want to do so for `vim`...
[ { "content": "from typing import Set\n\nfrom talon import Module, Context, actions, app\nimport sys\n\ndefault_alphabet = \"air bat cap drum each fine gust harp sit jury crunch look made near odd pit quench red sun trap urge vest whale plex yank zip\".split(\n \" \"\n)\nletters_string = \"abcdefghijklmnopqrs...
[ { "content": "from typing import Set\n\nfrom talon import Module, Context, actions, app\nimport sys\n\ndefault_alphabet = \"air bat cap drum each fine gust harp sit jury crunch look made near odd pit quench red sun trap urge vest whale plex yank zip\".split(\n \" \"\n)\nletters_string = \"abcdefghijklmnopqrs...
diff --git a/code/keys.py b/code/keys.py index a6764aedd8..10c0dc699a 100644 --- a/code/keys.py +++ b/code/keys.py @@ -249,3 +249,12 @@ def letters(m) -> str: } +@mod.action_class +class Actions: + def move_cursor(s: str): + """Given a sequence of directions, eg. 'left left up', moves the cursor accordingly using edit.{left,right,up,down}.""" + for d in s.split(): + if d in ('left','right','up','down'): + getattr(actions.edit, d)() + else: + raise RuntimeError(f'invalid arrow key: {d}') diff --git a/misc/keys.talon b/misc/keys.talon index eeca9257bb..610671f38b 100644 --- a/misc/keys.talon +++ b/misc/keys.talon @@ -1,4 +1,4 @@ -go <user.arrow_keys>: key(arrow_keys) +go <user.arrow_keys>: user.move_cursor(arrow_keys) <user.letter>: key(letter) (ship | uppercase) <user.letters> [(lowercase | sunk)]: user.insert_formatted(letters, "ALL_CAPS") @@ -6,4 +6,7 @@ go <user.arrow_keys>: key(arrow_keys) <user.function_key>: key(function_key) <user.special_key>: key(special_key) <user.modifiers> <user.unmodified_key>: key("{modifiers}-{unmodified_key}") +# for key combos consisting only of modifiers, eg. `press super`. press <user.modifiers>: key(modifiers) +# for consistency with dictation mode and explicit arrow keys if you need them. +press <user.keys>: key(keys) diff --git a/modes/dictation_mode.talon b/modes/dictation_mode.talon index c6c4563e7a..3dc0684df7 100644 --- a/modes/dictation_mode.talon +++ b/modes/dictation_mode.talon @@ -1,6 +1,7 @@ mode: dictation - -^press <user.keys>$: key("{keys}") +^press <user.modifiers>$: key(modifiers) +^press <user.keys>$: key(keys) # Everything here should call `auto_insert()` (instead of `insert()`), to preserve the state to correctly auto-capitalize/auto-space. # (Talonscript string literals implicitly call `auto_insert`, so there's no need to wrap those)
SeldonIO__MLServer-192
Support other common names for SKLearn runtime Add support for models named `model.pickle` and `model.pkl`
[ { "content": "import joblib\n\nfrom typing import List\n\nfrom mlserver import types\nfrom mlserver.model import MLModel\nfrom mlserver.errors import InferenceError\nfrom mlserver.utils import get_model_uri, to_ndarray\n\n\nPREDICT_OUTPUT = \"predict\"\nPREDICT_PROBA_OUTPUT = \"predict_proba\"\nVALID_OUTPUTS = ...
[ { "content": "import joblib\n\nfrom typing import List\n\nfrom mlserver import types\nfrom mlserver.model import MLModel\nfrom mlserver.errors import InferenceError\nfrom mlserver.utils import get_model_uri, to_ndarray\n\n\nPREDICT_OUTPUT = \"predict\"\nPREDICT_PROBA_OUTPUT = \"predict_proba\"\nVALID_OUTPUTS = ...
diff --git a/runtimes/sklearn/mlserver_sklearn/sklearn.py b/runtimes/sklearn/mlserver_sklearn/sklearn.py index a419b8c89..312ea4067 100644 --- a/runtimes/sklearn/mlserver_sklearn/sklearn.py +++ b/runtimes/sklearn/mlserver_sklearn/sklearn.py @@ -12,7 +12,7 @@ PREDICT_PROBA_OUTPUT = "predict_proba" VALID_OUTPUTS = [PREDICT_OUTPUT, PREDICT_PROBA_OUTPUT] -WELLKNOWN_MODEL_FILENAMES = ["model.joblib"] +WELLKNOWN_MODEL_FILENAMES = ["model.joblib", "model.pickle", "model.pkl"] class SKLearnModel(MLModel):
nonebot__nonebot2-140
Bug: 发送窗口抖动消息,在msg中是无消息内容的,如果通过[0]索引或报错 cqhttp包下bot.py模块中 first_msg_seg = event.message[0] 超出索引 问题如上,另外建议连续二次索引时增加第一次索引的默认值防止第二次索引超出,state["_prefix"]["command"] in commands
[ { "content": "import re\nimport sys\nimport hmac\nimport json\nimport asyncio\nfrom typing import Any, Dict, Union, Optional, TYPE_CHECKING\n\nimport httpx\nfrom nonebot.log import logger\nfrom nonebot.config import Config\nfrom nonebot.typing import overrides\nfrom nonebot.message import handle_event\nfrom non...
[ { "content": "import re\nimport sys\nimport hmac\nimport json\nimport asyncio\nfrom typing import Any, Dict, Union, Optional, TYPE_CHECKING\n\nimport httpx\nfrom nonebot.log import logger\nfrom nonebot.config import Config\nfrom nonebot.typing import overrides\nfrom nonebot.message import handle_event\nfrom non...
diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py index 1aff6d5d2e97..d62ff8296b26 100644 --- a/nonebot/adapters/cqhttp/bot.py +++ b/nonebot/adapters/cqhttp/bot.py @@ -82,6 +82,10 @@ def _check_at_me(bot: "Bot", event: "Event"): if not isinstance(event, MessageEvent): return + # ensure message not empty + if not event.message: + event.message.append(MessageSegment.text("")) + if event.message_type == "private": event.to_me = True else:
locustio__locust-1359
Add --config parameter <!-- If you have a general question about how to use Locust, please check Stack Overflow first https://stackoverflow.com/questions/tagged/locust You can also ask new questions on SO, https://stackoverflow.com/questions/ask just remember to tag your question with "locust". --> ### Is your feature request related to a problem? Please describe. <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] --> I would like to be able to have multiple config files stored in version control for different purposes (eg one that uses step-mode and one that doesn't). ### Describe the solution you'd like <!-- A clear and concise description of what you want to happen --> `ConfigArgParse` makes it easy to add this capability. I think it could be done with a single line in `parse_options`: `parser.add_argument('--config', is_config_file_arg=True, help='config file path')` ### Describe alternatives you've considered <!-- A clear and concise description of any alternative solutions or features you've considered --> Current workaround is to keep multiple sets of configurations in `locust.conf`, with the active one uncommented.
[ { "content": "import argparse\nimport os\nimport sys\nimport textwrap\n\nimport configargparse\n\nimport locust\n\nversion = locust.__version__\n\n\nDEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']\n\n\ndef _is_package(path):\n \"\"\"\n Is the given path a Python package?\n \"\"\"\n return (\...
[ { "content": "import argparse\nimport os\nimport sys\nimport textwrap\n\nimport configargparse\n\nimport locust\n\nversion = locust.__version__\n\n\nDEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']\n\n\ndef _is_package(path):\n \"\"\"\n Is the given path a Python package?\n \"\"\"\n return (\...
diff --git a/docs/configuration.rst b/docs/configuration.rst index a876e34a3b..a7f95a6c9d 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -27,3 +27,33 @@ Most of the configuration that can be set through command line arguments can als environment variables. Here's a table of all the available environment variables: .. include:: env-options.rst + + + +.. _configuration-files: + +Configuration files +------------------- + +Any of the configuration that can be set through command line arguments can also be set by a +configuration file in the `config file <https://github.com/bw2/ConfigArgParse#config-file-syntax>`_ +format. +Locust will look for ``locust.conf`` or ``~/.locust.conf`` by default, or a file may be specified +with the ``--config`` flag. Parameters passed as command line arguments will override the settings +from the config file. + + +.. code-block:: + + # step_mode.conf in current directory + locustfile locust_files/my_locust_file.py + host localhost + users 100 + hatch-rate 10 + step-load + step-users 20 + step-time 60 + +.. code-block:: console + + $ locust --config=step_mode.conf diff --git a/docs/quickstart.rst b/docs/quickstart.rst index d79f26775d..2da12ff1fd 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -144,8 +144,10 @@ host defaults to 127.0.0.1): $ locust -f locust_files/my_locust_file.py --worker --master-host=192.168.0.100 -Parameters can also be set as :ref:`environment variables <environment-variables>`, or in a -`config file <https://github.com/bw2/ConfigArgParse#config-file-syntax>`_ (``locust.conf`` or ``~/.locust.conf``). +Parameters can also be set as :ref:`environment variables <environment-variables>`, or in a +`config file <https://github.com/bw2/ConfigArgParse#config-file-syntax>`_. +Locust will look for ``locust.conf`` or ``~/.locust.conf`` by default, or a file may be specified +with the ``--config`` flag. For example: (this will do the same thing as the previous command) diff --git a/locust/argument_parser.py b/locust/argument_parser.py index 3d0bf758ce..36ddd843fd 100644 --- a/locust/argument_parser.py +++ b/locust/argument_parser.py @@ -76,6 +76,8 @@ def get_empty_argument_parser(add_help=True, default_config_files=DEFAULT_CONFIG help="Python module file to import, e.g. '../other.py'. Default: locustfile", env_var="LOCUST_LOCUSTFILE", ) + parser.add_argument('--config', is_config_file_arg=True, help='Config file path') + return parser diff --git a/locust/test/test_main.py b/locust/test/test_main.py index 34ef2bbe17..c0065686a6 100644 --- a/locust/test/test_main.py +++ b/locust/test/test_main.py @@ -77,6 +77,40 @@ def test_create_environment(self): self.assertEqual(None, env.host) self.assertFalse(env.reset_stats) + def test_specify_config_file(self): + with temporary_file(textwrap.dedent(""" + host = localhost # With "=" + u 100 # Short form + hatch-rate 5 # long form + headless # boolean + """), suffix=".conf") as conf_file_path: + options = parse_options(args=[ + "--config", conf_file_path, + ]) + self.assertEqual(conf_file_path, options.config) + self.assertEqual("localhost", options.host) + self.assertEqual(100, options.num_users) + self.assertEqual(5, options.hatch_rate) + self.assertTrue(options.headless) + + def test_command_line_arguments_override_config_file(self): + with temporary_file("host=from_file", suffix=".conf") as conf_file_path: + options = parse_options(args=[ + "--config", conf_file_path, + "--host", "from_args", + ]) + self.assertEqual("from_args", options.host) + + def test_locustfile_can_be_set_in_config_file(self): + with temporary_file( + "locustfile my_locust_file.py", + suffix=".conf", + ) as conf_file_path: + options = parse_options(args=[ + "--config", conf_file_path, + ]) + self.assertEqual("my_locust_file.py", options.locustfile) + class LocustProcessIntegrationTest(TestCase): def setUp(self):
quantumlib__Cirq-2952
Update cirq.google.Bristlecone/Foxtail with accurate duration numbers
[ { "content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by...
[ { "content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by...
diff --git a/cirq/google/devices/known_devices.py b/cirq/google/devices/known_devices.py index 36bf4adc0a3..2caacbe41bd 100644 --- a/cirq/google/devices/known_devices.py +++ b/cirq/google/devices/known_devices.py @@ -228,8 +228,8 @@ def _json_dict_(self) -> Dict[str, Any]: # Duration dict in picoseconds _DURATIONS_FOR_XMON = { - 'cz': 50_000, - 'xy': 20_000, + 'cz': 45_000, + 'xy': 15_000, 'z': 0, 'meas': 4_000_000, # 1000ns for readout, 3000ns for "ring down" } diff --git a/cirq/google/devices/known_devices_test.py b/cirq/google/devices/known_devices_test.py index 587af9df721..400d409c25e 100644 --- a/cirq/google/devices/known_devices_test.py +++ b/cirq/google/devices/known_devices_test.py @@ -43,7 +43,7 @@ def test_foxtail_device_proto(): name: "half_turns" type: FLOAT } - gate_duration_picos: 20000 + gate_duration_picos: 15000 } valid_gates { id: "z" @@ -80,7 +80,7 @@ def test_foxtail_device_proto(): name: "half_turns" type: FLOAT } - gate_duration_picos: 50000 + gate_duration_picos: 45000 valid_targets: "2_qubit_targets" } valid_gates { diff --git a/cirq/google/devices/serializable_device_test.py b/cirq/google/devices/serializable_device_test.py index 5ac3a17ae3c..4d445b5e28a 100644 --- a/cirq/google/devices/serializable_device_test.py +++ b/cirq/google/devices/serializable_device_test.py @@ -148,7 +148,7 @@ def test_duration_of(): proto=cg.devices.known_devices.FOXTAIL_PROTO, gate_sets=[cg.gate_sets.XMON]) - assert foxtail.duration_of(cirq.X(valid_qubit1)) == cirq.Duration(nanos=20) + assert foxtail.duration_of(cirq.X(valid_qubit1)) == cirq.Duration(nanos=15) # Unsupported op with pytest.raises(ValueError):
carpentries__amy-1046
Django Debug Toolbar should have SQL panel ON by default Turning the panel ON allows to spot bottlenecks right on - just by looking at the number of queries (>8? Investigate). This panel is the most useful and most often used by me. The next one is template variables, which is ON by default already. Django Debug Toolbar should have SQL panel ON by default Turning the panel ON allows to spot bottlenecks right on - just by looking at the number of queries (>8? Investigate). This panel is the most useful and most often used by me. The next one is template variables, which is ON by default already.
[ { "content": "\"\"\"\nDjango settings for amy project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like th...
[ { "content": "\"\"\"\nDjango settings for amy project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like th...
diff --git a/amy/settings.py b/amy/settings.py index fbf86e346..f51f70bb1 100644 --- a/amy/settings.py +++ b/amy/settings.py @@ -346,10 +346,3 @@ # Debug Toolbar DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ['127.0.0.1', '::1'] -DEBUG_TOOLBAR_CONFIG = { - # Disable all panels (except for timer) by default in order not to slow - # down page loading. - 'DISABLE_PANELS': [ - 'debug_toolbar.panels.sql.SQLPanel', - ], -}
secdev__scapy-2471
Getting "Exception ignored in: <bound method SuperSocket.__del__ of ... >" #### Brief description Using `sniff` method with unreal `iface` parameter leads to `Ignored exception ...` #### Environment - Scapy version: `Version 2.4.3` - Python version: `Python 3.6.9` - Operating System: `Linux 5.3.0-28-generic #30~18.04.1-Ubuntu x86_64 GNU/Linux` #### How to reproduce ``` # (module name : sample.py) import scapy.all as scapy def main(): try: pkts = scapy.sniff(iface="mocked") except Exception as e: print("===========================================") print(str(e)) print("===========================================") exit() if __name__ == "__main__": main() ``` Ran from terminal as: `$ sudo python ./sample.py` #### Actual result ``` $ sudo python ./sample.py =========================================== [Errno 19] No such device =========================================== Exception ignored in: <bound method SuperSocket.__del__ of <scapy.arch.linux.L2ListenSocket object at 0x7f7ca13086a0>> Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/scapy/supersocket.py", line 134, in __del__ self.close() File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 514, in close set_promisc(self.ins, self.iface, 0) File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 165, in set_promisc mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, b"") File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 380, in get_if_index return int(struct.unpack("I", get_if(iff, SIOCGIFINDEX)[16:20])[0]) File "/usr/local/lib/python3.6/dist-packages/scapy/arch/common.py", line 59, in get_if ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8"))) OSError: [Errno 19] No such device ``` #### Expected result Just a successful exit from a program without additional std::err output. #### Related resources <!-- traces / sample pcaps (stripped to the relevant frames), related standards, RFCs or other resources -->
[ { "content": "# This file is part of Scapy\n# See http://www.secdev.org/projects/scapy for more information\n# Copyright (C) Philippe Biondi <phil@secdev.org>\n# This program is published under a GPLv2 license\n\n\"\"\"\nLinux specific functions.\n\"\"\"\n\nfrom __future__ import absolute_import\n\n\nimport arr...
[ { "content": "# This file is part of Scapy\n# See http://www.secdev.org/projects/scapy for more information\n# Copyright (C) Philippe Biondi <phil@secdev.org>\n# This program is published under a GPLv2 license\n\n\"\"\"\nLinux specific functions.\n\"\"\"\n\nfrom __future__ import absolute_import\n\n\nimport arr...
diff --git a/scapy/arch/linux.py b/scapy/arch/linux.py index a6a70b988c9..6a082176e39 100644 --- a/scapy/arch/linux.py +++ b/scapy/arch/linux.py @@ -494,7 +494,7 @@ def close(self): try: if self.promisc and self.ins: set_promisc(self.ins, self.iface, 0) - except AttributeError: + except (AttributeError, OSError): pass SuperSocket.close(self)
graspologic-org__graspologic-583
Fix bug in `is_unweighted` for sparse - [ ] Does this PR add any new dependencies? - [ ] Does this PR modify any existing APIs? - [ ] Is the change to the API backwards compatible? - [ ] Have you built the documentation (reference and/or tutorial) and verified the generated documentation is appropriate? #### Reference Issues/PRs #### What does this implement/fix? Briefly explain your changes. `is_unweighted` doesn't work properly for a sparse array input #### Any other comments? I think we could instead just do `graph[graph != 0].max() == 1 and graph[graph != 0].min() == 1` for that entire section of the code. [BUG] Bug in joblib transitive dependency causes exception when multi-threading ## Expected Behavior Multi-threading LatentDistributionTest using a "workers" value != 1 should return without error on all platforms. ## Actual Behavior When using any "workers" value > 1 or equal to -1 on a Windows computer, the code throws an exception. ## Example Code ```python test = LatentDistributionTest(input_graph=False, workers=10) result = test.fit_predict(graph1, graph2) ``` ## Full Traceback ```pytb C:\ProgramData\Anaconda3\lib\site-packages\joblib\disk.py:122: UserWarning: Unable to delete folder C:\Users\msrwinadm4\AppData\Local\Temp\5\joblib_memmapping_folder_11132_7308949288 after 5 tentatives. .format(folder_path, RM_SUBDIRS_N_RETRY)) Traceback (most recent call last): File "GraphsByOrg.py", line 79, in <module> logger.info(f'Calculating nonpar for {org1} and {org2}') File "C:\ProgramData\Anaconda3\lib\site-packages\graspologic\inference\latent_distribution_test.py", line 487, in fit_predict self.fit(A1, A2) File "C:\ProgramData\Anaconda3\lib\site-packages\graspologic\inference\latent_distribution_test.py", line 449, in fit X1_hat, X2_hat, reps=self.n_bootstraps, workers=self.workers, auto=False File "C:\ProgramData\Anaconda3\lib\site-packages\hyppo\ksample\ksamp.py", line 166, in test return self.indep_test.test(u, v, reps, workers, auto=auto) File "C:\ProgramData\Anaconda3\lib\site-packages\hyppo\independence\dcorr.py", line 215, in test stat, pvalue = super(Dcorr, self).test(x, y, reps, workers) File "C:\ProgramData\Anaconda3\lib\site-packages\hyppo\independence\base.py", line 67, in test self._statistic, x, y, reps=reps, workers=workers, is_distsim=is_distsim File "C:\ProgramData\Anaconda3\lib\site-packages\hyppo\_utils.py", line 140, in perm_test [delayed(_perm_stat)(calc_stat, x, y, is_distsim) for rep in range(reps)] File "C:\ProgramData\Anaconda3\lib\site-packages\joblib\parallel.py", line 1027, in __call__ self._terminate_backend() File "C:\ProgramData\Anaconda3\lib\site-packages\joblib\parallel.py", line 734, in _terminate_backend self._backend.terminate() File "C:\ProgramData\Anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 571, in terminate delete_folder(self._workers._temp_folder) File "C:\ProgramData\Anaconda3\lib\site-packages\joblib\disk.py", line 115, in delete_folder shutil.rmtree(folder_path, False, None) File "C:\ProgramData\Anaconda3\lib\shutil.py", line 516, in rmtree return _rmtree_unsafe(path, onerror) File "C:\ProgramData\Anaconda3\lib\shutil.py", line 400, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "C:\ProgramData\Anaconda3\lib\shutil.py", line 398, in _rmtree_unsafe os.unlink(fullname) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\msrwinadm4\\AppData\\Local\\Temp\\5\\joblib_memmapping_folder_11132_7308949288\\11132-1819792920136-683b9c4b033b449dbac251acbe3decfb.pkl' C:\ProgramData\Anaconda3\lib\site-packages\joblib\disk.py:122: UserWarning: Unable to delete folder C:\Users\msrwinadm4\AppData\Local\Temp\5\joblib_memmapping_folder_11132_7308949288 after 5 tentatives. .format(folder_path, RM_SUBDIRS_N_RETRY)) C:\ProgramData\Anaconda3\lib\site-packages\joblib\_memmapping_reducer.py:409: UserWarning: Failed to clean temporary folder: C:\Users\msrwinadm4\AppData\Local\Temp\5\joblib_memmapping_folder_11132_7308949288 .format(pool_folder)) ``` ## Your Environment * Python version: 3.7.6 (Anaconda) * graspologic version: 0.1.0.dev331219603 * Windows 2016 Datacenter (448 GB RAM) x64 ## Additional Details graspologic==0.1.0.dev331219603 joblib==0.14.1 hyppo==0.1.3 scikit-image==0.16.2 scikit-learn==0.22.1 scipy==1.4.1 numpy==1.18.1 ## Underlying problem: Older versions of joblib have a known issue running on Windows. See https://github.com/joblib/joblib/issues/806. This appears to be fixed on May 3rd, 2020 by https://github.com/joblib/joblib/pull/966. Hyppo uses joblib as a transitive dependency of scikit-learn but does not declare it as a dependency. Scikit-learn only requires joblib 0.11 which does not include this fix. See https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_min_dependencies.py
[ { "content": "# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport os\nimport sys\nfrom setuptools import setup, find_packages\n\n\nMINIMUM_PYTHON_VERSION = 3, 6 # Minimum of Python 3.6\n\nif sys.version_info < MINIMUM_PYTHON_VERSION:\n sys.exit(\"Python {}.{}...
[ { "content": "# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport os\nimport sys\nfrom setuptools import setup, find_packages\n\n\nMINIMUM_PYTHON_VERSION = 3, 6 # Minimum of Python 3.6\n\nif sys.version_info < MINIMUM_PYTHON_VERSION:\n sys.exit(\"Python {}.{}...
diff --git a/setup.py b/setup.py index b1fa371b2..cc5d59121 100644 --- a/setup.py +++ b/setup.py @@ -51,6 +51,7 @@ "anytree>=2.8.0", "gensim", "hyppo>=0.1.3", + "joblib>=0.17.0", # Older versions of joblib cause issue #806. Transitive dependency of hyppo. "matplotlib>=3.0.0,<=3.3.0", "networkx>=2.1", "numpy>=1.8.1",
kserve__kserve-1137
Installed KFServing SDK 0.4 but getting import error while running the custom built image /kind bug **What steps did you take and what happened:** Run a custom built image with KFServing SDK 0.4. ``` Traceback (most recent call last): File "/python3/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/python3/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/job/blambda-function/image_transformer_v2/__main__.py", line 15, in <module> import kfserving File "/python3/lib/python3.7/site-packages/kfserving/__init__.py", line 18, in <module> from .storage import Storage File "/python3/lib/python3.7/site-packages/kfserving/storage.py", line 23, in <module> from google.cloud import storage File "/python3/lib/python3.7/site-packages/google/cloud/storage/__init__.py", line 39, in <module> from google.cloud.storage.batch import Batch File "/python3/lib/python3.7/site-packages/google/cloud/storage/batch.py", line 31, in <module> from google.cloud.storage._http import Connection File "/python3/lib/python3.7/site-packages/google/cloud/storage/_http.py", line 17, in <module> from google.cloud import _http File "/python3/lib/python3.7/site-packages/google/cloud/_http.py", line 22, in <module> from six.moves import collections_abc ImportError: cannot import name 'collections_abc' from 'six.moves' (unknown location) ``` **What did you expect to happen:** **Anything else you would like to add:** We have fixed this in master branch but looks like we need to patch the setup.py in 0.4 branch and release a new minor version **Environment:** - Istio Version: - Knative Version: - KFServing Version: - Kubeflow version: - Kfdef:[k8s_istio/istio_dex/gcp_basic_auth/gcp_iap/aws/aws_cognito/ibm] - Minikube version: - Kubernetes version: (use `kubectl version`): - OS (e.g. from `/etc/os-release`):
[ { "content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applica...
[ { "content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applica...
diff --git a/python/alibiexplainer/setup.py b/python/alibiexplainer/setup.py index 6dce65a6c55..88dc38638c0 100644 --- a/python/alibiexplainer/setup.py +++ b/python/alibiexplainer/setup.py @@ -32,6 +32,7 @@ python_requires='>=3.6', packages=find_packages("alibiexplainer"), install_requires=[ + "shap==0.35", "kfserving>=0.4.0", "alibi==0.4.0", "scikit-learn>=0.20.3", diff --git a/python/kfserving/requirements.txt b/python/kfserving/requirements.txt index 455c148da27..027686e558f 100644 --- a/python/kfserving/requirements.txt +++ b/python/kfserving/requirements.txt @@ -1,14 +1,15 @@ certifi>=14.05.14 -six>=1.10 +six==1.15 python_dateutil>=2.5.3 setuptools>=21.0.0 urllib3>=1.15.1 kubernetes==10.0.1 -tornado>=1.4.1 +tornado>=6.0.0 argparse>=1.4.0 minio>=4.0.9 -google-cloud-storage>=1.16.0 +google-cloud-storage>=1.31.0 adal>=1.2.2 table_logger>=0.3.5 numpy>=1.17.3 -azure-storage-blob>=1.3.0,<=2.1.0 \ No newline at end of file +azure-storage-blob>=1.3.0,<=2.1.0 + diff --git a/python/kfserving/test/test_storage.py b/python/kfserving/test/test_storage.py index 528ead5d1f7..65e4a4cd250 100644 --- a/python/kfserving/test/test_storage.py +++ b/python/kfserving/test/test_storage.py @@ -73,7 +73,7 @@ def test_no_permission_buckets(mock_connection, mock_minio): bad_gcs_path = "gs://random/path" # Access private buckets without credentials mock_minio.return_value = Minio("s3.us.cloud-object-storage.appdomain.cloud", secure=True) - mock_connection.side_effect = error.AccessDenied(None) + mock_connection.side_effect = error.AccessDenied() with pytest.raises(error.AccessDenied): kfserving.Storage.download(bad_s3_path) mock_connection.side_effect = exceptions.Forbidden(None) diff --git a/test/scripts/run-e2e-tests.sh b/test/scripts/run-e2e-tests.sh index 4135dd529e8..04fb80c8e3b 100755 --- a/test/scripts/run-e2e-tests.sh +++ b/test/scripts/run-e2e-tests.sh @@ -80,9 +80,9 @@ kubectl create clusterrolebinding cluster-admin-binding \ --user=$(gcloud config get-value core/account) # Install and Initialize Helm -curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 -chmod 700 get_helm.sh -./get_helm.sh +wget https://get.helm.sh/helm-v3.0.2-linux-amd64.tar.gz +tar xvf helm-v3.0.2-linux-amd64.tar.gz +mv linux-amd64/helm /usr/local/bin/ echo "Install istio ..." mkdir istio_tmp
sopel-irc__sopel-1987
reddit: floating point error in upvote ratio https://github.com/sopel-irc/sopel/blob/d850844870ac62e4568b4743bd38f0f90d76af7d/sopel/modules/reddit.py#L183 Occasionally this code results in an output ratio like "57.99999999999999%". Should be super easy for anyone who wants a quick PR.
[ { "content": "# coding=utf-8\n\"\"\"\nreddit.py - Sopel Reddit Plugin\nCopyright 2012, Elsie Powell, embolalia.com\nCopyright 2019, dgw, technobabbl.es\nCopyright 2019, deathbybandaid, deathbybandaid.net\nLicensed under the Eiffel Forum License 2.\n\nhttps://sopel.chat\n\"\"\"\nfrom __future__ import absolute_i...
[ { "content": "# coding=utf-8\n\"\"\"\nreddit.py - Sopel Reddit Plugin\nCopyright 2012, Elsie Powell, embolalia.com\nCopyright 2019, dgw, technobabbl.es\nCopyright 2019, deathbybandaid, deathbybandaid.net\nLicensed under the Eiffel Forum License 2.\n\nhttps://sopel.chat\n\"\"\"\nfrom __future__ import absolute_i...
diff --git a/sopel/modules/reddit.py b/sopel/modules/reddit.py index ac97563cc8..819af86dd7 100644 --- a/sopel/modules/reddit.py +++ b/sopel/modules/reddit.py @@ -192,7 +192,7 @@ def say_post_info(bot, trigger, id_, show_link=True, show_comments_link=False): points_text = 'point' if s.score == 1 else 'points' - percent = color(unicode(s.upvote_ratio * 100) + '%', point_color) + percent = color('{:.1%}'.format(s.upvote_ratio), point_color) comments_link = '' if show_comments_link:
conan-io__conan-6198
[bug] SystemPackageTool installed() method is missing According to [conan-io/docs](https://github.com/conan-io/docs/blame/18d6adbf56a55a7d9185a12aa707b5fe161b35e9/reference/conanfile/methods.rst#L642), [docs.conan.io](https://docs.conan.io/en/latest/reference/conanfile/methods.html#systempackagetool) SystemPackageTool should have a public `installed(package_name)` method. Instead, only a protected `_installed(packages)` is provided (see [here](https://github.com/conan-io/conan/blob/develop/conans/client/tools/system_pm.py#L146)). ### Environment Details (include every applicable attribute) * Operating System+version: Ubuntu 18.04.3 LTS * Compiler+version: no applicable * Conan version: 1.20.5 * Python version: 3.6.9 ### Steps to reproduce (Include if Applicable) Try to use `SystemPackageTool.installed(package_name)` ### Logs (Executed commands with output) (Include/Attach if Applicable) ` ERROR: while executing system_requirements(): 'SystemPackageTool' object has no attribute 'installed'` and if `_installed` is used: ``` Linter warnings WARN: Linter. Line 25: Access to a protected member _installed of a client class ```
[ { "content": "import os\nimport sys\n\nfrom conans.client.runner import ConanRunner\nfrom conans.client.tools.oss import OSInfo, cross_building, get_cross_building_settings\nfrom conans.client.tools.files import which\nfrom conans.errors import ConanException\nfrom conans.util.env_reader import get_env\nfrom co...
[ { "content": "import os\nimport sys\n\nfrom conans.client.runner import ConanRunner\nfrom conans.client.tools.oss import OSInfo, cross_building, get_cross_building_settings\nfrom conans.client.tools.files import which\nfrom conans.errors import ConanException\nfrom conans.util.env_reader import get_env\nfrom co...
diff --git a/conans/client/tools/system_pm.py b/conans/client/tools/system_pm.py index de3b10e4aac..7b5e8d62ce1 100644 --- a/conans/client/tools/system_pm.py +++ b/conans/client/tools/system_pm.py @@ -143,6 +143,9 @@ def _get_package_names(self, packages, arch_names): return parsed_packages return packages + def installed(self, package_name): + return self._tool.installed(package_name) + def _installed(self, packages): if not packages: return True diff --git a/conans/test/unittests/client/tools/system_pm_test.py b/conans/test/unittests/client/tools/system_pm_test.py index 84a8aefdd92..335850ab3af 100644 --- a/conans/test/unittests/client/tools/system_pm_test.py +++ b/conans/test/unittests/client/tools/system_pm_test.py @@ -443,8 +443,10 @@ def system_package_tool_installed_test(self): expected_package = "chocolatey" # The expected should be installed on development/testing machines self.assertTrue(spt._tool.installed(expected_package)) + self.assertTrue(spt.installed(expected_package)) # This package hopefully doesn't exist self.assertFalse(spt._tool.installed("oidfjgesiouhrgioeurhgielurhgaeiorhgioearhgoaeirhg")) + self.assertFalse(spt.installed("oidfjgesiouhrgioeurhgielurhgaeiorhgioearhgoaeirhg")) def system_package_tool_fail_when_not_0_returned_test(self): def get_linux_error_message():
readthedocs__readthedocs.org-7582
Upgrade elastic search to 7.x https://www.elastic.co/blog/elasticsearch-7-0-0-released Changelog https://www.elastic.co/guide/en/elasticsearch/reference/current/breaking-changes-7.0.html
[ { "content": "import logging\nimport re\n\nfrom django.conf import settings\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import FacetedSearch, TermsFacet\nfrom elasticsearch_dsl.faceted_search import NestedFacet\nfrom elasticsearch_dsl.query import (\n Bool,\n FunctionScore,\n Multi...
[ { "content": "import logging\nimport re\n\nfrom django.conf import settings\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import FacetedSearch, TermsFacet\nfrom elasticsearch_dsl.faceted_search import NestedFacet\nfrom elasticsearch_dsl.query import (\n Bool,\n FunctionScore,\n Multi...
diff --git a/.circleci/config.yml b/.circleci/config.yml index 89119d19ca4..7516f9c8d3a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -6,8 +6,10 @@ jobs: - image: 'cimg/python:3.6' environment: TOX_POSARGS: '' - - image: 'docker.elastic.co/elasticsearch/elasticsearch:6.8.12' + - image: 'docker.elastic.co/elasticsearch/elasticsearch:7.9.2' name: search + environment: + discovery.type: single-node steps: - checkout - run: git submodule sync diff --git a/readthedocs/search/faceted_search.py b/readthedocs/search/faceted_search.py index 69ba778a429..33e0064bb11 100644 --- a/readthedocs/search/faceted_search.py +++ b/readthedocs/search/faceted_search.py @@ -275,7 +275,7 @@ def total_count(self): # we are only interested in the total count s = s.extra(size=0) s = s.execute() - return s.hits.total + return s.hits.total['value'] def query(self, search, query): """ diff --git a/requirements/pip.txt b/requirements/pip.txt index 08e5d23f969..fbc9599ea50 100644 --- a/requirements/pip.txt +++ b/requirements/pip.txt @@ -52,9 +52,9 @@ django-allauth==0.42.0 # pyup: ignore GitPython==3.1.11 # Search -elasticsearch==6.8.1 # pyup: <7.0.0 -elasticsearch-dsl==6.4.0 # pyup: <7.0 -django-elasticsearch-dsl==6.4.2 # pyup: <7.0 +elasticsearch==7.9.1 # pyup: <8.0.0 +elasticsearch-dsl==7.3.0 # pyup: <8.0 +django-elasticsearch-dsl==7.1.4 # pyup: <8.0 selectolax==0.2.9 # NOTE: this dep can be removed in python 3.7 in favor of ``date.fromisoformat``
hylang__hy-358
Allow macros to return None ``` (defmacro foo []) (foo) ``` Will break as macros are not handling the NoneType yet
[ { "content": "# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# t...
[ { "content": "# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# t...
diff --git a/hy/macros.py b/hy/macros.py index 20d0caca7..d3f08d88c 100644 --- a/hy/macros.py +++ b/hy/macros.py @@ -84,7 +84,8 @@ def require(source_module, target_module): complex: HyComplex, str_type: HyString, dict: lambda d: HyDict(_wrap_value(x) for x in sum(d.items(), ())), - list: lambda l: HyList(_wrap_value(x) for x in l) + list: lambda l: HyList(_wrap_value(x) for x in l), + type(None): lambda foo: HySymbol("None"), } diff --git a/tests/native_tests/native_macros.hy b/tests/native_tests/native_macros.hy index f5b1b74e1..b9f1cf07d 100644 --- a/tests/native_tests/native_macros.hy +++ b/tests/native_tests/native_macros.hy @@ -34,6 +34,9 @@ (defmacro a-dict [] {1 2}) (assert (= (a-dict) {1 2})) +(defmacro a-none []) +(assert (= (a-none) None)) + ; A macro calling a previously defined function (eval-when-compile (defn foo [x y]
kserve__kserve-1053
Tabular Explainer e2e test failing /kind bug ``` (base) C02YJ034JGH5:~ dsun20$ kubectl logs isvc-explainer-tabular-explainer-default-7cnkj-deployment-4q4hn -n kfserving-ci-e2e-test kfserving-container [I 200828 13:12:28 font_manager:1423] Generating new fontManager, this may take some time... Traceback (most recent call last): File "/usr/local/lib/python3.7/runpy.py", line 183, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/local/lib/python3.7/runpy.py", line 142, in _get_module_details return _get_module_details(pkg_main_name, error) File "/usr/local/lib/python3.7/runpy.py", line 109, in _get_module_details __import__(pkg_name) File "/alibiexplainer/alibiexplainer/__init__.py", line 15, in <module> from .explainer import AlibiExplainer File "/alibiexplainer/alibiexplainer/explainer.py", line 21, in <module> from alibiexplainer.anchor_images import AnchorImages File "/alibiexplainer/alibiexplainer/anchor_images.py", line 17, in <module> import alibi File "/usr/local/lib/python3.7/site-packages/alibi/__init__.py", line 1, in <module> from . import confidence, datasets, explainers, utils File "/usr/local/lib/python3.7/site-packages/alibi/explainers/__init__.py", line 11, in <module> from .kernel_shap import KernelShap File "/usr/local/lib/python3.7/site-packages/alibi/explainers/kernel_shap.py", line 11, in <module> from shap.common import DenseData, DenseDataWithIndex ModuleNotFoundError: No module named 'shap.common' ``` **What did you expect to happen:** **Anything else you would like to add:** [Miscellaneous information that will assist in solving the issue.] **Environment:** - Istio Version: - Knative Version: - KFServing Version: - Kubeflow version: - Kfdef:[k8s_istio/istio_dex/gcp_basic_auth/gcp_iap/aws/aws_cognito/ibm] - Minikube version: - Kubernetes version: (use `kubectl version`): - OS (e.g. from `/etc/os-release`):
[ { "content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applica...
[ { "content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applica...
diff --git a/python/alibiexplainer/setup.py b/python/alibiexplainer/setup.py index 6dce65a6c55..88dc38638c0 100644 --- a/python/alibiexplainer/setup.py +++ b/python/alibiexplainer/setup.py @@ -32,6 +32,7 @@ python_requires='>=3.6', packages=find_packages("alibiexplainer"), install_requires=[ + "shap==0.35", "kfserving>=0.4.0", "alibi==0.4.0", "scikit-learn>=0.20.3",
pypi__warehouse-6301
[Project-scoped API tokens] aren't available to maintainers **Describe the bug** <!-- A clear and concise description the bug --> When I use a "bot" account with "Maintainer" level access to projects, there are no projects to select from in the form for the token creation. **Expected behavior** <!-- A clear and concise description of what you expected to happen --> Since this "bot" can upload dists using user/password auth, it should also have similar privileges set when using tokens. **To Reproduce** <!-- Steps to reproduce the bug, or a link to PyPI where the bug is visible --> Go to https://pypi.org/manage/account/token and try selecting a project where you have only "Maintainer"-level access, not "Owner". **My Platform** N/A **Additional context** <!-- Add any other context, links, etc. about the feature here. --> N/A
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, softw...
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, softw...
diff --git a/tests/unit/manage/test_views.py b/tests/unit/manage/test_views.py index 876b2979ca53..ddcdf1c33be3 100644 --- a/tests/unit/manage/test_views.py +++ b/tests/unit/manage/test_views.py @@ -1363,6 +1363,41 @@ def test_default_response(self, monkeypatch): "delete_macaroon_form": delete_macaroon_obj, } + def test_project_names(self, db_request): + user = UserFactory.create() + another_user = UserFactory.create() + + db_request.user = user + db_request.find_service = lambda *a, **kw: pretend.stub() + + # A project with a sole owner that is the user + with_sole_owner = ProjectFactory.create(name="foo") + RoleFactory.create(user=user, project=with_sole_owner, role_name="Owner") + RoleFactory.create( + user=another_user, project=with_sole_owner, role_name="Maintainer" + ) + + # A project with multiple owners, including the user + with_multiple_owners = ProjectFactory.create(name="bar") + RoleFactory.create(user=user, project=with_multiple_owners, role_name="Owner") + RoleFactory.create( + user=another_user, project=with_multiple_owners, role_name="Owner" + ) + + # A project with a sole owner that is not the user + not_an_owner = ProjectFactory.create(name="baz") + RoleFactory.create(user=user, project=not_an_owner, role_name="Maintainer") + RoleFactory.create(user=another_user, project=not_an_owner, role_name="Owner") + + # A project that the user is neither owner nor maintainer of + neither_owner_nor_maintainer = ProjectFactory.create(name="quux") + RoleFactory.create( + user=another_user, project=neither_owner_nor_maintainer, role_name="Owner" + ) + + view = views.ProvisionMacaroonViews(db_request) + assert set(view.project_names) == {"foo", "bar", "baz"} + def test_manage_macaroons(self, monkeypatch): request = pretend.stub(find_service=lambda *a, **kw: pretend.stub()) @@ -1412,10 +1447,10 @@ def test_create_macaroon_invalid_form(self, monkeypatch): ) monkeypatch.setattr(views, "CreateMacaroonForm", create_macaroon_cls) - user_projects = pretend.call_recorder( - lambda r: {"projects_owned": [pretend.stub(name=pretend.stub())]} + project_names = [pretend.stub()] + monkeypatch.setattr( + views.ProvisionMacaroonViews, "project_names", project_names ) - monkeypatch.setattr(views, "user_projects", user_projects) default_response = {"default": "response"} monkeypatch.setattr( @@ -1458,11 +1493,10 @@ def test_create_macaroon(self, monkeypatch): ) monkeypatch.setattr(views, "CreateMacaroonForm", create_macaroon_cls) - project_name = pretend.stub() - user_projects = pretend.call_recorder( - lambda r: {"projects_owned": [pretend.stub(name=project_name)]} + project_names = [pretend.stub()] + monkeypatch.setattr( + views.ProvisionMacaroonViews, "project_names", project_names ) - monkeypatch.setattr(views, "user_projects", user_projects) default_response = {"default": "response"} monkeypatch.setattr( diff --git a/warehouse/manage/views.py b/warehouse/manage/views.py index 7e1f5e1dd63e..2b523c493abf 100644 --- a/warehouse/manage/views.py +++ b/warehouse/manage/views.py @@ -559,8 +559,7 @@ def __init__(self, request): @property def project_names(self): - projects = user_projects(self.request)["projects_owned"] - return [project.name for project in projects] + return sorted(project.name for project in self.request.user.projects) @property def default_response(self): diff --git a/warehouse/templates/manage/account.html b/warehouse/templates/manage/account.html index a19d0ddfd330..63a17b646429 100644 --- a/warehouse/templates/manage/account.html +++ b/warehouse/templates/manage/account.html @@ -152,7 +152,7 @@ All projects {% else %} {% for project in macaroon.caveats.get("permissions")['projects'] %} - <a href="{{ request.route_path('manage.project.releases', project_name=project) }}">{{ project }}</a> + <a href="{{ request.route_path('packaging.project', name=project) }}">{{ project }}</a> {% endfor %} {% endif %} </td> diff --git a/warehouse/templates/manage/token.html b/warehouse/templates/manage/token.html index daecf4e56425..4b0cfcb6ca20 100644 --- a/warehouse/templates/manage/token.html +++ b/warehouse/templates/manage/token.html @@ -88,6 +88,7 @@ <h2>Add another token</h2> <label for="token_scope" class="form-group__label">Scope</label> <select name="token_scope" id="token_scope" class="form-group__input" aria-describedby="token_scope-errors"> <option disabled selected value="scope:unspecified">Select scope...</option> + <option value="scope:user">Entire account (all projects)</option> {% for project in project_names %} <option value="scope:project:{{ project }}">Project: {{ project }}</option> {% endfor %}
strawberry-graphql__strawberry-1994
Postponed annotation evaluation causes `Annotated` to break When using postponed annotation evaluation, annotating resolver arguments no longer works: ```python from __future__ import annotations import random from typing import Annotated import strawberry @strawberry.type class Query: @strawberry.field def dice_roll( self, sides: Annotated[ int, strawberry.argument(description="Number of sides the die should have."), ] = 6, ) -> int: return random.randint(1, sides) strawberry.Schema(query=Query) ``` The example above raises this TypeError: ``` TypeError: Query fields cannot be resolved. Unexpected type 'typing.Annotated[int, <strawberry.arguments.StrawberryArgumentAnnotation object at 0x7fd12e130d00>]' ``` When the first line (`from __future__ import annotations`) is left out, everything works as intended. This will probably also break once Python 3.11 lands, since the behavior will become mandatory then. #1586 refers to a somewhat related issue.
[ { "content": "from __future__ import annotations\n\nfrom typing import Any, Optional, Union, cast\n\nfrom typing_extensions import Annotated, get_args, get_origin\n\nfrom strawberry.type import StrawberryType\n\nfrom .annotation import StrawberryAnnotation\n\n\nclass StrawberryAutoMeta(type):\n \"\"\"Metacla...
[ { "content": "from __future__ import annotations\n\nfrom typing import Any, Optional, Union, cast\n\nfrom typing_extensions import Annotated, get_args, get_origin\n\nfrom strawberry.type import StrawberryType\n\nfrom .annotation import StrawberryAnnotation\n\n\nclass StrawberryAutoMeta(type):\n \"\"\"Metacla...
diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000000..d3956a9cdf --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,4 @@ +Release type: patch + +This release adds an initial fix to make `strawberry.auto` work when using +`from __future__ import annotations`. diff --git a/strawberry/auto.py b/strawberry/auto.py index 66747ebbeb..9232388090 100644 --- a/strawberry/auto.py +++ b/strawberry/auto.py @@ -57,7 +57,7 @@ def __instancecheck__( if args[0] is Any: return any(isinstance(arg, StrawberryAuto) for arg in args[1:]) - return False + return instance == "strawberry.auto" class StrawberryAuto(metaclass=StrawberryAutoMeta): diff --git a/tests/experimental/pydantic/schema/test_forward_reference.py b/tests/experimental/pydantic/schema/test_forward_reference.py new file mode 100644 index 0000000000..ebc94d4b37 --- /dev/null +++ b/tests/experimental/pydantic/schema/test_forward_reference.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import textwrap +from typing import Optional + +import pydantic + +import strawberry + + +def test_auto_fields(): + global User + + class UserModel(pydantic.BaseModel): + age: int + password: Optional[str] + other: float + + @strawberry.experimental.pydantic.type(UserModel) + class User: + age: strawberry.auto + password: strawberry.auto + + @strawberry.type + class Query: + @strawberry.field + def user(self) -> User: + return User(age=1, password="ABC") + + schema = strawberry.Schema(query=Query) + + expected_schema = """ + type Query { + user: User! + } + + type User { + age: Int! + password: String + } + """ + + assert str(schema) == textwrap.dedent(expected_schema).strip() + + query = "{ user { age } }" + + result = schema.execute_sync(query) + + assert not result.errors + assert result.data["user"]["age"] == 1
Rapptz__discord.py-1745
Using wait=True in webhook.execute raises AttributeError Title. Here's the code (using eval command) and traceback in case. ```py webhook = (await ctx.channel.webhooks())[0] msg = await webhook.execute("test", wait=True) ``` ``` Traceback (most recent call last): File "/home/nguuuquaaa/bot/Belphegor/belphegor/admin.py", line 131, in _eval await func() File "<string>", line 3, in func File "/usr/local/lib/python3.6/dist-packages/discord/webhook.py", line 197, in handle_execution_response return Message(data=data, state=self, channel=self.webhook.channel) File "/usr/local/lib/python3.6/dist-packages/discord/message.py", line 213, in __init__ self._update(channel, data) File "/usr/local/lib/python3.6/dist-packages/discord/message.py", line 278, in _update getattr(self, '_handle_%s' % handler)(data[handler]) File "/usr/local/lib/python3.6/dist-packages/discord/message.py", line 291, in _handle_author self.author = self._state.store_user(author) AttributeError: 'AsyncWebhookAdapter' object has no attribute 'store_user' ```
[ { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-2017 Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, includin...
[ { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-2017 Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, includin...
diff --git a/discord/webhook.py b/discord/webhook.py index 0dfe6ba6281a..a4f84632a45c 100644 --- a/discord/webhook.py +++ b/discord/webhook.py @@ -100,7 +100,7 @@ def handle_execution_response(self, data, *, wait): """ raise NotImplementedError() - def _store_user(self, data): + def store_user(self, data): # mocks a ConnectionState for appropriate use for Message return BaseUser(state=self, data=data)
Zeroto521__my-data-toolkit-467
TYP: specific `None` type <!-- Thanks for contributing a pull request! Please follow these standard acronyms to start the commit message: - ENH: enhancement - BUG: bug fix - DOC: documentation - TYP: type annotations - TST: addition or modification of tests - MAINT: maintenance commit (refactoring, typos, etc.) - BLD: change related to building - REL: related to releasing - API: an (incompatible) API change - DEP: deprecate something, or remove a deprecated object - DEV: development tool or utility - REV: revert an earlier commit - PERF: performance improvement - BOT: always commit via a bot - CI: related to CI or CD - CLN: Code cleanup --> - [ ] closes #xxxx - [x] whatsnew entry `paramerter: TheType = None` means `parameter` is `Optional[TheType]`. `parameter: None` means `None` has any specifal function.
[ { "content": "from __future__ import annotations\n\nfrom textwrap import dedent\nfrom typing import TYPE_CHECKING\n\nimport pandas as pd\nfrom pandas.util._decorators import doc\nfrom pandas.util._validators import validate_bool_kwarg\n\nfrom dtoolkit.accessor.register import register_series_method\n\nif TYPE_C...
[ { "content": "from __future__ import annotations\n\nfrom textwrap import dedent\nfrom typing import TYPE_CHECKING\n\nimport pandas as pd\nfrom pandas.util._decorators import doc\nfrom pandas.util._validators import validate_bool_kwarg\n\nfrom dtoolkit.accessor.register import register_series_method\n\nif TYPE_C...
diff --git a/dtoolkit/accessor/series.py b/dtoolkit/accessor/series.py index b8481bd44..3597e58ad 100644 --- a/dtoolkit/accessor/series.py +++ b/dtoolkit/accessor/series.py @@ -382,7 +382,7 @@ def lens(s: pd.Series, number: int = 1, other: int = None) -> pd.Series: Parameters ---------- - number : int or None, default '1' + number : int, default 1 The default length of `number` type. other : int or None, default None The default length of `other` type.
sktime__sktime-6019
[BUG] `BaseRegressor.score` method fails with `sklearn.metrics r2_score got an unexpected keyword argument 'normalize'` **Describe the bug** When using ResNetRegressor score (also tested with FCNRegressor and same bug) you got a sklearn.metrics error. TypeError: got an unexpected keyword argument 'normalize' **To Reproduce** ```python import sktime from sktime.regression.deep_learning.resnet import ResNetRegressor from sktime.datasets import load_UCR_UEA_dataset data = 'BIDMC32HR' train_x, train_y = load_UCR_UEA_dataset(name=data, split="train") test_x, test_y = load_UCR_UEA_dataset(name=data, split="test") model = ResNetRegressor(n_epochs=1, batch_size=1) model.fit(train_x, train_y) model.score(test_x, test_y) ``` **Expected behavior** Not an error but score **Additional context** ResNetRegressor::score <details> ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[7], line 1 ----> 1 model.score(test_x, test_y) File [~/Development/sktime-dev/sktime/sktime/regression/base.py:302](http://localhost:18888/lab/tree/sktime/sktime/sktime/regression/base.py#line=301), in BaseRegressor.score(self, X, y, multioutput) 298 from sklearn.metrics import r2_score 300 self.check_is_fitted() --> 302 return r2_score(y, self.predict(X), normalize=True, multioutput=multioutput) File [~/Development/sktime-dev/venv/lib/python3.10/site-packages/sklearn/utils/_param_validation.py:191](http://localhost:18888/lab/tree/sktime/venv/lib/python3.10/site-packages/sklearn/utils/_param_validation.py#line=190), in validate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs) 188 func_sig = signature(func) 190 # Map *args/**kwargs to the function signature --> 191 params = func_sig.bind(*args, **kwargs) 192 params.apply_defaults() 194 # ignore self/cls and positional/keyword markers File /usr/lib/python3.10/inspect.py:3186, in Signature.bind(self, *args, **kwargs) 3181 def bind(self, /, *args, **kwargs): 3182 """Get a BoundArguments object, that maps the passed `args` 3183 and `kwargs` to the function's signature. Raises `TypeError` 3184 if the passed arguments can not be bound. 3185 """ -> 3186 return self._bind(args, kwargs) File /usr/lib/python3.10/inspect.py:3175, in Signature._bind(self, args, kwargs, partial) 3173 arguments[kwargs_param.name] = kwargs 3174 else: -> 3175 raise TypeError( 3176 'got an unexpected keyword argument {arg!r}'.format( 3177 arg=next(iter(kwargs)))) 3179 return self._bound_arguments_cls(self, arguments) TypeError: got an unexpected keyword argument 'normalize' ``` </details> FCNRegressor::model <details> ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 4 2 model = FCNRegressor(n_epochs=1, batch_size=1) 3 model.fit(train_x, train_y) ----> 4 model.score(test_x, test_y) File [~/Development/sktime-dev/sktime/sktime/regression/base.py:302](http://localhost:18888/lab/tree/sktime/sktime/sktime/regression/base.py#line=301), in BaseRegressor.score(self, X, y, multioutput) 298 from sklearn.metrics import r2_score 300 self.check_is_fitted() --> 302 return r2_score(y, self.predict(X), normalize=True, multioutput=multioutput) File [~/Development/sktime-dev/venv/lib/python3.10/site-packages/sklearn/utils/_param_validation.py:191](http://localhost:18888/lab/tree/sktime/venv/lib/python3.10/site-packages/sklearn/utils/_param_validation.py#line=190), in validate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs) 188 func_sig = signature(func) 190 # Map *args/**kwargs to the function signature --> 191 params = func_sig.bind(*args, **kwargs) 192 params.apply_defaults() 194 # ignore self/cls and positional/keyword markers File /usr/lib/python3.10/inspect.py:3186, in Signature.bind(self, *args, **kwargs) 3181 def bind(self, /, *args, **kwargs): 3182 """Get a BoundArguments object, that maps the passed `args` 3183 and `kwargs` to the function's signature. Raises `TypeError` 3184 if the passed arguments can not be bound. 3185 """ -> 3186 return self._bind(args, kwargs) File /usr/lib/python3.10/inspect.py:3175, in Signature._bind(self, args, kwargs, partial) 3173 arguments[kwargs_param.name] = kwargs 3174 else: -> 3175 raise TypeError( 3176 'got an unexpected keyword argument {arg!r}'.format( 3177 arg=next(iter(kwargs)))) 3179 return self._bound_arguments_cls(self, arguments) TypeError: got an unexpected keyword argument 'normalize' ``` </details> **Versions** <details> ``` /home/cyril/Development/sktime-dev/venv/lib/python3.10/site-packages/_distutils_hack/__init__.py:26: UserWarning: Setuptools is replacing distutils. warnings.warn("Setuptools is replacing distutils.") /home/cyril/Development/sktime-dev/venv/lib/python3.10/site-packages/statsforecast/core.py:26: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from tqdm.autonotebook import tqdm ``` System: python: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] executable: /home/cyril/Development/sktime-dev/venv/bin/python machine: Linux-6.5.0-14-generic-x86_64-with-glibc2.35 Python dependencies: pip: 24.0 sktime: 0.26.1 sklearn: 1.4.1.post1 skbase: 0.7.2 numpy: 1.26.4 scipy: 1.12.0 pandas: 2.1.4 matplotlib: 3.8.3 joblib: 1.3.2 numba: 0.58.1 statsmodels: 0.14.1 pmdarima: 2.0.4 statsforecast: 1.7.3 tsfresh: 0.20.2 tslearn: 0.6.3 torch: None tensorflow: 2.15.0 tensorflow_probability: None </details> <!-- Thanks for contributing! -->
[ { "content": "# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\"\"\"Abstract base class for time series regressors.\n\n class name: BaseRegressor\n\nDefining methods:\n fitting - fit(self, X, y)\n predicting - predict(self, X)\n\nInherited inspection methods:\n ...
[ { "content": "# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\"\"\"Abstract base class for time series regressors.\n\n class name: BaseRegressor\n\nDefining methods:\n fitting - fit(self, X, y)\n predicting - predict(self, X)\n\nInherited inspection methods:\n ...
diff --git a/.all-contributorsrc b/.all-contributorsrc index 7f4681438ca..0f7a286d3e4 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -2590,7 +2590,9 @@ "avatar_url": "https://avatars.githubusercontent.com/u/69190238?v=4", "profile": "https://cyrilmeyer.eu/", "contributions": [ - "code" + "bug", + "code", + "test" ] }, { diff --git a/sktime/regression/base.py b/sktime/regression/base.py index ef95794ea0e..11a41a35266 100644 --- a/sktime/regression/base.py +++ b/sktime/regression/base.py @@ -299,7 +299,7 @@ def score(self, X, y, multioutput="uniform_average") -> float: self.check_is_fitted() - return r2_score(y, self.predict(X), normalize=True, multioutput=multioutput) + return r2_score(y, self.predict(X), multioutput=multioutput) def _fit(self, X, y): """Fit time series regressor to training data. diff --git a/sktime/regression/tests/test_all_regressors.py b/sktime/regression/tests/test_all_regressors.py index c3e8b1c4ab9..a499fa65ef5 100644 --- a/sktime/regression/tests/test_all_regressors.py +++ b/sktime/regression/tests/test_all_regressors.py @@ -77,6 +77,9 @@ def test_regressor_output(self, estimator_instance, scenario): # run fit and predict y_pred = scenario.run(estimator_instance, method_sequence=["fit", "predict"]) + # check score + score = estimator_instance.score(X_new, y_pred) + assert np.issubdtype(score.dtype, np.floating) # check predict assert isinstance(y_pred, np.ndarray) @@ -95,6 +98,9 @@ def test_multioutput(self, estimator_instance): estimator_instance.fit(X, y_mult) y_pred = estimator_instance.predict(X) + # check score + score = estimator_instance.score(X, y_mult) + assert np.issubdtype(score.dtype, np.floating) assert isinstance(y_pred, pd.DataFrame) assert y_pred.shape == y_mult.shape
jupyter__docker-stacks-1859
[BUG] - Health Check fails if you change the port jupyter runs on ### What docker image(s) are you using? minimal-notebook ### OS system and architecture running docker image RHEL7 docker swarm ### What Docker command are you running? Not really relevant, but I need to run it in a docker swarm, with a generalise 'ingress service'. For this I needed to change internal port jupyter runs on needs to be changes for intergation into a 'ingress proxy' To change the port I made a slight modification the docker image to set the internal port it runs on (see below) The problem is the docker container dies unexpectedly after running for 46 seconds. During that time the service is visible within the conatiner, but not external to the container. This is because the built-in heathcheck never succeeds, and eventually kills the container with little logged reporting. (see below) ### How to Reproduce the problem? Dockerfile, to set port ```dockerfile FROM "jupyter/minimal-notebook:latest" # Update Jupyter configuration to set port RUN set -eux; \ sed -i 's/port = 8888/port = 8080/' /etc/jupyter/jupyter_notebook_config.py ;\ sed -i 's/port = 8888/port = 8080/' /etc/jupyter/jupyter_server_config.py ;\ :; ``` You can also change the port in other ways such as... Creating a `~joyvan/.jupyter/jupyter_server_config.py` file (which can also set a password) or setting a JUPYTER_PORT environment variable (IF the setting in `/etc/jupyter` configs are removed) ### Command output When you build and then run the modified docker image, `docker ps` reports `Up 9 seconds (health: starting) 8888/tcp` despite the fact that jupyter is now running on port 8080 46 seconds after starting the container dies with a unhelpful (Signal 15) Log output... ``` [I 2022-10-28 05:20:00.393 ServerApp] Jupyter Server 1.21.0 is running at: [I 2022-10-28 05:20:00.393 ServerApp] http://jupyter_service:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c or http://127.0.0.1:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c [I 2022-10-28 05:20:00.393 ServerApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 2022-10-28 05:20:00.397 ServerApp] To access the server, open this file in a browser: file:///home/jovyan/.local/share/jupyter/runtime/jpserver-8-open.html Or copy and paste one of these URLs: http://jupyter_service:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c or http://127.0.0.1:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c Entered start.sh with args: jupyter lab Executing the command: jupyter lab [C 2022-10-28 05:20:46.261 ServerApp] received signal 15, stopping [I 2022-10-28 05:20:46.262 ServerApp] Shutting down 2 extensions [I 2022-10-28 05:20:46.263 ServerApp] Shutting down 0 terminals ``` ### Expected behavior Changing the internal port should not take days of work to track down, it should be straight forward and documented. The healthcheck should also be properly documented in jupyter-stacks documentation. This will make it more 'swarm friendly' as well as allow others to integrate it better when port 8888 is NOT available. Yes you can map the port when doing a 'docker run', but that is NOT always possible. ### Actual behavior Internal Port changing is undocumented in stacks Heathcheck kills the container without notice (signal 15 hardly makes it clear) when port is different. Days of work lost trying to figure out what should be a straight forward and simple task. ### Anything else? There is an existing environment variable "JUPYTER_PORT" that defines the default port. But any such setting is currently overridden by the configuration files in `/etc/jupyter` This may be usable to set healthcheck, especially if the config file default is removed, or allows the env var to override. in Dockerfile.... ``` HEALTHCHECK --interval=15s --timeout=3s --start-period=5s --retries=3 \ CMD wget -O- --no-verbose --tries=1 --no-check-certificate \ http${GEN_CERT:+s}://localhost:${JUPYTER_PORT:-8888}${JUPYTERHUB_SERVICE_PREFIX:-/}api || exit 1 ``` That Environment variable also needs to be documented in the jupyter-stacks documentation, with the health check. [BUG] - Health Check fails if you change the port jupyter runs on ### What docker image(s) are you using? minimal-notebook ### OS system and architecture running docker image RHEL7 docker swarm ### What Docker command are you running? Not really relevant, but I need to run it in a docker swarm, with a generalise 'ingress service'. For this I needed to change internal port jupyter runs on needs to be changes for intergation into a 'ingress proxy' To change the port I made a slight modification the docker image to set the internal port it runs on (see below) The problem is the docker container dies unexpectedly after running for 46 seconds. During that time the service is visible within the conatiner, but not external to the container. This is because the built-in heathcheck never succeeds, and eventually kills the container with little logged reporting. (see below) ### How to Reproduce the problem? Dockerfile, to set port ```dockerfile FROM "jupyter/minimal-notebook:latest" # Update Jupyter configuration to set port RUN set -eux; \ sed -i 's/port = 8888/port = 8080/' /etc/jupyter/jupyter_notebook_config.py ;\ sed -i 's/port = 8888/port = 8080/' /etc/jupyter/jupyter_server_config.py ;\ :; ``` You can also change the port in other ways such as... Creating a `~joyvan/.jupyter/jupyter_server_config.py` file (which can also set a password) or setting a JUPYTER_PORT environment variable (IF the setting in `/etc/jupyter` configs are removed) ### Command output When you build and then run the modified docker image, `docker ps` reports `Up 9 seconds (health: starting) 8888/tcp` despite the fact that jupyter is now running on port 8080 46 seconds after starting the container dies with a unhelpful (Signal 15) Log output... ``` [I 2022-10-28 05:20:00.393 ServerApp] Jupyter Server 1.21.0 is running at: [I 2022-10-28 05:20:00.393 ServerApp] http://jupyter_service:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c or http://127.0.0.1:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c [I 2022-10-28 05:20:00.393 ServerApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 2022-10-28 05:20:00.397 ServerApp] To access the server, open this file in a browser: file:///home/jovyan/.local/share/jupyter/runtime/jpserver-8-open.html Or copy and paste one of these URLs: http://jupyter_service:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c or http://127.0.0.1:8080/lab?token=929eaaf2e60f8a947761cb1f2741d745fd46dde62f6fef7c Entered start.sh with args: jupyter lab Executing the command: jupyter lab [C 2022-10-28 05:20:46.261 ServerApp] received signal 15, stopping [I 2022-10-28 05:20:46.262 ServerApp] Shutting down 2 extensions [I 2022-10-28 05:20:46.263 ServerApp] Shutting down 0 terminals ``` ### Expected behavior Changing the internal port should not take days of work to track down, it should be straight forward and documented. The healthcheck should also be properly documented in jupyter-stacks documentation. This will make it more 'swarm friendly' as well as allow others to integrate it better when port 8888 is NOT available. Yes you can map the port when doing a 'docker run', but that is NOT always possible. ### Actual behavior Internal Port changing is undocumented in stacks Heathcheck kills the container without notice (signal 15 hardly makes it clear) when port is different. Days of work lost trying to figure out what should be a straight forward and simple task. ### Anything else? There is an existing environment variable "JUPYTER_PORT" that defines the default port. But any such setting is currently overridden by the configuration files in `/etc/jupyter` This may be usable to set healthcheck, especially if the config file default is removed, or allows the env var to override. in Dockerfile.... ``` HEALTHCHECK --interval=15s --timeout=3s --start-period=5s --retries=3 \ CMD wget -O- --no-verbose --tries=1 --no-check-certificate \ http${GEN_CERT:+s}://localhost:${JUPYTER_PORT:-8888}${JUPYTERHUB_SERVICE_PREFIX:-/}api || exit 1 ``` That Environment variable also needs to be documented in the jupyter-stacks documentation, with the health check.
[ { "content": "# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n# mypy: ignore-errors\nimport os\nimport stat\nimport subprocess\n\nfrom jupyter_core.paths import jupyter_data_dir\n\nc = get_config() # noqa: F821\nc.ServerApp.ip = \"0.0.0.0\"\nc.ServerApp.po...
[ { "content": "# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n# mypy: ignore-errors\nimport os\nimport stat\nimport subprocess\n\nfrom jupyter_core.paths import jupyter_data_dir\n\nc = get_config() # noqa: F821\nc.ServerApp.ip = \"0.0.0.0\"\nc.ServerApp.op...
diff --git a/base-notebook/Dockerfile b/base-notebook/Dockerfile index 9804ddb251..9f3d226df1 100644 --- a/base-notebook/Dockerfile +++ b/base-notebook/Dockerfile @@ -47,7 +47,8 @@ RUN mamba install --quiet --yes \ fix-permissions "${CONDA_DIR}" && \ fix-permissions "/home/${NB_USER}" -EXPOSE 8888 +ENV JUPYTER_PORT=8888 +EXPOSE $JUPYTER_PORT # Configure container startup CMD ["start-notebook.sh"] @@ -70,7 +71,7 @@ RUN sed -re "s/c.ServerApp/c.NotebookApp/g" \ # https://github.com/jupyter/docker-stacks/issues/915#issuecomment-1068528799 HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=3 \ CMD wget -O- --no-verbose --tries=1 --no-check-certificate \ - http${GEN_CERT:+s}://localhost:8888${JUPYTERHUB_SERVICE_PREFIX:-/}api || exit 1 + http${GEN_CERT:+s}://localhost:${JUPYTER_PORT}${JUPYTERHUB_SERVICE_PREFIX:-/}api || exit 1 # Switch back to jovyan to avoid accidental container runs as root USER ${NB_UID} diff --git a/base-notebook/jupyter_server_config.py b/base-notebook/jupyter_server_config.py index c95957cc7b..679f96bee0 100644 --- a/base-notebook/jupyter_server_config.py +++ b/base-notebook/jupyter_server_config.py @@ -9,7 +9,6 @@ c = get_config() # noqa: F821 c.ServerApp.ip = "0.0.0.0" -c.ServerApp.port = 8888 c.ServerApp.open_browser = False # to output both image/svg+xml and application/pdf plot formats in the notebook file diff --git a/docs/using/common.md b/docs/using/common.md index 2444495a3b..bf11753b29 100644 --- a/docs/using/common.md +++ b/docs/using/common.md @@ -22,10 +22,16 @@ You can pass [Jupyter server options](https://jupyter-server.readthedocs.io/en/l 2. To set the [base URL](https://jupyter-server.readthedocs.io/en/latest/operators/public-server.html#running-the-notebook-with-a-customized-url-prefix) of the notebook server, you can run the following: ```bash - docker run -it --rm -p 8888:8888 jupyter/base-notebook \ + docker run -it --rm -p 8888:8888 --no-healthcheck jupyter/base-notebook \ start-notebook.sh --NotebookApp.base_url=/customized/url/prefix/ ``` + Note: We pass the `--no-healthcheck` parameter when setting a custom `base_url` for the Jupyter server, + because our current implementation for doing healthcheck assumes the `base_url` to be `/` (the default). + Without using this parameter, the container may run, but it's state will be "unhealthy". + Alternatively, you can [use your own command for healthcheck](https://docs.docker.com/engine/reference/run/#healthcheck) + using the `--health-cmd` parameter. + ## Docker Options You may instruct the `start-notebook.sh` script to customize the container environment before launching the notebook server. @@ -123,6 +129,8 @@ You do so by passing arguments to the `docker run` command. The variables are unset after the hooks have been executed but before the command provided to the startup script runs. - `-e NOTEBOOK_ARGS="--log-level='DEBUG' --dev-mode"` - Adds custom options to add to `jupyter` commands. This way, the user could use any option supported by `jupyter` subcommand. +- `-e JUPYTER_PORT=8117` - Changes the port in the container that Jupyter is using to the value of the `${JUPYTER_PORT}` environment variable. + This may be useful if you run multiple instances of Jupyter in swarm mode and want to use a different port for each instance. ## Startup Hooks diff --git a/tests/base-notebook/test_container_options.py b/tests/base-notebook/test_container_options.py index bb3129e663..33a856221f 100644 --- a/tests/base-notebook/test_container_options.py +++ b/tests/base-notebook/test_container_options.py @@ -78,3 +78,39 @@ def test_unsigned_ssl( assert "ERROR" not in logs warnings = TrackedContainer.get_warnings(logs) assert not warnings + + +@pytest.mark.parametrize( + "env", + [ + {}, + {"JUPYTER_PORT": 1234, "DOCKER_STACKS_JUPYTER_CMD": "lab"}, + {"JUPYTER_PORT": 2345, "DOCKER_STACKS_JUPYTER_CMD": "notebook"}, + {"JUPYTER_PORT": 3456, "DOCKER_STACKS_JUPYTER_CMD": "server"}, + {"JUPYTER_PORT": 4567, "DOCKER_STACKS_JUPYTER_CMD": "nbclassic"}, + {"JUPYTER_PORT": 5678, "RESTARTABLE": "yes"}, + {"JUPYTER_PORT": 6789}, + {"JUPYTER_PORT": 7890, "DOCKER_STACKS_JUPYTER_CMD": "notebook"}, + ], +) +def test_custom_internal_port( + container: TrackedContainer, + http_client: requests.Session, + env: dict[str, str], +) -> None: + """Container should be accessible from the host + when using custom internal port""" + host_port = find_free_port() + internal_port = env.get("JUPYTER_PORT", 8888) + running_container = container.run_detached( + command=["start-notebook.sh", "--NotebookApp.token=''"], + environment=env, + ports={internal_port: host_port}, + ) + resp = http_client.get(f"http://localhost:{host_port}") + resp.raise_for_status() + logs = running_container.logs().decode("utf-8") + LOGGER.debug(logs) + assert "ERROR" not in logs + warnings = TrackedContainer.get_warnings(logs) + assert not warnings diff --git a/tests/base-notebook/test_healthcheck.py b/tests/base-notebook/test_healthcheck.py index e6260fa2f5..954825c7fc 100644 --- a/tests/base-notebook/test_healthcheck.py +++ b/tests/base-notebook/test_healthcheck.py @@ -17,10 +17,12 @@ [ None, ["DOCKER_STACKS_JUPYTER_CMD=lab"], - ["RESTARTABLE=yes"], ["DOCKER_STACKS_JUPYTER_CMD=notebook"], ["DOCKER_STACKS_JUPYTER_CMD=server"], ["DOCKER_STACKS_JUPYTER_CMD=nbclassic"], + ["RESTARTABLE=yes"], + ["JUPYTER_PORT=8171"], + ["JUPYTER_PORT=8117", "DOCKER_STACKS_JUPYTER_CMD=notebook"], ], ) def test_health(container: TrackedContainer, env: Optional[list[str]]) -> None:
spotify__luigi-1809
Terminal Width affects Lock identification under Centos 6.5 The luigi.lock.getpcmd function will return a shorter command line if the terminal is smaller in width. This can result in locks being misidentified as identical and can be a significant problem if your binary/scripts are located in deep paths. Presumably there is some option that can be passed to ps to resolve this. edit: It looks like if the ps command is changed to `ps x -wwo pid,args` that should take care of it.
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#...
[ { "content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#...
diff --git a/luigi/lock.py b/luigi/lock.py index cf73f1279b..702629184f 100644 --- a/luigi/lock.py +++ b/luigi/lock.py @@ -42,7 +42,7 @@ def getpcmd(pid): _, val = lines return val else: - cmd = 'ps -xo pid,args' + cmd = 'ps x -wwo pid,args' with os.popen(cmd, 'r') as p: # Skip the column titles p.readline()
xorbitsai__inference-1096
ENH: Add the option to use CPU to inference even there is GPU device ### Is your feature request related to a problem? Please describe There is a GPU in my server, but when load some LLM model, I need load it into my memory because the model size is bigger than GPU memory. However, when I launch the model from web page, the N-GPU setting only contains auto, 0, 1 options, if I select 0, system will complain the following error: > Server error: 400 - [address=0.0.0.0:19270, pid=2063850] The parameter `n_gpu` must be greater than 0 and not greater than the number of GPUs: 1 on the machine. ### Describe the solution you'd like I think when the N GPU setting is set to 0, it should use CPU as inference device.
[ { "content": "# Copyright 2022-2023 XProbe Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by ap...
[ { "content": "# Copyright 2022-2023 XProbe Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by ap...
diff --git a/xinference/device_utils.py b/xinference/device_utils.py index 731c6ae051..035391ccb4 100644 --- a/xinference/device_utils.py +++ b/xinference/device_utils.py @@ -92,8 +92,6 @@ def gpu_count(): ) return min(torch.cuda.device_count(), len(cuda_visible_devices)) - elif torch.backends.mps.is_available(): - return 1 elif is_xpu_available(): return torch.xpu.device_count() else: diff --git a/xinference/web/ui/src/scenes/launch_model/modelCard.js b/xinference/web/ui/src/scenes/launch_model/modelCard.js index 3755257ff6..d854f0ee3c 100644 --- a/xinference/web/ui/src/scenes/launch_model/modelCard.js +++ b/xinference/web/ui/src/scenes/launch_model/modelCard.js @@ -109,6 +109,14 @@ const ModelCard = ({ url, modelData, gpuAvailable, is_custom = false }) => { } }, [modelFormat, modelSize, modelData]) + const getNGPURange = () => { + if (gpuAvailable === 0) { + // remain 'auto' for distributed situation + return ['auto', 'CPU'] + } + return ['auto', 'CPU'].concat(range(1, gpuAvailable)) + } + const launchModel = (url) => { if (isCallingApi || isUpdatingModel) { return @@ -124,7 +132,11 @@ const ModelCard = ({ url, modelData, gpuAvailable, is_custom = false }) => { model_size_in_billions: convertModelSize(modelSize), quantization: quantization, n_gpu: - nGPU === '0' ? null : nGPU === 'auto' ? 'auto' : parseInt(nGPU, 10), + parseInt(nGPU, 10) === 0 || nGPU === 'CPU' + ? null + : nGPU === 'auto' + ? 'auto' + : parseInt(nGPU, 10), replica: replica, } @@ -512,24 +524,13 @@ const ModelCard = ({ url, modelData, gpuAvailable, is_custom = false }) => { onChange={(e) => setNGPU(e.target.value)} label="N-GPU" > - {['auto'] - .concat( - range( - 0, - modelFormat !== 'pytorch' && - modelFormat !== 'gptq' && - modelFormat !== 'awq' - ? 1 - : gpuAvailable - ) + {getNGPURange().map((v) => { + return ( + <MenuItem key={v} value={v}> + {v} + </MenuItem> ) - .map((v) => { - return ( - <MenuItem key={v} value={v}> - {v} - </MenuItem> - ) - })} + })} </Select> </FormControl> ) : (
freedomofpress__securedrop-5369
doc-linkcheck needs some appeasement ## Description We have a [CI failure because of a link to a private repo](https://app.circleci.com/jobs/github/freedomofpress/securedrop/42146). ## Steps to Reproduce Run `make docs-linkcheck`. ## Expected Behavior That it would complete with no error. ## Actual Behavior The link to the private repo causes a 404. ## Comments That private URL should be added to `linkcheck_ignore` in `docs/conf.py`.
[ { "content": "# -*- coding: utf-8 -*-\n#\n# SecureDrop documentation build configuration file, created by\n# sphinx-quickstart on Tue Oct 13 12:08:52 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in...
[ { "content": "# -*- coding: utf-8 -*-\n#\n# SecureDrop documentation build configuration file, created by\n# sphinx-quickstart on Tue Oct 13 12:08:52 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in...
diff --git a/docs/conf.py b/docs/conf.py index 46b973917e..c11c77fac9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -309,4 +309,5 @@ r'http://localhost(:\d+)?/?', 'https://forum.securedrop.org/admin/users/list/active', 'https://weblate.securedrop.org/projects/securedrop/securedrop/#repository', + 'https://github.com/freedomofpress/securedrop-debian-packages-lfs', ] diff --git a/docs/development/i18n.rst b/docs/development/i18n.rst index 1a8fd2e6f7..6d738e7873 100644 --- a/docs/development/i18n.rst +++ b/docs/development/i18n.rst @@ -351,20 +351,20 @@ Two weeks before the release: string freeze When features for a new SecureDrop release are frozen, the localization manager for the release will: * :ref:`merge_develop_to_weblate`. +* Update the `i18n timeline`_ in the translation section of the forum. * Post an announcement `to the translation section of the forum <https://forum.securedrop.org/c/translations>`__ (see `an example <https://forum.securedrop.org/t/4-securedrop-strings-need-work-march-2018-string-freeze/461>`__). -* Add a prominent Weblate whiteboard announcement that reads `The X.Y.Z deadline is Month day, year at midnight US/Pacific time. String freeze is in effect: no source strings will be modified before the release.`. -* Remind all developers about the string freeze, in the `chat room <https://gitter.im/freedomofpress/securedrop>`__. +* Remind all developers about the string freeze in `Gitter <https://gitter.im/freedomofpress/securedrop>`__. +* Add a `Weblate announcement`_ with the translation timeline for the release. * Create a pull request for every source string suggestion coming from translators. -* Update the `i18n timeline`_ and `Weblate whiteboard`_. Release day ^^^^^^^^^^^ * :ref:`merge_weblate_to_develop`. * :ref:`Update the screenshots <updating_screenshots>`. -* Remove the prominent Weblate whiteboard announcement. +* Remove the `Weblate announcement`_ about this release's translation timeline. * Provide translator credits to add to the SecureDrop release announcement. -* Update the `i18n timeline`_ and `Weblate whiteboard`_. +* Update the `i18n timeline`_ in the forum. Translator credits ^^^^^^^^^^^^^^^^^^ @@ -466,7 +466,7 @@ with a release looming, the server can be rebooted. .. _`Weblate translation creation page`: https://weblate.securedrop.org/new-lang/securedrop/securedrop/ .. _`Weblate desktop translation creation page`: https://weblate.securedrop.org/new-lang/securedrop/desktop/ .. _`i18n timeline`: https://forum.securedrop.org/t/about-the-translations-category/16 -.. _`Weblate whiteboard`: https://weblate.securedrop.org/admin/trans/whiteboardmessage/6/change/ +.. _`Weblate announcement`: https://weblate.securedrop.org/admin/trans/announcement .. |Weblate commit Lock| image:: ../images/weblate/admin-lock.png .. |Weblate commit Locked| image:: ../images/weblate/admin-locked.png diff --git a/docs/hardware.rst b/docs/hardware.rst index f6be365fe5..040ba17057 100644 --- a/docs/hardware.rst +++ b/docs/hardware.rst @@ -434,10 +434,6 @@ support is preferable, since you want neither WiFi nor Bluetooth. updating the BIOS according to `these instructions <http://arstechnica.com/gadgets/2014/02/new-intel-nuc-bios-update-fixes-steamos-other-linux-booting-problems/>`__. -.. caution:: Some older NUC BIOS versions will cause the server to `brick itself <https://communities.intel.com/message/359708>`__ if the device - attempts to suspend. This has `since been fixed <https://communities.intel.com/message/432692>`__ - in a BIOS update. See these `release notes <https://downloadmirror.intel.com/29454/eng/RY_0384_ReleaseNotes.pdf>`__ (PDF) for more details. - 2014 Mac Minis ~~~~~~~~~~~~~~ diff --git a/docs/includes/update-gui.txt b/docs/includes/update-gui.txt index ee9d8b5cd0..08aa668c46 100644 --- a/docs/includes/update-gui.txt +++ b/docs/includes/update-gui.txt @@ -8,4 +8,4 @@ in the updater to perform the update. do so, you will need to reboot to enable it. .. _`Tails Administrator - password`: https://tails.boum.org/doc/first_steps/welcome_screen/administration_password/index.en.html + password`: https://tails.boum.org/doc/first_steps/welcome_screen/administration_password/ diff --git a/docs/set_up_transfer_and_export_device.rst b/docs/set_up_transfer_and_export_device.rst index d61d4ad232..0eb5298845 100644 --- a/docs/set_up_transfer_and_export_device.rst +++ b/docs/set_up_transfer_and_export_device.rst @@ -232,7 +232,7 @@ mitigate that risk. One option is to restrict write access to the *Export Device* before it is plugged into a device other than the *Secure Viewing Station*. Some USB flash -drives come with a physical write protection switch, and `write blockers <https://www.forensicswiki.org/wiki/Write_Blockers>`__ +drives come with a physical write protection switch, and `write blockers <https://forensicswiki.xyz/wiki/index.php?title=Write_Blockers>`__ are used in forensics to ensure storage media are not modified during examination. diff --git a/docs/tails_printing_guide.rst b/docs/tails_printing_guide.rst index 339c9b00b6..4456d8478a 100644 --- a/docs/tails_printing_guide.rst +++ b/docs/tails_printing_guide.rst @@ -41,7 +41,7 @@ Installing and Printing via the Tails GUI Let's look at the flow in Tails 4 for installing a USB-connected printer. On the Tails welcome screen, unlock your persistent volume, and -`set an admin password <https://tails.boum.org/doc/first_steps/startup_options/administration_password/index.en.html>`__. +`set an admin password <https://tails.boum.org/doc/first_steps/welcome_screen/administration_password/>`__. This ensures that you won't have to reinstall the printer each time you start Tails.
huggingface__accelerate-177
TypeError: Can't apply _send_to_device on object of type <class 'int'>, only of nested list/tuple/dicts of objects that satisfy _has_to_method. When I use 0.4.0 version , it is ok. But it is error when using 0.5.1 version. And the data is a dict, including tensor and List[List[int]]
[ { "content": "# Copyright 2021 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#...
[ { "content": "# Copyright 2021 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#...
diff --git a/src/accelerate/utils.py b/src/accelerate/utils.py index e25b80c4976..28a38539adb 100644 --- a/src/accelerate/utils.py +++ b/src/accelerate/utils.py @@ -201,7 +201,7 @@ def _send_to_device(t, device): def _has_to_method(t): return hasattr(t, "to") - return recursively_apply(_send_to_device, tensor, device, test_type=_has_to_method, error_on_other_type=True) + return recursively_apply(_send_to_device, tensor, device, test_type=_has_to_method) def get_data_structure(data): diff --git a/tests/test_utils.py b/tests/test_utils.py index ca617634dd9..9b16aba7bed 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -20,7 +20,7 @@ from accelerate.utils import send_to_device -TestNamedTuple = namedtuple("TestNamedTuple", "a b") +TestNamedTuple = namedtuple("TestNamedTuple", "a b c") class UtilsTester(unittest.TestCase): @@ -31,23 +31,26 @@ def test_send_to_device(self): result1 = send_to_device(tensor, device) self.assertTrue(torch.equal(result1.cpu(), tensor)) - result2 = send_to_device((tensor, [tensor, tensor]), device) + result2 = send_to_device((tensor, [tensor, tensor], 1), device) self.assertIsInstance(result2, tuple) self.assertTrue(torch.equal(result2[0].cpu(), tensor)) self.assertIsInstance(result2[1], list) self.assertTrue(torch.equal(result2[1][0].cpu(), tensor)) self.assertTrue(torch.equal(result2[1][1].cpu(), tensor)) + self.assertEqual(result2[2], 1) - result2 = send_to_device({"a": tensor, "b": [tensor, tensor]}, device) + result2 = send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}, device) self.assertIsInstance(result2, dict) self.assertTrue(torch.equal(result2["a"].cpu(), tensor)) self.assertIsInstance(result2["b"], list) self.assertTrue(torch.equal(result2["b"][0].cpu(), tensor)) self.assertTrue(torch.equal(result2["b"][1].cpu(), tensor)) + self.assertEqual(result2["c"], 1) - result3 = send_to_device(TestNamedTuple(a=tensor, b=[tensor, tensor]), device) + result3 = send_to_device(TestNamedTuple(a=tensor, b=[tensor, tensor], c=1), device) self.assertIsInstance(result3, TestNamedTuple) self.assertTrue(torch.equal(result3.a.cpu(), tensor)) self.assertIsInstance(result3.b, list) self.assertTrue(torch.equal(result3.b[0].cpu(), tensor)) self.assertTrue(torch.equal(result3.b[1].cpu(), tensor)) + self.assertEqual(result3.c, 1)
readthedocs__readthedocs.org-10947
Teams: project form doesn't allow for null/empty project list I found trying to remove a project from a team that it was impossible to remove the project if it was the last project attached to the team. The form expects some non-null value and throws a validation error if the list is empty. To reproduce: - Add a team - Add a project to the team - Try to remove the project from the team - You'll get a validation error on the form Instead, this should be a valid form submission and the team should have 0 projects attached.
[ { "content": "\"\"\"Organization forms.\"\"\"\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import NON_FIELD_ERRORS, ValidationError\nfrom django.core.validators import EmailValidator\nfrom django.db.models import Q\nfrom django.utils.translation import gett...
[ { "content": "\"\"\"Organization forms.\"\"\"\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import NON_FIELD_ERRORS, ValidationError\nfrom django.core.validators import EmailValidator\nfrom django.db.models import Q\nfrom django.utils.translation import gett...
diff --git a/readthedocs/organizations/forms.py b/readthedocs/organizations/forms.py index 0120c05ae5a..85fc7ae3818 100644 --- a/readthedocs/organizations/forms.py +++ b/readthedocs/organizations/forms.py @@ -208,6 +208,7 @@ def __init__(self, *args, **kwargs): self.fields["projects"] = forms.ModelMultipleChoiceField( queryset=self.organization.projects, widget=forms.CheckboxSelectMultiple, + required=False, )
vyperlang__vyper-2905
Missing @view decorator for interface ERC20Detailed.py ### Version Information * vyper Version (output of `vyper --version`): 0.3.3 * OS: linux * Python Version (output of `python --version`): Python 3.9.5 ### What's your issue about? **Issue** Error using `ERC20Detailed.py` as an interface to a vyper class. Trying to compile the following snippet produces the following error. ``` # @version 0.3.3 from vyper.interfaces import ERC20Detailed @view @external def getSymbol() -> String[32]: return ERC20Detailed(0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2).symbol() ``` **Error** ``` vyper.exceptions.StateAccessViolation: May not call state modifying function 'symbol' within a constant function.vyper.exceptions.StateAccessViolation: May not call state modifying function 'symbol' within a constant function. ``` **Reason** This issue occurs because `ERC20Detailed.py` does not contain `@view` decorator for its interfaces ### How can it be fixed? Adding `@view` decorator to interface under `vyper.builtin_interfaces.ERC20Detailed.py` ``` @external @view def name() -> String[1]: pass @external @view def symbol() -> String[1]: pass @external @view def decimals() -> uint8: pass ``` **Why?** Running `vyper -f interface examples/tokens/ERC20.vy` generates the following ``` ... @view @external def name() -> String[32]: pass @view @external def symbol() -> String[32]: pass @view @external def decimals() -> uint8: pass ... ``` Adding `@view` decorator to `vyper.builtin_interfaces.ERC20Detailed.py` would make interface consistent.
[ { "content": "\"\"\"\nNOTE: interface uses `String[1]` where 1 is the lower bound of the string returned by the function.\n For end-users this means they can't use `implements: ERC20Detailed` unless their implementation\n uses a value n >= 1. Regardless this is fine as one can't do String[0] where n == 0....
[ { "content": "\"\"\"\nNOTE: interface uses `String[1]` where 1 is the lower bound of the string returned by the function.\n For end-users this means they can't use `implements: ERC20Detailed` unless their implementation\n uses a value n >= 1. Regardless this is fine as one can't do String[0] where n == 0....
diff --git a/vyper/builtin_interfaces/ERC20Detailed.py b/vyper/builtin_interfaces/ERC20Detailed.py index 23f4a8a844..03dd597e8a 100644 --- a/vyper/builtin_interfaces/ERC20Detailed.py +++ b/vyper/builtin_interfaces/ERC20Detailed.py @@ -5,14 +5,17 @@ """ interface_code = """ +@view @external def name() -> String[1]: pass +@view @external def symbol() -> String[1]: pass +@view @external def decimals() -> uint8: pass
ivy-llc__ivy-14109
frombuffer
[ { "content": "# local\nimport ivy\nfrom ivy.func_wrapper import with_unsupported_dtypes\nfrom ivy.functional.frontends.torch.func_wrapper import to_ivy_arrays_and_back\n\n\n@to_ivy_arrays_and_back\ndef empty(\n *args,\n size=None,\n out=None,\n dtype=None,\n layout=None,\n device=None,\n re...
[ { "content": "# local\nimport ivy\nfrom ivy.func_wrapper import with_unsupported_dtypes\nfrom ivy.functional.frontends.torch.func_wrapper import to_ivy_arrays_and_back\n\n\n@to_ivy_arrays_and_back\ndef empty(\n *args,\n size=None,\n out=None,\n dtype=None,\n layout=None,\n device=None,\n re...
diff --git a/ivy/functional/frontends/torch/creation_ops.py b/ivy/functional/frontends/torch/creation_ops.py index 458d7e00a8de8..8231d6368b7fc 100644 --- a/ivy/functional/frontends/torch/creation_ops.py +++ b/ivy/functional/frontends/torch/creation_ops.py @@ -285,3 +285,15 @@ def asarray( copy=None, ): return ivy.asarray(obj, copy=copy, dtype=dtype, device=device) + + +@to_ivy_arrays_and_back +def frombuffer( + buffer, + *, + dtype, + count=-1, + offset=0, + requires_grad=False, +): + return ivy.frombuffer(buffer, dtype=dtype, count=count, offset=offset) diff --git a/ivy_tests/test_ivy/test_frontends/test_torch/test_creation_ops.py b/ivy_tests/test_ivy/test_frontends/test_torch/test_creation_ops.py index af62da7f03174..a5b373590888c 100644 --- a/ivy_tests/test_ivy/test_frontends/test_torch/test_creation_ops.py +++ b/ivy_tests/test_ivy/test_frontends/test_torch/test_creation_ops.py @@ -2,6 +2,7 @@ import ivy from hypothesis import strategies as st, assume import math +import numpy as np # local import ivy_tests.test_ivy.helpers as helpers @@ -688,3 +689,48 @@ def test_torch_from_dlpack( fn_tree=fn_tree, on_device=on_device, ) + + +@st.composite +def _get_dtype_buffer_count_offset(draw): + dtype, value = draw( + helpers.dtype_and_values( + available_dtypes=helpers.get_dtypes("valid"), + ) + ) + value = np.array(value) + length = value.size + value = value.tobytes() + + offset = draw(helpers.ints(min_value=0, max_value=length - 1)) + count = draw(helpers.ints(min_value=-(2**30), max_value=length - offset)) + if count == 0: + count = -1 + offset = offset * np.dtype(dtype[0]).itemsize + + return dtype, value, count, offset + + +@handle_frontend_test( + fn_tree="torch.frombuffer", + dtype_buffer_count_offset=_get_dtype_buffer_count_offset(), +) +def test_torch_frombuffer( + dtype_buffer_count_offset, + test_flags, + frontend, + fn_tree, + on_device, +): + input_dtype, buffer, count, offset = dtype_buffer_count_offset + helpers.test_frontend_function( + input_dtypes=input_dtype, + test_flags=test_flags, + on_device=on_device, + frontend=frontend, + fn_tree=fn_tree, + buffer=buffer, + dtype=input_dtype[0], + count=count, + offset=offset, + )
pymedusa__Medusa-1543
[APP SUBMITTED]: ==================================================================== ### INFO **Python Version**: `2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)]` **Operating System**: `Windows-8.1-6.3.9600` **Locale**: `cp1252` **Branch**: [master](../tree/master) **Commit**: PyMedusa/SickRage@9c6346bedbf9deec3efc4ea60cf0f9bb5ce818b5 **Link to Log**: https://gist.github.com/a98d151bbf9b8345c030445e3fdfe507 ### ERROR <pre> 2016-09-12 22:30:22 ERROR Thread-19 :: [9c6346b] Failed doing web ui callback: Traceback (most recent call last): File "C:\Users\uTorrentVM\SickRage\sickbeard\server\web\core\base.py", line 270, in async_call result = function(**kwargs) File "C:\Users\uTorrentVM\SickRage\sickbeard\server\web\home\post_process.py", line 50, in processEpisode is_priority=argToBool(is_priority), delete_on=argToBool(delete_on), failed=argToBool(failed), proc_type=type, ignore_subs=argToBool(ignore_subs) File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 303, in processDir process_media(processPath, videoFiles, nzbName, process_method, force, is_priority, ignore_subs, result) File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 571, in process_media if already_postprocessed(processPath, cur_video_file, force, result): File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 531, in already_postprocessed parse_result = NameParser(try_indexers=True).parse(dirName) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\parser.py", line 235, in parse result = self._parse_string(name) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\parser.py", line 62, in _parse_string guess = guessit.guessit(name, dict(show_type=self.show_type)) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\guessit_parser.py", line 99, in guessit return default_api.guessit(name, options=final_options) File "C:\Users\uTorrentVM\SickRage\lib\guessit\api.py", line 113, in guessit raise GuessitException(string, options) GuessitException: An internal error has occured in guessit. ===================== Guessit Exception Report ===================== version=2.1.0.dev0 string=C:\Users\uTorrentVM\Downloads\Complete\sb\[HorribleSubs]_Mob_Psycho_100_-_10_[1080p]_mkv_[5_7]_-_`[HorribleSubs]_Mob_Psycho_100_-_10_[1080p]_vol03+04_par2` options={'allowed_languages': ['ru', 'hu', 'en', 'nl', 'pt', 'de', 'jp', 'sv', 'it', 'fr', 'es', 'uk', 'ro', 'pl', 'he'], 'expected_group': ['re:\\bCDD\\b', 're:\\bF4ST3R\\b', 're:\\bTGNF4ST\\b', 're:\\bNovaRip\\b', 're:\\bRiPRG\\b', 're:\\bPtM\\b', 're:\\bbyEMP\\b', 're:\\b4EVERHD\\b', 're:\\bPOURMOi\\b', 're:\\bPARTiCLE\\b', 're:\\bTV2LAX9\\b', 're:\\bCDP\\b', 're:\\bELITETORRENT\\b', 're:\\bRipPourBox\\b', 're:\\bF4ST\\b', 're:\\bHDD\\b'], 'expected_title': ['re:(?<![^/\\\\])\\w+ it\\b', 're:\\bMob +Psycho +100\\b'], 'allowed_countries': ['gb', 'us'], 'episode_prefer_number': False, 'show_type': None, 'type': u'episode', 'implicit': True} -------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\uTorrentVM\SickRage\lib\guessit\api.py", line 102, in guessit matches = self.rebulk.matches(string, options) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rebulk.py", line 275, in matches self._execute_rules(matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rebulk.py", line 306, in _execute_rules rules.execute_all_rules(matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rules.py", line 318, in execute_all_rules when_response = execute_rule(rule, matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rules.py", line 339, in execute_rule when_response = rule.when(matches, context) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\rules\rules.py", line 1006, in when predicate=lambda match: (match.name == 'episode' and File "C:\Users\uTorrentVM\SickRage\lib\rebulk\match.py", line 115, in next current = match.start + 1 AttributeError: 'NoneType' object has no attribute 'start' -------------------------------------------------------------------- Please report at https://github.com/guessit-io/guessit/issues. ==================================================================== Traceback (most recent call last): File "C:\Users\uTorrentVM\SickRage\sickbeard\server\web\core\base.py", line 270, in async_call result = function(**kwargs) File "C:\Users\uTorrentVM\SickRage\sickbeard\server\web\home\post_process.py", line 50, in processEpisode is_priority=argToBool(is_priority), delete_on=argToBool(delete_on), failed=argToBool(failed), proc_type=type, ignore_subs=argToBool(ignore_subs) File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 303, in processDir process_media(processPath, videoFiles, nzbName, process_method, force, is_priority, ignore_subs, result) File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 571, in process_media if already_postprocessed(processPath, cur_video_file, force, result): File "C:\Users\uTorrentVM\SickRage\sickbeard\processTV.py", line 531, in already_postprocessed parse_result = NameParser(try_indexers=True).parse(dirName) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\parser.py", line 235, in parse result = self._parse_string(name) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\parser.py", line 62, in _parse_string guess = guessit.guessit(name, dict(show_type=self.show_type)) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\guessit_parser.py", line 99, in guessit return default_api.guessit(name, options=final_options) File "C:\Users\uTorrentVM\SickRage\lib\guessit\api.py", line 113, in guessit raise GuessitException(string, options) GuessitException: An internal error has occured in guessit. ===================== Guessit Exception Report ===================== version=2.1.0.dev0 string=C:\Users\uTorrentVM\Downloads\Complete\sb\[HorribleSubs]_Mob_Psycho_100_-_10_[1080p]_mkv_[5_7]_-_`[HorribleSubs]_Mob_Psycho_100_-_10_[1080p]_vol03+04_par2` options={'allowed_languages': ['ru', 'hu', 'en', 'nl', 'pt', 'de', 'jp', 'sv', 'it', 'fr', 'es', 'uk', 'ro', 'pl', 'he'], 'expected_group': ['re:\\bCDD\\b', 're:\\bF4ST3R\\b', 're:\\bTGNF4ST\\b', 're:\\bNovaRip\\b', 're:\\bRiPRG\\b', 're:\\bPtM\\b', 're:\\bbyEMP\\b', 're:\\b4EVERHD\\b', 're:\\bPOURMOi\\b', 're:\\bPARTiCLE\\b', 're:\\bTV2LAX9\\b', 're:\\bCDP\\b', 're:\\bELITETORRENT\\b', 're:\\bRipPourBox\\b', 're:\\bF4ST\\b', 're:\\bHDD\\b'], 'expected_title': ['re:(?<![^/\\\\])\\w+ it\\b', 're:\\bMob +Psycho +100\\b'], 'allowed_countries': ['gb', 'us'], 'episode_prefer_number': False, 'show_type': None, 'type': u'episode', 'implicit': True} -------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\uTorrentVM\SickRage\lib\guessit\api.py", line 102, in guessit matches = self.rebulk.matches(string, options) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rebulk.py", line 275, in matches self._execute_rules(matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rebulk.py", line 306, in _execute_rules rules.execute_all_rules(matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rules.py", line 318, in execute_all_rules when_response = execute_rule(rule, matches, context) File "C:\Users\uTorrentVM\SickRage\lib\rebulk\rules.py", line 339, in execute_rule when_response = rule.when(matches, context) File "C:\Users\uTorrentVM\SickRage\sickbeard\name_parser\rules\rules.py", line 1006, in when predicate=lambda match: (match.name == 'episode' and File "C:\Users\uTorrentVM\SickRage\lib\rebulk\match.py", line 115, in next current = match.start + 1 AttributeError: 'NoneType' object has no attribute 'start' -------------------------------------------------------------------- Please report at https://github.com/guessit-io/guessit/issues. ==================================================================== </pre> --- _STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators
[ { "content": "# coding=utf-8\n# Author: Nic Wolfe <nic@wolfeden.ca>\n#\n# This file is part of Medusa.\n#\n# Medusa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or...
[ { "content": "# coding=utf-8\n# Author: Nic Wolfe <nic@wolfeden.ca>\n#\n# This file is part of Medusa.\n#\n# Medusa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or...
diff --git a/medusa/process_tv.py b/medusa/process_tv.py index 439becf959..8969357c02 100644 --- a/medusa/process_tv.py +++ b/medusa/process_tv.py @@ -652,6 +652,9 @@ def subtitles_enabled(*args): :rtype: bool """ for name in args: + if not name: + continue + try: parse_result = NameParser().parse(name, cache_result=True) if parse_result.show.indexerid:
mkdocs__mkdocs-694
current_page.ancestors only contains direct ancestor and not the full path of the page I'm using the mkdocs theme and tried to enhance it with a breadcrumb trail. The page navigation is created automatically by mkdocs (I don't use the pages confguration since I have almost 300 pages). I copied and adapted the `breadcrumbs.html` file from the readthedocs theme and integrated it in `content.html`: ``` <ol class="breadcrumb"> <li><a href="{{ homepage_url }}">Docs</a></li> {% if current_page %} {% for doc in current_page.ancestors %} {% if doc.link %} <li><a href="{{ doc.link|e }}">{{ doc.title }}</a></li> {% else %} <li>{{ doc.title }}</li> {% endif %} {% endfor %} {% endif %} {% if current_page %}<li>{{ current_page.title }}</li>{% endif %} </ol> ``` My file path (starting from the `docs_dir`) is: `beheerteam/diensten/algemeen/ActiveDirectory.md` The generated breadcrumb trail is: `Docs/algemeen/ActiveDirectory` `algemeen` is the only part that originates from the loop `for doc in current_page.ancestors`. Maybe this is a stupid question or it is just not possible, but I couldn't find i in the documentation and I'm just starting with mkdocs and couldn't understand the source on how this works.
[ { "content": "# coding: utf-8\n\n\"\"\"\nDeals with generating the site-wide navigation.\n\nThis consists of building a set of interlinked page and header objects.\n\"\"\"\n\nfrom __future__ import unicode_literals\nimport datetime\nimport logging\nimport os\n\nfrom mkdocs import utils, exceptions\n\nlog = logg...
[ { "content": "# coding: utf-8\n\n\"\"\"\nDeals with generating the site-wide navigation.\n\nThis consists of building a set of interlinked page and header objects.\n\"\"\"\n\nfrom __future__ import unicode_literals\nimport datetime\nimport logging\nimport os\n\nfrom mkdocs import utils, exceptions\n\nlog = logg...
diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md index 72c1604487..9418d6e7a3 100644 --- a/docs/about/release-notes.md +++ b/docs/about/release-notes.md @@ -50,6 +50,8 @@ themes theme. (#631) * Bugfix: Ensure consistent ordering of auto-populated pages. (#638) * Bugfix: Scroll the TOC on the MkDocs theme if it is too long for the page. +* Bugfix: Add all ancestors to the page attribute `ancestors` rather than just + the initial one. [site_description]: /user-guide/configuration.md#site_description [site_author]: /user-guide/configuration.md#site_author diff --git a/mkdocs/nav.py b/mkdocs/nav.py index 672ff4fffd..b72e21feb2 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -217,7 +217,7 @@ def _follow(config_line, url_context, use_dir_urls, header=None, title=None): page = _path_to_page(path, title, url_context, use_dir_urls) if header: - page.ancestors = [header] + page.ancestors = header.ancestors + [header, ] header.children.append(page) yield page diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py index 3c300887b7..84357d8d96 100644 --- a/mkdocs/tests/nav_tests.py +++ b/mkdocs/tests/nav_tests.py @@ -325,6 +325,9 @@ def test_ancestors(self): {'Running': 'api-guide/running.md'}, {'Testing': 'api-guide/testing.md'}, {'Debugging': 'api-guide/debugging.md'}, + {'Advanced': [ + {'Part 1': 'api-guide/advanced/part-1.md'}, + ]}, ]}, {'About': [ {'Release notes': 'about/release-notes.md'}, @@ -338,12 +341,18 @@ def test_ancestors(self): [site_navigation.nav_items[1]], [site_navigation.nav_items[1]], [site_navigation.nav_items[1]], + [site_navigation.nav_items[1], + site_navigation.pages[4].ancestors[-1]], [site_navigation.nav_items[2]], [site_navigation.nav_items[2]], ) - for page, expected_ancestor in zip(site_navigation.pages, ancestors): - self.assertEqual(page.ancestors, expected_ancestor) + self.assertEqual(len(site_navigation.pages), len(ancestors)) + + for i, (page, expected_ancestor) in enumerate( + zip(site_navigation.pages, ancestors)): + self.assertEqual(page.ancestors, expected_ancestor, + "Failed on ancestor test {0}".format(i)) def test_nesting(self):
GeotrekCE__Geotrek-admin-1571
Error - SHAPE export Trying to export TRAILS as a shape, send some errors emails to ADMIN : [Geotrek] ERROR: GDAL_ERROR 1: Field id of width 255 truncated to 254. [Geotrek] ERROR: GDAL_ERROR 1: Field name of width 255 truncated to 254. [Geotrek] ERROR: GDAL_ERROR 1: Field departure of width 255 truncated to 254. [Geotrek] ERROR: GDAL_ERROR 1: Field arrival of width 255 truncated to 254. Same when exporting PATH to shapes.
[ { "content": "import os\nimport logging\n\nfrom django.conf import settings\nfrom django.contrib.gis.db import models\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import MinValueValidator\nfrom django.template.defaultfilters import slugify\nfrom django.utils.translation impor...
[ { "content": "import os\nimport logging\n\nfrom django.conf import settings\nfrom django.contrib.gis.db import models\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import MinValueValidator\nfrom django.template.defaultfilters import slugify\nfrom django.utils.translation impor...
diff --git a/conf/buildout.cfg b/conf/buildout.cfg index e6542ec3fd..fb7898606a 100644 --- a/conf/buildout.cfg +++ b/conf/buildout.cfg @@ -69,7 +69,7 @@ paths = ${django:staticroot} [omelette] recipe = collective.recipe.omelette # We need mapentity templates and static dirs -eggs = +eggs = mapentity django-celery celery @@ -89,7 +89,7 @@ zc.buildout = 1.7.1 # From Geotrek # Django = 1.6.5 -mapentity = 2.5.2 +mapentity = 2.7.0 GDAL=1.10.0 tif2geojson=0.1.3 django-extended-choices = 0.3.0 diff --git a/docs/changelog.rst b/docs/changelog.rst index 7489fd31c4..461451e9e3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,10 @@ CHANGELOG **Bug fixes** * Allow NULL values for id_externe fields in database +* Fix missing elements (eg. POI enumeration) on trek map capture +* Prevent overlaping controls at bottom of list view +* Translation of column names in shapefiles export +* UTF-8 and truncated alerts in shapefile export 2.7.2 (2016-01-26) diff --git a/geotrek/maintenance/tests/test_views.py b/geotrek/maintenance/tests/test_views.py index 529f2d3f6c..164e8075fd 100644 --- a/geotrek/maintenance/tests/test_views.py +++ b/geotrek/maintenance/tests/test_views.py @@ -366,8 +366,8 @@ def test_shape_mixed(self): u'id', u'name', u'period', u'type', u'domain', u'constraint', u'global_cos', u'interventi', u'interven_1', u'comments', u'contractor', u'project_ow', u'project_ma', u'founders', - u'structure', u'date_inser', u'date_updat', - u'cities', u'districts', u'areas' + u'related_st', u'insertion_', u'update_dat', + u'cities', u'districts', u'restricted' ]) self.assertEquals(len(layer_point), 1) diff --git a/geotrek/trekking/models.py b/geotrek/trekking/models.py index d1777d8453..fa05c2ff0f 100755 --- a/geotrek/trekking/models.py +++ b/geotrek/trekking/models.py @@ -119,6 +119,7 @@ class Trek(StructureRelated, PicturesMixin, PublishableMixin, MapEntityMixin, To objects = Topology.get_manager_cls(models.GeoManager)() category_id_prefix = 'T' + capture_map_image_waitfor = '.poi_enum_loaded.services_loaded.info_desks_loaded.ref_points_loaded' class Meta: db_table = 'o_t_itineraire' diff --git a/geotrek/trekking/templates/trekking/trek_detail.html b/geotrek/trekking/templates/trekking/trek_detail.html index b3d43b0846..51edc0c893 100644 --- a/geotrek/trekking/templates/trekking/trek_detail.html +++ b/geotrek/trekking/templates/trekking/trek_detail.html @@ -73,6 +73,7 @@ map.addLayer(pois); pois.showEnumeration(); + $('.map-panel').addClass('poi_enum_loaded'); }); // @@ -90,6 +91,7 @@ }); map.layerscontrol.addOverlay(services, tr('services'), tr('Objects')); map.addLayer(services); + $('.map-panel').addClass('services_loaded'); }); // @@ -105,6 +107,7 @@ return L.marker(latlng, {icon: infoDeskIcon}); } }).addTo(map); + $('.map-panel').addClass('info_desks_loaded'); }); // @@ -125,6 +128,7 @@ }; })() }).addTo(map); + $('.map-panel').addClass('ref_points_loaded'); })(map); });
google__jax-5751
jax.devices() behaves unintuitively Hi! I noticed some unexpected (?) behaviour in the following code: ```python import jax from jax.config import config config.update("jax_backend_target", 'grpc://some endpoint:8470') config.update("jax_xla_backend", 'tpu_driver') print(jax.devices('cpu')) #prints tpu devices instead of cpu ``` I can get the expected behaviour if I do ```python import jax print(jax.devices('cpu')) #prints cpu devices from jax.config import config config.update("jax_backend_target", 'grpc://11.111.11.1118470') config.update("jax_xla_backend", 'tpu_driver') print(jax.devices('cpu')) #now prints cpu devices print(jax.devices('tpu')) #now prints tpu devices ``` I think this may be related the caching of `jax.lib.xla_bridge.get_backend()`. Not sure if this is expected behaviour or a bug. I noticed this because I was trying `jit` a few smaller functions on the host vm cpu during a larger TPU computation . I tried using the `backend=cpu` argument and `device_put`, but was unable to obtain the desired behaviour. In the end the only thing that seemed to work was to clear the cache of `get_backend()` reconfigure `jax.config` to cpu.
[ { "content": "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicab...
[ { "content": "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicab...
diff --git a/jax/lib/xla_bridge.py b/jax/lib/xla_bridge.py index aba3c6615edc..a292730c3db2 100644 --- a/jax/lib/xla_bridge.py +++ b/jax/lib/xla_bridge.py @@ -144,7 +144,9 @@ def _get_local_backend(platform=None): _tpu_backend = None def _get_tpu_driver_backend(platform): - del platform + if platform == "cpu": + return _get_local_backend("cpu") + global _tpu_backend if _tpu_backend is None: backend_target = FLAGS.jax_backend_target
scikit-hep__pyhf-1524
jaxlib v0.1.68 breaks CI with segfault on macOS # Description On 2021-06-22 the scheduled nightly CI for `v0.6.2` [was passing](https://github.com/scikit-hep/pyhf/actions/runs/962645978) and had installed libraries [pass-pip-list.txt](https://github.com/scikit-hep/pyhf/files/6713928/pass-pip-list.txt). Then on 2021-06-23 the CI [fails](https://github.com/scikit-hep/pyhf/actions/runs/966295835) with a segfault and had and had installed libraries [fail-pip-list.txt](https://github.com/scikit-hep/pyhf/files/6713929/fail-pip-list.txt), where the difference between them is the versions of `jax` and `jaxlib`. ``` $ diff pass-pip-list.txt fail-pip-list.txt 5a6 > appnope 0.1.2 41,42c42,43 < jax 0.2.14 < jaxlib 0.1.67 --- > jax 0.2.16 > jaxlib 0.1.68 97c98 < pyhf 0.6.2 /home/runner/work/pyhf/pyhf/src --- > pyhf 0.6.2 /Users/runner/work/pyhf/pyhf/src ``` The relevant section of the logs for the failure is the following: ```pytb src/pyhf/infer/utils.py .. [ 3%] Fatal Python error: Segmentation fault Thread 0x000070000dda9000 (most recent call first): File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/threading.py", line 306 in wait File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/threading.py", line 558 in wait File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/tqdm/_monitor.py", line 60 in run File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/threading.py", line 890 in _bootstrap Current thread 0x00000001050cfdc0 (most recent call first): File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jaxlib/xla_client.py", line 67 in make_cpu_client File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/lib/xla_bridge.py", line 206 in backends File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/lib/xla_bridge.py", line 242 in get_backend File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/lib/xla_bridge.py", line 263 in get_device_backend File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/interpreters/xla.py", line 138 in _device_put_array File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/interpreters/xla.py", line 133 in device_put File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/_src/lax/lax.py", line 1596 in _device_put_raw File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py", line 3025 in array File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py", line 3064 in asarray File "/Users/runner/work/pyhf/pyhf/src/pyhf/tensor/jax_backend.py", line 230 in astensor File "/Users/runner/work/pyhf/pyhf/src/pyhf/tensor/common.py", line 30 in _precompute File "/Users/runner/work/pyhf/pyhf/src/pyhf/events.py", line 36 in __call__ File "/Users/runner/work/pyhf/pyhf/src/pyhf/__init__.py", line 147 in set_backend File "/Users/runner/work/pyhf/pyhf/src/pyhf/events.py", line 93 in register_wrapper File "<doctest pyhf.tensor.jax_backend.jax_backend.astensor[1]>", line 1 in <module> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/doctest.py", line 1336 in __run File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/doctest.py", line 1483 in run File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/doctest.py", line 1844 in run File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/doctest.py", line 287 in runtest File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 162 in pytest_runtest_call File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/callers.py", line 187 in _multicall File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 84 in <lambda> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 93 in _hookexec File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/hooks.py", line 286 in __call__ File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 255 in <lambda> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 311 in from_call File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 254 in call_runtest_hook File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 215 in call_and_report File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 126 in runtestprotocol File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/runner.py", line 109 in pytest_runtest_protocol File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/callers.py", line 187 in _multicall File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 84 in <lambda> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 93 in _hookexec File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/hooks.py", line 286 in __call__ File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/main.py", line 348 in pytest_runtestloop File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/callers.py", line 187 in _multicall File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 84 in <lambda> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 93 in _hookexec File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/hooks.py", line 286 in __call__ File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/main.py", line 323 in _main File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/main.py", line 269 in wrap_session File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/main.py", line 316 in pytest_cmdline_main File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/callers.py", line 187 in _multicall File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 84 in <lambda> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/manager.py", line 93 in _hookexec File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pluggy/hooks.py", line 286 in __call__ File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/config/__init__.py", line 162 in main File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/_pytest/config/__init__.py", line 185 in console_main File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/pytest/__main__.py", line 5 in <module> File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/runpy.py", line 87 in _run_code File "/Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/runpy.py", line 194 in _run_module_as_main /Users/runner/work/_temp/b65896af-bc5b-4842-94da-e0fd5882e8d5.sh: line 1: 1785 Segmentation fault: 11 python -m pytest -r sx --ignore tests/benchmarks/ --ignore tests/contrib --ignore tests/test_notebooks.py /Users/runner/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/multiprocessing/resource_tracker.py:216: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown warnings.warn('resource_tracker: There appear to be %d ' src/pyhf/tensor/jax_backend.py Error: Process completed with exit code 139. ``` Both `jax` and `jaxlib` had releases on 2021-06-23: - [`jax` `v0.2.16`](https://pypi.org/project/jax/0.2.16/#history) - [`jaxlib` `v0.1.68`](https://pypi.org/project/jaxlib/0.1.68/#history) @lukasheinrich @kratsg we'll need to follow up with the JAX team.
[ { "content": "from setuptools import setup\n\nextras_require = {\n 'shellcomplete': ['click_completion'],\n 'tensorflow': [\n 'tensorflow~=2.2.1', # TensorFlow minor releases are as volatile as major\n 'tensorflow-probability~=0.10.1',\n ],\n 'torch': ['torch~=1.8'],\n 'jax': ['jax...
[ { "content": "from setuptools import setup\n\nextras_require = {\n 'shellcomplete': ['click_completion'],\n 'tensorflow': [\n 'tensorflow~=2.2.1', # TensorFlow minor releases are as volatile as major\n 'tensorflow-probability~=0.10.1',\n ],\n 'torch': ['torch~=1.8'],\n 'jax': ['jax...
diff --git a/setup.py b/setup.py index 55a4de07c7..036df19c41 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ 'tensorflow-probability~=0.10.1', ], 'torch': ['torch~=1.8'], - 'jax': ['jax~=0.2.8', 'jaxlib~=0.1.58,<0.1.68'], + 'jax': ['jax~=0.2.8', 'jaxlib~=0.1.58,!=0.1.68'], # c.f. Issue 1501 'xmlio': [ 'uproot3>=3.14.1', 'uproot~=4.0',
pwndbg__pwndbg-958
xinfo command doesn't like anonymous page names The naming of anonymous memory pages introduced in 462eb53 is cool but it doesn't play nicely with the `xinfo` command. The following figure shows `xinfo` behaving correctly when displaying info on a regular mapping, followed by an error when used with an anonymous mapping. ![xinfo](https://user-images.githubusercontent.com/16000770/133327381-c4f9d13b-5d20-4fd3-80b5-01aad51a5387.png) `xinfo` uses `page.is_memory_mapped_file()` to determine whether a page is file backed, this in turn is based on the object name: https://github.com/pwndbg/pwndbg/blob/648c7f014e25a2944ee40891000fb43031182e51/pwndbg/memory.py#L409-L411 Because 462eb53 names anonymous pages that previously had no name, the above function reports them as memory mapped files which `xinfo` tries to open. A possible solution could be to enclose the anonymous page names in square brackets, which `is_memory_mapped_file()` ignores.
[ { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nRoutines to enumerate mapped memory, and attempt to associate\naddress ranges with various ELF files and permissions.\n\nThe reason that we need robustness is that not every operating\nsystem has /proc/$$/maps, which backs 'info proc mapping'...
[ { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nRoutines to enumerate mapped memory, and attempt to associate\naddress ranges with various ELF files and permissions.\n\nThe reason that we need robustness is that not every operating\nsystem has /proc/$$/maps, which backs 'info proc mapping'...
diff --git a/pwndbg/vmmap.py b/pwndbg/vmmap.py index 9f7604c3bd1..456603b0ecc 100644 --- a/pwndbg/vmmap.py +++ b/pwndbg/vmmap.py @@ -212,7 +212,7 @@ def proc_pid_maps(): try: inode, objfile = inode_objfile.split(None, 1) except: - objfile = 'anon_' + start[:-3] + objfile = '[anon_' + start[:-3] + ']' start = int(start, 16) stop = int(stop, 16)
ivy-llc__ivy-22625
remainder
[ { "content": "# local\nimport ivy\nimport ivy.functional.frontends.paddle as paddle_frontend\nfrom ivy.func_wrapper import (\n with_supported_dtypes,\n with_unsupported_dtypes,\n)\nfrom ivy.functional.frontends.paddle.func_wrapper import _to_ivy_array\n\n\nclass Tensor:\n def __init__(self, array, dtyp...
[ { "content": "# local\nimport ivy\nimport ivy.functional.frontends.paddle as paddle_frontend\nfrom ivy.func_wrapper import (\n with_supported_dtypes,\n with_unsupported_dtypes,\n)\nfrom ivy.functional.frontends.paddle.func_wrapper import _to_ivy_array\n\n\nclass Tensor:\n def __init__(self, array, dtyp...
diff --git a/ivy/functional/frontends/paddle/tensor/tensor.py b/ivy/functional/frontends/paddle/tensor/tensor.py index b621b83084113..fda3fc4d9ff1a 100644 --- a/ivy/functional/frontends/paddle/tensor/tensor.py +++ b/ivy/functional/frontends/paddle/tensor/tensor.py @@ -654,3 +654,7 @@ def std(self, axis=None, unbiased=True, keepdim=False, name=None): ) def trunc(self, name=None): return paddle_frontend.Tensor(ivy.trunc(self._ivy_array)) + + @with_unsupported_dtypes({"2.5.1 and below": ("float16", "bfloat16")}, "paddle") + def remainder(self, y, name=None): + return ivy.remainder(self._ivy_array, y) diff --git a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_tensor.py b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_tensor.py index 5a8ddd8609dfc..112e2c73a6007 100644 --- a/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_tensor.py +++ b/ivy_tests/test_ivy/test_frontends/test_paddle/test_tensor/test_tensor.py @@ -3020,3 +3020,42 @@ def test_torch_tensor_sqrt_( frontend=frontend, on_device=on_device, ) + + +# remainder +@handle_frontend_method( + class_tree=CLASS_TREE, + init_tree="paddle.to_tensor", + method_name="remainder", + dtype_and_x=helpers.dtype_and_values( + available_dtypes=helpers.get_dtypes("float"), + num_arrays=2, + allow_inf=False, + large_abs_safety_factor=2, + small_abs_safety_factor=2, + safety_factor_scale="log", + shared_dtype=True, + ), +) +def test_paddle_tensor_remainder( + dtype_and_x, + frontend_method_data, + init_flags, + method_flags, + frontend, + on_device, + backend_fw, +): + input_dtype, x = dtype_and_x + helpers.test_frontend_method( + init_input_dtypes=input_dtype, + backend_to_test=backend_fw, + init_all_as_kwargs_np={"data": x[0]}, + method_input_dtypes=input_dtype, + method_all_as_kwargs_np={"y": x[1]}, + frontend_method_data=frontend_method_data, + init_flags=init_flags, + method_flags=method_flags, + frontend=frontend, + on_device=on_device, + )
akvo__akvo-rsr-2137
Bug in project document category API ## Test plan The project_document_category should not give an error. E.g. `http://rsr.localdev.akvo.org/rest/v1/project_document_category/` should load. ## Issue description The project document category API gives an error. See http://sentry.support.akvo-ops.org/rsr/test/group/879/, or on the Test server: http://rsr.test.akvo.org/rest/v1/project_document_category/.
[ { "content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nfrom akv...
[ { "content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nfrom akv...
diff --git a/akvo/rest/views/project_document.py b/akvo/rest/views/project_document.py index a91a48968e..705e1df3ba 100644 --- a/akvo/rest/views/project_document.py +++ b/akvo/rest/views/project_document.py @@ -24,3 +24,4 @@ class ProjectDocumentCategoryViewSet(PublicProjectViewSet): queryset = ProjectDocumentCategory.objects.all() serializer_class = ProjectDocumentCategorySerializer filter_fields = ('document__project', 'document', 'category', ) + project_relation = 'document__project__'
pypi__warehouse-3056
Disable 'delete confirm' button until confirmation word is correct We currently have a modal on `warehouse/templates/manage/settings.html`, that allows the user to confirm that they want to delete their project: ![screenshot from 2018-02-03 14-43-29](https://user-images.githubusercontent.com/3323703/35768242-9dcfc21a-08f0-11e8-834d-fdcc3e6cd998.png) The user is required to enter the project name as an extra security measure. If they get it wrong, we show them this error: ![screenshot from 2018-02-03 14-44-19](https://user-images.githubusercontent.com/3323703/35768249-bba976d2-08f0-11e8-97ba-99c37bfc7479.png) ## Proposal It would be really nice if we could `disable` the delete button until the correct project name is given, e.g. ![screenshot from 2018-02-03 14-46-02](https://user-images.githubusercontent.com/3323703/35768271-fa2cdc64-08f0-11e8-848f-58433e60ae6b.png) ![screenshot from 2018-02-03 14-46-25](https://user-images.githubusercontent.com/3323703/35768274-0692bca8-08f1-11e8-9149-3aa7a5faad65.png) ## Notes We will have several other delete confirmation modals on other pages, sometimes with multiple modals on a single page (e.g. delete release, delete file) - so the code will need to be written to take this into account.
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, softw...
[ { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, softw...
diff --git a/.babelrc b/.babelrc index 002b4aa0d58e..10966c1f5a0c 100644 --- a/.babelrc +++ b/.babelrc @@ -1,3 +1,4 @@ { - "presets": ["env"] + "presets": ["env"], + "plugins": ["transform-class-properties"] } diff --git a/Gulpfile.babel.js b/Gulpfile.babel.js index 238b8a446aa1..dfdc96153cb8 100644 --- a/Gulpfile.babel.js +++ b/Gulpfile.babel.js @@ -44,6 +44,7 @@ let webpackConfig = { loader: "babel-loader", options: { presets: ["env"], + plugins: ["transform-class-properties"], }, }, }, diff --git a/package-lock.json b/package-lock.json index 8456afee7e7a..0f921dbd9d39 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2,6 +2,183 @@ "requires": true, "lockfileVersion": 1, "dependencies": { + "@babel/code-frame": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-beta.40.tgz", + "integrity": "sha512-eVXQSbu/RimU6OKcK2/gDJVTFcxXJI4sHbIqw2mhwMZeQ2as/8AhS9DGkEDoHMBBNJZ5B0US63lF56x+KDcxiA==", + "dev": true, + "requires": { + "@babel/highlight": "7.0.0-beta.40" + } + }, + "@babel/generator": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.0.0-beta.40.tgz", + "integrity": "sha512-c91BQcXyTq/5aFV4afgOionxZS1dxWt8OghEx5Q52SKssdGRFSiMKnk9tGkev1pYULPJBqjSDZU2Pcuc58ffZw==", + "dev": true, + "requires": { + "@babel/types": "7.0.0-beta.40", + "jsesc": "2.5.1", + "lodash": "4.17.4", + "source-map": "0.5.7", + "trim-right": "1.0.1" + }, + "dependencies": { + "jsesc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.1.tgz", + "integrity": "sha1-5CGiqOINawgZ3yiQj3glJrlt0f4=", + "dev": true + } + } + }, + "@babel/helper-function-name": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.0.0-beta.40.tgz", + "integrity": "sha512-cK9BVLtOfisSISTTHXKGvBc2OBh65tjEk4PgXhsSnnH0i8RP2v+5RCxoSlh2y/i+l2fxQqKqv++Qo5RMiwmRCA==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "7.0.0-beta.40", + "@babel/template": "7.0.0-beta.40", + "@babel/types": "7.0.0-beta.40" + } + }, + "@babel/helper-get-function-arity": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0-beta.40.tgz", + "integrity": "sha512-MwquaPznI4cUoZEgHC/XGkddOXtqKqD4DvZDOyJK2LR9Qi6TbMbAhc6IaFoRX7CRTFCmtGeu8gdXW2dBotBBTA==", + "dev": true, + "requires": { + "@babel/types": "7.0.0-beta.40" + } + }, + "@babel/highlight": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0-beta.40.tgz", + "integrity": "sha512-mOhhTrzieV6VO7odgzFGFapiwRK0ei8RZRhfzHhb6cpX3QM8XXuCLXWjN8qBB7JReDdUR80V3LFfFrGUYevhNg==", + "dev": true, + "requires": { + "chalk": "2.3.1", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", + "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", + "dev": true, + "requires": { + "color-convert": "1.9.1" + } + }, + "chalk": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.1.tgz", + "integrity": "sha512-QUU4ofkDoMIVO7hcx1iPTISs88wsO8jA92RQIm4JAwZvFGGAV2hSAA1NX7oVj2Ej2Q6NDTcRDjPTFrMCRZoJ6g==", + "dev": true, + "requires": { + "ansi-styles": "3.2.0", + "escape-string-regexp": "1.0.5", + "supports-color": "5.2.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "supports-color": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.2.0.tgz", + "integrity": "sha512-F39vS48la4YvTZUPVeTqsjsFNrvcMwrV3RLZINsmHo+7djCvuUzSIeXOnZ5hmjef4bajL1dNccN+tg5XAliO5Q==", + "dev": true, + "requires": { + "has-flag": "3.0.0" + } + } + } + }, + "@babel/template": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.0.0-beta.40.tgz", + "integrity": "sha512-RlQiVB7eL7fxsKN6JvnCCwEwEL28CBYalXSgWWULuFlEHjtMoXBqQanSie3bNyhrANJx67sb+Sd/vuGivoMwLQ==", + "dev": true, + "requires": { + "@babel/code-frame": "7.0.0-beta.40", + "@babel/types": "7.0.0-beta.40", + "babylon": "7.0.0-beta.40", + "lodash": "4.17.4" + }, + "dependencies": { + "babylon": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.40.tgz", + "integrity": "sha512-AVxF2EcxvGD5hhOuLTOLAXBb0VhwWpEX0HyHdAI2zU+AAP4qEwtQj8voz1JR3uclGai0rfcE+dCTHnNMOnimFg==", + "dev": true + } + } + }, + "@babel/traverse": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.0.0-beta.40.tgz", + "integrity": "sha512-h96SQorjvdSuxQ6hHFIuAa3oxnad1TA5bU1Zz88+XqzwmM5QM0/k2D+heXGGy/76gT5ajl7xYLKGiPA/KTyVhQ==", + "dev": true, + "requires": { + "@babel/code-frame": "7.0.0-beta.40", + "@babel/generator": "7.0.0-beta.40", + "@babel/helper-function-name": "7.0.0-beta.40", + "@babel/types": "7.0.0-beta.40", + "babylon": "7.0.0-beta.40", + "debug": "3.1.0", + "globals": "11.3.0", + "invariant": "2.2.2", + "lodash": "4.17.4" + }, + "dependencies": { + "babylon": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.40.tgz", + "integrity": "sha512-AVxF2EcxvGD5hhOuLTOLAXBb0VhwWpEX0HyHdAI2zU+AAP4qEwtQj8voz1JR3uclGai0rfcE+dCTHnNMOnimFg==", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "globals": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.3.0.tgz", + "integrity": "sha512-kkpcKNlmQan9Z5ZmgqKH/SMbSmjxQ7QjyNqfXVc8VJcoBV2UEg+sxQD15GQofGRh2hfpwUb70VC31DR7Rq5Hdw==", + "dev": true + } + } + }, + "@babel/types": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.0.0-beta.40.tgz", + "integrity": "sha512-uXCGCzTgMZxcSUzutCPtZmXbVC+cvENgS2e0tRuhn+Y1hZnMb8IHP0Trq7Q2MB/eFmG5pKrAeTIUfQIe5kA4Tg==", + "dev": true, + "requires": { + "esutils": "2.0.2", + "lodash": "4.17.4", + "to-fast-properties": "2.0.0" + }, + "dependencies": { + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + } + } + }, "@gulp-sourcemaps/identity-map": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@gulp-sourcemaps/identity-map/-/identity-map-1.0.1.tgz", @@ -30,6 +207,32 @@ "through2": "2.0.3" } }, + "@stimulus/core": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stimulus/core/-/core-1.0.1.tgz", + "integrity": "sha512-tQGBJyhkr+/6JZLb7WqrIgZiY46Aa0FbXH9nzNZjSMDut11LAfNPDqc7U5N9mvPoG7kCE2YJa/YQdGGlB6LgFg==", + "requires": { + "@stimulus/mutation-observers": "1.0.0" + } + }, + "@stimulus/multimap": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@stimulus/multimap/-/multimap-0.9.0.tgz", + "integrity": "sha512-cH38w+peiR6dMPN0bRJttNYatOs2aSussM4A8T27VNX9oVn5ZMVfPi7POnmDtPXzd8x3F6jpWoP8HkbzkqaPFw==" + }, + "@stimulus/mutation-observers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@stimulus/mutation-observers/-/mutation-observers-1.0.0.tgz", + "integrity": "sha512-lxXzttbMKjAML4+7JfxbETCwf9WFaIZwjTO9mbAIUq2Lykpajkc43DfdEsn6tVv5ayCU+3ODZRRllMkmLiENXg==", + "requires": { + "@stimulus/multimap": "0.9.0" + } + }, + "@stimulus/webpack-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@stimulus/webpack-helpers/-/webpack-helpers-1.0.0.tgz", + "integrity": "sha512-p525nE67Nj9Q7lzo6XMXjFGWHyCwPyEevypKJoMmtNp8CfTGEBJe+zyqhDfuqtPg1RvRSZPgrWJgDXAC844pQQ==" + }, "abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -511,6 +714,28 @@ "source-map": "0.5.7" } }, + "babel-eslint": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-8.2.2.tgz", + "integrity": "sha512-Qt2lz2egBxNYWqN9JIO2z4NOOf8i4b5JS6CFoYrOZZTDssueiV1jH/jsefyg+86SeNY3rB361/mi3kE1WK2WYQ==", + "dev": true, + "requires": { + "@babel/code-frame": "7.0.0-beta.40", + "@babel/traverse": "7.0.0-beta.40", + "@babel/types": "7.0.0-beta.40", + "babylon": "7.0.0-beta.40", + "eslint-scope": "3.7.1", + "eslint-visitor-keys": "1.0.0" + }, + "dependencies": { + "babylon": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.40.tgz", + "integrity": "sha512-AVxF2EcxvGD5hhOuLTOLAXBb0VhwWpEX0HyHdAI2zU+AAP4qEwtQj8voz1JR3uclGai0rfcE+dCTHnNMOnimFg==", + "dev": true + } + } + }, "babel-generator": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.0.tgz", @@ -682,6 +907,11 @@ "resolved": "https://registry.npmjs.org/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz", "integrity": "sha1-ytnK0RkbWtY0vzCuCHI5HgZHvpU=" }, + "babel-plugin-syntax-class-properties": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-class-properties/-/babel-plugin-syntax-class-properties-6.13.0.tgz", + "integrity": "sha1-1+sjt5oxf4VDlixQW4J8fWysJ94=" + }, "babel-plugin-syntax-exponentiation-operator": { "version": "6.13.0", "resolved": "https://registry.npmjs.org/babel-plugin-syntax-exponentiation-operator/-/babel-plugin-syntax-exponentiation-operator-6.13.0.tgz", @@ -702,6 +932,17 @@ "babel-runtime": "6.26.0" } }, + "babel-plugin-transform-class-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-class-properties/-/babel-plugin-transform-class-properties-6.24.1.tgz", + "integrity": "sha1-anl2PqYdM9NvN7YRqp3vgagbRqw=", + "requires": { + "babel-helper-function-name": "6.24.1", + "babel-plugin-syntax-class-properties": "6.13.0", + "babel-runtime": "6.26.0", + "babel-template": "6.26.0" + } + }, "babel-plugin-transform-es2015-arrow-functions": { "version": "6.22.0", "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz", @@ -3593,6 +3834,12 @@ "estraverse": "4.2.0" } }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, "espree": { "version": "3.5.2", "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.2.tgz", @@ -10538,6 +10785,15 @@ } } }, + "stimulus": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/stimulus/-/stimulus-1.0.1.tgz", + "integrity": "sha512-3cxlrUkI5KLUno41W4IFbkBK6uubt2D29x5CS+KPPTag693ZlBnD7d/2UgJEOg1mNBgTgukeiTyHh9UC+nRkSg==", + "requires": { + "@stimulus/core": "1.0.1", + "@stimulus/webpack-helpers": "1.0.0" + } + }, "stream-array": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/stream-array/-/stream-array-1.1.2.tgz", diff --git a/package.json b/package.json index 195a4829ae48..c871bef8c9f6 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "dependencies": { "babel-core": "6.26.0", "babel-loader": "7.1.2", + "babel-plugin-transform-class-properties": "6.24.1", "babel-polyfill": "6.26.0", "babel-preset-env": "1.6.1", "babel-register": "6.26.0", @@ -31,6 +32,7 @@ "gulp-watch": "4.3.11", "imports-loader": "0.7.1", "jquery": "3.2.1", + "stimulus": "1.0.1", "uglify-js": "3.2.1", "vinyl-named": "1.1.0", "webpack": "3.10.0", @@ -40,15 +42,18 @@ "zopflipng-bin": "4.0.0" }, "devDependencies": { + "babel-eslint": "8.2.2", "eslint": "4.12.1", "sass-lint": "1.12.1" }, "eslintConfig": { "env": { "browser": true, - "es6": true + "es6": true, + "amd": true }, "extends": "eslint:recommended", + "parser": "babel-eslint", "parserOptions": { "sourceType": "module" }, diff --git a/tests/unit/admin/views/test_projects.py b/tests/unit/admin/views/test_projects.py index 01f9d2b005cd..9f5895b171ca 100644 --- a/tests/unit/admin/views/test_projects.py +++ b/tests/unit/admin/views/test_projects.py @@ -434,7 +434,7 @@ def test_no_confirm(self): def test_wrong_confirm(self): project = pretend.stub(normalized_name='foo') request = pretend.stub( - POST={"confirm": "bar"}, + POST={"confirm_project_name": "bar"}, session=pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None), ), @@ -461,7 +461,7 @@ def test_deletes_project(self, db_request): db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None), ) - db_request.POST["confirm"] = project.normalized_name + db_request.POST["confirm_project_name"] = project.normalized_name db_request.user = UserFactory.create() db_request.remote_addr = "192.168.1.1" diff --git a/tests/unit/manage/test_views.py b/tests/unit/manage/test_views.py index 8a4b6e0242cc..1fed8166a861 100644 --- a/tests/unit/manage/test_views.py +++ b/tests/unit/manage/test_views.py @@ -773,7 +773,7 @@ def test_delete_project_no_confirm(self): def test_delete_project_wrong_confirm(self): project = pretend.stub(normalized_name='foo') request = pretend.stub( - POST={"confirm": "bar"}, + POST={"confirm_project_name": "bar"}, session=pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None), ), @@ -801,7 +801,7 @@ def test_delete_project(self, db_request): db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None), ) - db_request.POST["confirm"] = project.normalized_name + db_request.POST["confirm_project_name"] = project.normalized_name db_request.user = UserFactory.create() db_request.remote_addr = "192.168.1.1" diff --git a/tests/unit/utils/test_project.py b/tests/unit/utils/test_project.py index 021273ab9979..ba36d0524c2f 100644 --- a/tests/unit/utils/test_project.py +++ b/tests/unit/utils/test_project.py @@ -29,7 +29,7 @@ def test_confirm(): project = stub(normalized_name='foobar') request = stub( - POST={'confirm': 'foobar'}, + POST={'confirm_project_name': 'foobar'}, route_path=call_recorder(lambda *a, **kw: stub()), session=stub(flash=call_recorder(lambda *a, **kw: stub())), ) @@ -43,7 +43,7 @@ def test_confirm(): def test_confirm_no_input(): project = stub(normalized_name='foobar') request = stub( - POST={'confirm': ''}, + POST={'confirm_project_name': ''}, route_path=call_recorder(lambda *a, **kw: '/the-redirect'), session=stub(flash=call_recorder(lambda *a, **kw: stub())), ) @@ -63,7 +63,7 @@ def test_confirm_no_input(): def test_confirm_incorrect_input(): project = stub(normalized_name='foobar') request = stub( - POST={'confirm': 'bizbaz'}, + POST={'confirm_project_name': 'bizbaz'}, route_path=call_recorder(lambda *a, **kw: '/the-redirect'), session=stub(flash=call_recorder(lambda *a, **kw: stub())), ) diff --git a/warehouse/admin/templates/admin/projects/delete.html b/warehouse/admin/templates/admin/projects/delete.html index e8e635e7e42a..17ade1e46d9e 100644 --- a/warehouse/admin/templates/admin/projects/delete.html +++ b/warehouse/admin/templates/admin/projects/delete.html @@ -32,10 +32,10 @@ <h3 class="box-title">Delete Project</h3> </p> <div class="form-group col-sm-12"> - <label for="confirm"> + <label for="confirm_project_name"> Are you sure you want to delete <strong>{{ project_name }}</strong>? </label> - <input name="confirm" class="form-control" type="text" placeholder="Enter project name to confirm" autocomplete="off" autocorrect="off" autocapitalize="off"> + <input name="confirm_project_name" class="form-control" type="text" placeholder="Enter project name to confirm" autocomplete="off" autocorrect="off" autocapitalize="off"> </div> </div> diff --git a/warehouse/static/js/warehouse/controllers/confirm_controller.js b/warehouse/static/js/warehouse/controllers/confirm_controller.js new file mode 100644 index 000000000000..4177c8b432ff --- /dev/null +++ b/warehouse/static/js/warehouse/controllers/confirm_controller.js @@ -0,0 +1,17 @@ +import { Controller } from "stimulus"; + +export default class extends Controller { + static targets = [ "input", "button" ] + + connect() { + this.buttonTarget.disabled = true; + } + + check() { + if (this.inputTarget.value == this.buttonTarget.dataset.expected) { + this.buttonTarget.disabled = false; + } else { + this.buttonTarget.disabled = true; + } + } +} diff --git a/warehouse/static/js/warehouse/index.js b/warehouse/static/js/warehouse/index.js index 2a44301ce0fc..2a005db96ac9 100644 --- a/warehouse/static/js/warehouse/index.js +++ b/warehouse/static/js/warehouse/index.js @@ -16,6 +16,10 @@ // ensure we have an ES6 like environment. import "babel-polyfill"; +// Import stimulus +import { Application } from "stimulus"; +import { definitionsFromContext } from "stimulus/webpack-helpers"; + // We'll use docReady as a modern replacement for $(document).ready() which // does not require all of jQuery to use. This will let us use it without // having to load all of jQuery, which will make things faster. @@ -164,3 +168,7 @@ docReady(() => { } } }); + +const application = Application.start(); +const context = require.context("./controllers", true, /\.js$/); +application.load(definitionsFromContext(context)); diff --git a/warehouse/static/sass/blocks/_button.scss b/warehouse/static/sass/blocks/_button.scss index 9424d0fb1282..020f2fa6cdc7 100644 --- a/warehouse/static/sass/blocks/_button.scss +++ b/warehouse/static/sass/blocks/_button.scss @@ -51,7 +51,7 @@ border-color: $brand-color; color: darken($brand-color, 10); text-decoration: none; - z-index: index($z-index-scale, "active-button"); + z-index: index($z-index-scale, "active-button"); // Needed for button groups outline: none; } @@ -65,7 +65,7 @@ border-color: $brand-color; background-color: $brand-color; color: $white; - z-index: index($z-index-scale, "primary-button"); + z-index: index($z-index-scale, "primary-button"); // Needed for button groups &:focus, &:hover, diff --git a/warehouse/static/sass/blocks/_modal.scss b/warehouse/static/sass/blocks/_modal.scss index edb8c6c81f65..6ab881fad930 100644 --- a/warehouse/static/sass/blocks/_modal.scss +++ b/warehouse/static/sass/blocks/_modal.scss @@ -41,6 +41,7 @@ align-items: center; justify-content: center; flex-grow: 1; + text-align: left; &:target { opacity: 1; diff --git a/warehouse/static/sass/settings/_z-index.scss b/warehouse/static/sass/settings/_z-index.scss index 0f2f74703bf8..949c01a28754 100644 --- a/warehouse/static/sass/settings/_z-index.scss +++ b/warehouse/static/sass/settings/_z-index.scss @@ -25,14 +25,13 @@ // sass-lint:disable indentation -$z-index-scale: "tabs-border", +$z-index-scale: "active-button", + "primary-button", + "tabs-border", "history-line", "history-node", "callout-block", "callout-block-border", - "button", - "active-button", - "primary-button", "dropdown", "sticky-top", "dark-overlay", diff --git a/warehouse/templates/manage/account.html b/warehouse/templates/manage/account.html index d86b4b61a838..bbdb79dc899c 100644 --- a/warehouse/templates/manage/account.html +++ b/warehouse/templates/manage/account.html @@ -277,37 +277,7 @@ <h3>Cannot Delete Account</h3> {% else %} <h3>Proceed with caution!</h3> <p>You will not be able to recover your account after you delete it.</p> - <form> - <a href="#delete-account-modal" class="button button--primary"> - Delete Account - </a> - </form> + {{ confirm_button("Delete your PyPI Account", "Username", user.username) }} {% endif %} </div> - - <div id="delete-account-modal" class="modal"> - <div class="modal__content" role="dialog"> - <form method="POST" action="{{ request.current_route_path() }}" class="modal__form"> - <a href="#modal-close" title="Close" class="modal__close"> - <i class="fa fa-times" aria-hidden="true"></i> - <span class="sr-only">close</span> - </a> - <div class="modal__body"> - <h3 class="modal__title">Delete your PyPI account?</h3> - <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> - <p>Warning: This action cannot be undone!</p> - </div> - <p>Confirm your username to continue.</p> - <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}"> - <label for="confirm_username">Username</label> - <input name="confirm_username" type="text" placeholder="Confirm your username" autocomplete="off" autocorrect="off" autocapitalize="off"> - </div> - <div class="modal__footer"> - <a href="#modal-close" class="button modal__action">Cancel</a> - <button class="button button--primary modal__action" type="submit">Delete Account</button> - </div> - </form> - </div> - </div> - {% endblock %} diff --git a/warehouse/templates/manage/manage_base.html b/warehouse/templates/manage/manage_base.html index 02b583233998..1cbf1f0783d4 100644 --- a/warehouse/templates/manage/manage_base.html +++ b/warehouse/templates/manage/manage_base.html @@ -54,3 +54,54 @@ <h3 class="sidebar-section__title">Your Account</h3> </div> </div> {% endblock %} + +{% macro modal_slug(title, index) %} +{% endmacro %} + +{% macro confirm_modal(title, confirm_name, confirm_string, slug, index=None, extra_fields=None, action=None) %} + <div id="{{ slug }}" class="modal" data-controller="confirm"> + <div class="modal__content" role="dialog"> + <form method="POST" class="modal__form" action="{{ action or request.current_route_path() }}"> + <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}"> + {{ extra_fields if extra_fields else '' }} + <a href="#modal-close" title="Close" class="modal__close"> + <i class="fa fa-times" aria-hidden="true"></i> + <span class="sr-only">close</span> + </a> + <div class="modal__body"> + <h3 class="modal__title">{{ title }} {{ confirm_string }}?</h3> + <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> + <p>Warning: This action cannot be undone!</p> + </div> + <p>Confirm the {{ confirm_name|lower }} to continue.</p> + {% set name = "confirm_" + confirm_name.lower().replace(' ', '_') %} + <label for="{{ name }}">{{ confirm_name }}</label> + <input name="{{ name }}" data-action="input->confirm#check" data-target="confirm.input" type="text" placeholder="{{ confirm_string }}" autocomplete="off" autocorrect="off" autocapitalize="off"> + </div> + <div class="modal__footer"> + <a href="#modal-close" class="button modal__action">Cancel</a> + <button class="button button--primary modal__action" data-target="confirm.button" data-expected="{{ confirm_string }}" type="submit"> + {{ title }} + </button> + </div> + </form> + </div> + </div> +{% endmacro %} + +{% macro confirm_button(title, confirm_name, confirm_string, index=None, extra_fields=None, action=None) %} + {% set slug = title.lower().replace(' ', '-') + '-modal' + ('-{}'.format(index) if index else '') %} + <a href="#{{ slug }}" class="button button--primary"> + {{ title }} + </a> + {{ confirm_modal(title, confirm_name, confirm_string, slug, index=None, extra_fields=extra_fields, action=action) }} +{% endmacro %} + +{% macro confirm_dropdown(title, confirm_name, confirm_string, index=None, extra_fields=None, action=None) %} + {% set slug = title.lower().replace(' ', '-') + '-modal' + ('-{}'.format(index) if index else '') %} + <a href="#{{ slug }}" class="dropdown__link"> + <i class="fa fa-trash" aria-hidden="true"></i> + Delete + </a> + {{ confirm_modal(title, confirm_name, confirm_string, slug, index=index, extra_fields=extra_fields, action=action) }} +{% endmacro %} diff --git a/warehouse/templates/manage/manage_project_base.html b/warehouse/templates/manage/manage_project_base.html index 280920205079..1247618b320b 100644 --- a/warehouse/templates/manage/manage_project_base.html +++ b/warehouse/templates/manage/manage_project_base.html @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -#} -{% extends "base.html" %} +{% extends "manage_base.html" %} {% set user = request.user %} {% set projects = user.projects %} diff --git a/warehouse/templates/manage/release.html b/warehouse/templates/manage/release.html index 0be8f077d183..777681d72f33 100644 --- a/warehouse/templates/manage/release.html +++ b/warehouse/templates/manage/release.html @@ -74,10 +74,10 @@ <h2 class="heading-wsubtitle__heading">Release Version {{ release.version }}</h2 <i class="fa fa-hashtag" aria-hidden="true"></i> View Hashes </a> - <a href="#delete-file-modal-{{ loop.index }}" class="dropdown__link"> - <i class="fa fa-trash" aria-hidden="true"></i> - Delete - </a> + {% set extra_fields %} + <input name="file_id" type="hidden" value="{{ file.id }}"> + {% endset %} + {{ confirm_dropdown("Delete File", "Filename", file.filename, index=loop.index, extra_fields=extra_fields) }} </div> </div> </td> @@ -112,63 +112,11 @@ <h3>Delete Release</h3> Deleting will irreversibly delete this release. {% endif %} </p> - <a href="#delete-release-modal" class="button button--primary">Delete</a> - </div> - - <div id="delete-release-modal" class="modal"> - <div class="modal__content" role="dialog"> - <form method="POST" class="modal__form" action="{{ request.current_route_path() }}"> - <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}"> - <a href="#modal-close" title="Close" class="modal__close"> - <i class="fa fa-times" aria-hidden="true"></i> - <span class="sr-only">close</span> - </a> - <div class="modal__body"> - <h3 class="modal__title">Delete Release {{ release.version }}?</h3> - <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> - <p>Warning: This action cannot be undone!</p> - </div> - <p>Confirm the release version to continue.</p> - <label for="confirm_version">Release version</label> - <input name="confirm_version" type="text" placeholder="Confirm version" autocomplete="off" autocorrect="off" autocapitalize="off"> - </div> - <div class="modal__footer"> - <a href="#modal-close" class="button modal__action">Cancel</a> - <button class="button button--primary modal__action" type="submit">Delete Release</button> - </div> - </form> - </div> + {{ confirm_button("Delete Release", "Version", release.version) }} </div> {% if files %} {% for file in files %} - <div id="delete-file-modal-{{ loop.index }}" class="modal"> - {% set project_name = project.normalized_name %} - <div class="modal__content" role="dialog"> - <form method="POST" class="modal__form" action="{{ request.current_route_path() }}"> - <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}"> - <input name="file_id" type="hidden" value="{{ file.id }}"> - <a href="#modal-close" title="Close" class="modal__close"> - <i class="fa fa-times" aria-hidden="true"></i> - <span class="sr-only">close</span> - </a> - <div class="modal__body"> - <h3 class="modal__title">Delete {{ file.filename }}?</h3> - <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> - <p>Warning: This action cannot be undone!</p> - </div> - <p>Confirm the file name to continue.</p> - <label for="confirm_filename">File name</label> - <input name="confirm_filename" type="text" placeholder="Confirm file name" autocomplete="off" autocorrect="off" autocapitalize="off"> - </div> - <div class="modal__footer"> - <a href="#modal-close" class="button modal__action">Cancel</a> - <button class="button button--primary modal__action" type="submit">Delete File</button> - </div> - </form> - </div> - </div> - <div id="copy-hash-modal-{{ loop.index }}" class="modal modal--wide"> <div class="modal__content" role="dialog"> <a href="#modal-close" title="Close" class="modal__close"> diff --git a/warehouse/templates/manage/releases.html b/warehouse/templates/manage/releases.html index 5284746b089d..05036a6151ac 100644 --- a/warehouse/templates/manage/releases.html +++ b/warehouse/templates/manage/releases.html @@ -61,12 +61,8 @@ <h2>Releases ({{ project.releases|length }})</h2> <i class="fa fa-eye" aria-hidden="true"></i> View </a> - {# TODO: https://github.com/pypa/warehouse/issues/2808 - <a href="#delete-release-modal-{{ loop.index }}" class="dropdown__link"> - <i class="fa fa-trash" aria-hidden="true"></i> - Delete - </a> - #} + {% set action = request.route_path('manage.project.release', project_name=project.name, version=release.version) %} + {{ confirm_dropdown("Delete Release", "Version", release.version, index=loop.index, action=action) }} </div> </div> </td> @@ -85,38 +81,4 @@ <h3>No Releases Found</h3> {% endif %} <p>Learn how to create a new release on the <a href="https://packaging.python.org/tutorials/distributing-packages/">Python Packaging User Guide</a></p> </div> - - {# TODO: https://github.com/pypa/warehouse/issues/2808 - {% for release in project.releases %} - <div id="delete-release-modal-{{ loop.index }}" class="modal"> - <div class="modal__content" role="dialog"> - <a href="#modal-close" title="Close" class="modal__close"> - <i class="fa fa-times" aria-hidden="true"></i> - <span class="sr-only">close</span> - </a> - <div class="modal__body"> - <h3 class="modal__title">Delete {{ project.name }} - release {{ release.version }}?</h3> - <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> - <p>Warning: This action cannot be undone!</p> - </div> - <p>Enter your password to continue.</p> - <form class="modal__form"> - <div class="split-layout"> - <label for="password">Password</label> - <label for="show-password" class="show-password"> - <input id="show-password" type="checkbox">&nbsp;Show password - </label> - </div> - <input type="password" id="password" placeholder="Your password"> - </form> - </div> - <div class="modal__footer"> - <a href="#modal-close" class="button modal__action">Cancel</a> - <button class="button button--primary modal__action">Delete Release</button> - </div> - </div> - <p>Enter your password to continue.</p> - </div> - {% endfor %} - #} {% endblock %} diff --git a/warehouse/templates/manage/settings.html b/warehouse/templates/manage/settings.html index d20e19790253..0cee4a1c2ccc 100644 --- a/warehouse/templates/manage/settings.html +++ b/warehouse/templates/manage/settings.html @@ -37,32 +37,7 @@ <h3>Delete Project</h3> Deleting will irreversibly delete this project. {% endif %} </p> - <a href="#delete-project-modal" class="button button--primary">Delete</a> - </div> - - <div id="delete-project-modal" class="modal"> - {% set project_name = project.normalized_name %} - <div class="modal__content" role="dialog"> - <form method="POST" action="{{ request.route_path('manage.project.delete_project', project_name=project_name) }}" class="modal__form"> - <a href="#modal-close" title="Close" class="modal__close"> - <i class="fa fa-times" aria-hidden="true"></i> - <span class="sr-only">close</span> - </a> - <div class="modal__body"> - <h3 class="modal__title">Delete {{ project.name }}?</h3> - <div class="callout-block callout-block--danger callout-block--bottom-margin no-top-margin"> - <p>Warning: This action cannot be undone!</p> - </div> - <p>Confirm the project name to continue.</p> - <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}"> - <label for="project-name">Project Name</label> - <input name="confirm" type="text" placeholder="Confirm project name" autocomplete="off" autocorrect="off" autocapitalize="off"> - </div> - <div class="modal__footer"> - <a href="#modal-close" class="button modal__action">Cancel</a> - <button class="button button--primary modal__action" type="submit">Delete Project</button> - </div> - </form> - </div> + {% set action = request.route_path('manage.project.delete_project', project_name=project.normalized_name) %} + {{ confirm_button("Delete project", "Project name", project.normalized_name, action=action) }} </div> {% endblock %} diff --git a/warehouse/utils/project.py b/warehouse/utils/project.py index 5ae484f0d19d..2b1b59e61946 100644 --- a/warehouse/utils/project.py +++ b/warehouse/utils/project.py @@ -19,7 +19,7 @@ def confirm_project(project, request, fail_route): - confirm = request.POST.get("confirm") + confirm = request.POST.get("confirm_project_name") project_name = project.normalized_name if not confirm: request.session.flash(
netket__netket-897
[input validation] nk.graph.Chain([L]) does not fial nk.graph.Chain([L]) should fail, but does not, and leads to failure later that it took me a while to realise... We should validate the input to be an integer. ```python >>> graph = nk.graph.Chain([L]) >>> sgb = graph.space_group_builder() >>> sgb.little_group([0]) ```
[ { "content": "# Copyright 2021 The NetKet Authors - All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n...
[ { "content": "# Copyright 2021 The NetKet Authors - All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n...
diff --git a/netket/graph/common_lattices.py b/netket/graph/common_lattices.py index 831e9037ab..a3c74eb76b 100644 --- a/netket/graph/common_lattices.py +++ b/netket/graph/common_lattices.py @@ -140,6 +140,8 @@ def Hypercube(length: int, n_dim: int = 1, *, pbc: bool = True) -> Lattice: >>> print(g.n_nodes) 1000 """ + if not isinstance(length, int) or length <= 0: + raise TypeError("Argument `length` must be a positive integer") length_vector = [length] * n_dim return Grid(length_vector, pbc=pbc) diff --git a/test/graph/test_graph.py b/test/graph/test_graph.py index 878e94a62e..f9d99d91de 100644 --- a/test/graph/test_graph.py +++ b/test/graph/test_graph.py @@ -305,6 +305,18 @@ def test_graph_wrong(): with pytest.raises(ValueError): nk.graph.Graph([1, 2, 3], [1, 2, 3]) + with pytest.raises(TypeError): + nk.graph.Hypercube([5]) + + with pytest.raises(TypeError): + nk.graph.Cube([5]) + + with pytest.raises(TypeError): + nk.graph.Square([5]) + + with pytest.raises(TypeError): + nk.graph.Chain([5]) + def test_edges_are_correct(): def check_edges(length, n_dim, pbc):
conda__conda-3538
Invalid JSON output When installing `Jupyter` I sometimes see the following error: ``` post-link :: /etc/machine-id not found .. bus post-link :: .. using /proc/sys/kernel/random/boot_id ``` When installing with the `--json` flag the error output causes the json to be invalid. Example: ``` root@head:~# conda create -n test_env2 python jupyter -y --json -q dbus post-link :: /etc/machine-id not found .. dbus post-link :: .. using /proc/sys/kernel/random/boot_id { "actions": { "LINK": [ "expat-2.1.0-0 1", ... ], "PREFIX": "/opt/a/b/c/muunitnoc/anaconda/envs/test_env2", "SYMLINK_CONDA": [ "/opt/a/b/c/muunitnoc/anaconda" ], "op_order": [ "RM_FETCHED", "FETCH", "RM_EXTRACTED", "EXTRACT", "UNLINK", "LINK", "SYMLINK_CONDA" ] }, "success": true } ``` In my opinion this is a fairly critical -- I need to depend on valid JSON output cc @kalefranz @koverholt @mingwandroid Invalid JSON output When installing `Jupyter` I sometimes see the following error: ``` post-link :: /etc/machine-id not found .. bus post-link :: .. using /proc/sys/kernel/random/boot_id ``` When installing with the `--json` flag the error output causes the json to be invalid. Example: ``` root@head:~# conda create -n test_env2 python jupyter -y --json -q dbus post-link :: /etc/machine-id not found .. dbus post-link :: .. using /proc/sys/kernel/random/boot_id { "actions": { "LINK": [ "expat-2.1.0-0 1", ... ], "PREFIX": "/opt/a/b/c/muunitnoc/anaconda/envs/test_env2", "SYMLINK_CONDA": [ "/opt/a/b/c/muunitnoc/anaconda" ], "op_order": [ "RM_FETCHED", "FETCH", "RM_EXTRACTED", "EXTRACT", "UNLINK", "LINK", "SYMLINK_CONDA" ] }, "success": true } ``` In my opinion this is a fairly critical -- I need to depend on valid JSON output cc @kalefranz @koverholt @mingwandroid
[ { "content": "# (c) 2012-2014 Continuum Analytics, Inc. / http://continuum.io\n# All Rights Reserved\n#\n# conda is distributed under the terms of the BSD 3-clause license.\n# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.\n\"\"\" This module contains:\n * all low-level code for extracting...
[ { "content": "# (c) 2012-2014 Continuum Analytics, Inc. / http://continuum.io\n# All Rights Reserved\n#\n# conda is distributed under the terms of the BSD 3-clause license.\n# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.\n\"\"\" This module contains:\n * all low-level code for extracting...
diff --git a/conda/install.py b/conda/install.py index 128194407c5..f73050c2e32 100644 --- a/conda/install.py +++ b/conda/install.py @@ -1046,7 +1046,8 @@ def messages(prefix): path = join(prefix, '.messages.txt') try: with open(path) as fi: - sys.stdout.write(fi.read()) + fh = sys.stderr if context.json else sys.stdout + fh.write(fi.read()) except IOError: pass finally:
frappe__hrms-1526
Organizational Chart: Total connections includes employees left ### Information about bug <img width="329" alt="Screenshot 2024-03-08 at 11 20 37 AM" src="https://github.com/frappe/hrms/assets/20027965/b88248f8-502e-41fa-ba1a-87c0cd43165a"> The current system displays a total count of connections for each employee, including those who are no longer with the company. However, when viewing the connections, only active employees are shown. **Expected Output:** The count now reflects only active employees, ensuring consistency between the number displayed and the individuals visible upon selecting any employee. ### Module HR ### Version ERPNext: v14.x.x-develop () (develop) Frappe Framework: v15.x.x-develop () (develop) Frappe HR: v16.0.0-dev (develop) ### Installation method manual install ### Relevant log output / Stack trace / Full Error Message. _No response_ ### Code of Conduct - [x] I agree to follow this project's Code of Conduct
[ { "content": "import frappe\nfrom frappe.query_builder.functions import Count\n\n\n@frappe.whitelist()\ndef get_children(parent=None, company=None, exclude_node=None):\n\tfilters = [[\"status\", \"=\", \"Active\"]]\n\tif company and company != \"All Companies\":\n\t\tfilters.append([\"company\", \"=\", company]...
[ { "content": "import frappe\nfrom frappe.query_builder.functions import Count\n\n\n@frappe.whitelist()\ndef get_children(parent=None, company=None, exclude_node=None):\n\tfilters = [[\"status\", \"=\", \"Active\"]]\n\tif company and company != \"All Companies\":\n\t\tfilters.append([\"company\", \"=\", company]...
diff --git a/hrms/hr/page/organizational_chart/organizational_chart.py b/hrms/hr/page/organizational_chart/organizational_chart.py index b8bfce5dc4..8be4802104 100644 --- a/hrms/hr/page/organizational_chart/organizational_chart.py +++ b/hrms/hr/page/organizational_chart/organizational_chart.py @@ -43,7 +43,7 @@ def get_connections(employee: str, lft: int, rgt: int) -> int: query = ( frappe.qb.from_(Employee) .select(Count(Employee.name)) - .where((Employee.lft > lft) & (Employee.rgt < rgt)) + .where((Employee.lft > lft) & (Employee.rgt < rgt) & (Employee.status == "Active")) ).run() return query[0][0]