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 ⌀ |
|---|---|---|---|---|
neptune-ai__neptune-client-899 | BUG: Inconsistency in `fetch_run_table` tag selector
Hi,
according to `fetch_run_table`'s documentation:
> Only experiments that have all specified tags will match this criterion.
Thus, the query aggregator for tags should be `AND`.
https://github.com/neptune-ai/neptune-client/blob/4b164bc470278edd160b7b9b5059a32c4822b376/neptune/new/metadata_containers/project.py#L235
| [
{
"content": "#\n# Copyright (c) 2020, Neptune Labs Sp. z o.o.\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": "#\n# Copyright (c) 2020, Neptune Labs Sp. z o.o.\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/CHANGELOG.md b/CHANGELOG.md
index 3c596404d..3dacc0b04 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Fixes
- Fix computing of a multipart upload chunk size ([#897](https://github.com/neptune-ai/neptune-client/pull/897))
+- Matching all listed tags instead of any when calling `fetch_runs_table` ([#899](https://github.com/neptune-ai/neptune-client/pull/899))
## neptune-client 0.16.2
diff --git a/e2e_tests/standard/test_base.py b/e2e_tests/standard/test_base.py
index 7aecf0095..5e1cda66b 100644
--- a/e2e_tests/standard/test_base.py
+++ b/e2e_tests/standard/test_base.py
@@ -177,30 +177,30 @@ def test_add_and_remove_tags(self, container: MetadataContainer):
class TestFetchTable(BaseE2ETest):
def test_fetch_runs_table(self, environment):
- tag = str(uuid.uuid4())
+ tag1, tag2 = str(uuid.uuid4()), str(uuid.uuid4())
with neptune.init_run(project=environment.project) as run:
- run["sys/tags"].add(tag)
+ run["sys/tags"].add(tag1)
+ run["sys/tags"].add(tag2)
run["value"] = 12
run.sync()
with neptune.init_run(project=environment.project) as run:
- run["sys/tags"].add(tag)
+ run["sys/tags"].add(tag2)
run["another/value"] = "testing"
run.sync()
- # wait for the elasticsearch cache to fill
+ # wait for the cache to fill
time.sleep(5)
project = neptune.get_project(name=environment.project)
runs_table = sorted(
- project.fetch_runs_table(tag=tag).to_rows(),
+ project.fetch_runs_table(tag=[tag1, tag2]).to_rows(),
key=lambda r: r.get_attribute_value("sys/id"),
)
- assert len(runs_table) == 2
+ assert len(runs_table) == 1
assert runs_table[0].get_attribute_value("value") == 12
- assert runs_table[1].get_attribute_value("another/value") == "testing"
@pytest.mark.parametrize("container", ["model"], indirect=True)
def test_fetch_model_versions_table(self, container: Model, environment):
diff --git a/neptune/new/metadata_containers/project.py b/neptune/new/metadata_containers/project.py
index 3607b7d36..088bb3d21 100644
--- a/neptune/new/metadata_containers/project.py
+++ b/neptune/new/metadata_containers/project.py
@@ -232,7 +232,7 @@ def fetch_runs_table(
)
for tag in tags
],
- aggregator=NQLAggregator.OR,
+ aggregator=NQLAggregator.AND,
)
)
|
svthalia__concrexit-2705 | V2 events API reports wrong participants number
### Describe the bug
On some event the amount of participants is not reported correctly on V2 version of the API.
### How to reproduce
Steps to reproduce the behaviour:
1. Go to https://thalia.nu/api/v2/events/1005/
2. Go to https://thalia.nu/events/1005/
3. Observe a small difference.
The difference is not present in V1
Counting the pictures of the participants matches up with V1 and not V2
### Expected behaviour
The V2 API should properly report the number of registered members
| [
{
"content": "import uuid\n\nfrom django.conf import settings\nfrom django.core import validators\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import models, router\nfrom django.db.models import Count, Q\nfrom django.db.models.deletion import Collector\nfrom django.url... | [
{
"content": "import uuid\n\nfrom django.conf import settings\nfrom django.core import validators\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import models, router\nfrom django.db.models import Count, Q\nfrom django.db.models.deletion import Collector\nfrom django.url... | diff --git a/website/events/models/event.py b/website/events/models/event.py
index 06908f889..39e36cdbf 100644
--- a/website/events/models/event.py
+++ b/website/events/models/event.py
@@ -258,7 +258,7 @@ def has_fields(self):
participant_count = AggregateProperty(
Count(
"eventregistration",
- filter=~Q(eventregistration__date_cancelled__lt=timezone.now()),
+ filter=Q(eventregistration__date_cancelled=None),
)
)
diff --git a/website/events/tests/test_views.py b/website/events/tests/test_views.py
index aba8b7b60..860502e22 100644
--- a/website/events/tests/test_views.py
+++ b/website/events/tests/test_views.py
@@ -182,7 +182,7 @@ def setUp(self):
def test_registration_register_not_required(self):
response = self.client.post("/events/1/registration/register/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
def test_registration_register(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=1)
@@ -191,7 +191,7 @@ def test_registration_register(self):
self.event.save()
response = self.client.post("/events/1/registration/register/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
self.assertEqual(self.event.eventregistration_set.first().member, self.member)
def test_registration_register_twice(self):
@@ -203,7 +203,7 @@ def test_registration_register_twice(self):
self.assertEqual(response.status_code, 200)
response = self.client.post("/events/1/registration/register/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
def test_registration_register_closed(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=2)
@@ -212,7 +212,7 @@ def test_registration_register_closed(self):
self.event.save()
response = self.client.post("/events/1/registration/register/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 0)
+ self.assertEqual(self.event.participant_count, 0)
def test_registration_cancel(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=1)
@@ -222,7 +222,7 @@ def test_registration_cancel(self):
EventRegistration.objects.create(event=self.event, member=self.member)
response = self.client.post("/events/1/registration/cancel/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 0)
+ self.assertEqual(self.event.participant_count, 0)
def test_registration_register_no_fields(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=1)
@@ -261,7 +261,7 @@ def test_registration_register_no_fields(self):
)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
registration = self.event.eventregistration_set.first()
self.assertEqual(field1.get_value_for(registration), None)
self.assertEqual(field2.get_value_for(registration), None)
@@ -301,7 +301,7 @@ def test_registration_missing_fields(self):
self.assertEqual(response.status_code, 200)
template_names = [template.name for template in response.templates]
self.assertIn("events/registration.html", template_names)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
def test_registration_register_fields_required(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=1)
@@ -320,7 +320,7 @@ def test_registration_register_fields_required(self):
self.assertEqual(response.status_code, 200)
template_names = [template.name for template in response.templates]
self.assertIn("events/registration.html", template_names)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
def test_registration_update_form_load_not_changes_fields(self):
self.event.registration_start = timezone.now() - datetime.timedelta(hours=1)
@@ -428,7 +428,7 @@ def test_registration_update_form_post_changes_fields(self):
)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 1)
+ self.assertEqual(self.event.participant_count, 1)
registration = self.event.eventregistration_set.first()
self.assertEqual(field1.get_value_for(registration), False)
self.assertEqual(field2.get_value_for(registration), 1337)
@@ -443,7 +443,7 @@ def test_registration_cancel_after_deadline_notification(self):
EventRegistration.objects.create(event=self.event, member=self.member)
response = self.client.post("/events/1/registration/cancel/", follow=True)
self.assertEqual(response.status_code, 200)
- self.assertEqual(self.event.participants.count(), 0)
+ self.assertEqual(self.event.participant_count, 0)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].to,
|
google__mobly-311 | Exceptions in `setup_test` should leave the test in `ERROR` status
Regardless of the type of the exception, `setup_test` error should cause `ERROR` status.
This is different from a test method.
In a test method, an exception based on signals.TestFailure should cause the test to exit with `FAILED` status.
This is to be consistent with pyunit's behavior.
| [
{
"content": "# Copyright 2016 Google 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 applicab... | [
{
"content": "# Copyright 2016 Google 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 applicab... | diff --git a/mobly/base_test.py b/mobly/base_test.py
index 5233aa5c..fde8faba 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -17,6 +17,7 @@
import functools
import inspect
import logging
+import sys
from mobly import logger
from mobly import records
@@ -316,7 +317,7 @@ def exec_one_test(self, test_name, test_method, args=(), **kwargs):
Executes setup_test, the test method, and teardown_test; then creates a
records.TestResultRecord object with the execution information and adds
- the record to the test class's test results.
+ the record to the test class's test result s.
Args:
test_name: Name of the test.
@@ -330,7 +331,12 @@ def exec_one_test(self, test_name, test_method, args=(), **kwargs):
teardown_test_failed = False
try:
try:
- self._setup_test(test_name)
+ try:
+ self._setup_test(test_name)
+ except signals.TestFailure as e:
+ new_e = signals.TestError(e.details, e.extras)
+ _, _, new_e.__traceback__ = sys.exc_info()
+ raise new_e
if args or kwargs:
test_method(*args, **kwargs)
else:
diff --git a/mobly/signals.py b/mobly/signals.py
index 8899065a..85bdc303 100644
--- a/mobly/signals.py
+++ b/mobly/signals.py
@@ -46,6 +46,10 @@ def __str__(self):
return 'Details=%s, Extras=%s' % (self.details, self.extras)
+class TestError(TestSignal):
+ """Raised when a test has an unexpected error."""
+
+
class TestFailure(TestSignal):
"""Raised when a test has failed."""
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index bd7dce9b..d8604c94 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -239,11 +239,13 @@ def test_something(self):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run(test_names=["test_something"])
- actual_record = bt_cls.results.failed[0]
+ actual_record = bt_cls.results.error[0]
self.assertEqual(actual_record.test_name, self.mock_test_name)
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ # Make sure the full stacktrace of `setup_test` is preserved.
+ self.assertTrue('self.setup_test()' in actual_record.stacktrace)
self.assertIsNone(actual_record.extras)
- expected_summary = ("Error 0, Executed 1, Failed 1, Passed 0, "
+ expected_summary = ("Error 1, Executed 1, Failed 0, Passed 0, "
"Requested 1, Skipped 0")
self.assertEqual(bt_cls.results.summary_str(), expected_summary)
@@ -407,6 +409,7 @@ def test_something(self):
def test_procedure_function_gets_correct_record(self):
on_fail_mock = mock.MagicMock()
+
class MockBaseTest(base_test.BaseTestClass):
def on_fail(self, record):
on_fail_mock.record = record
@@ -418,12 +421,16 @@ def test_something(self):
bt_cls.run()
actual_record = bt_cls.results.failed[0]
self.assertEqual(actual_record.test_name, 'test_something')
- self.assertEqual(on_fail_mock.record.test_name, actual_record.test_name)
- self.assertEqual(on_fail_mock.record.begin_time, actual_record.begin_time)
+ self.assertEqual(on_fail_mock.record.test_name,
+ actual_record.test_name)
+ self.assertEqual(on_fail_mock.record.begin_time,
+ actual_record.begin_time)
self.assertEqual(on_fail_mock.record.end_time, actual_record.end_time)
- self.assertEqual(on_fail_mock.record.stacktrace, actual_record.stacktrace)
+ self.assertEqual(on_fail_mock.record.stacktrace,
+ actual_record.stacktrace)
self.assertEqual(on_fail_mock.record.extras, actual_record.extras)
- self.assertEqual(on_fail_mock.record.extra_errors, actual_record.extra_errors)
+ self.assertEqual(on_fail_mock.record.extra_errors,
+ actual_record.extra_errors)
# But they are not the same object.
self.assertIsNot(on_fail_mock.record, actual_record)
@@ -989,6 +996,23 @@ def test_func(self):
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
self.assertEqual(actual_record.extras, MOCK_EXTRA)
+ def test_skip_in_setup_test(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_test(self):
+ asserts.skip(MSG_EXPECTED_EXCEPTION, extras=MOCK_EXTRA)
+
+ def test_func(self):
+ never_call()
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_func"])
+ actual_record = bt_cls.results.skipped[0]
+ self.assertIsNotNone(actual_record.begin_time)
+ self.assertIsNotNone(actual_record.end_time)
+ self.assertEqual(actual_record.test_name, "test_func")
+ self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertEqual(actual_record.extras, MOCK_EXTRA)
+
def test_unpack_userparams_required(self):
"""Missing a required param should raise an error."""
required = ["some_param"]
|
Pyomo__pyomo-3017 | Pyomo AD fails with constant Expressions
## Summary
Pyomo AD raises an error when encountering `Expressions` with a constant value.
### Steps to reproduce the issue
```console
import pyomo.environ as pyo
from pyomo.core.expr.calculus.derivatives import Modes, differentiate
m = pyo.ConcreteModel()
m.x = pyo.Var(units=pyo.units.mol, initialize=0)
@m.Expression()
def y(blk):
return 2
@m.Expression()
def product(blk):
return blk.x * blk.y
diff_expr = differentiate(
expr=m.product,
wrt=m.x,
mode=Modes.reverse_symbolic
)
diff_expr.pprint()
```
### Error Message
```console
Exception has occurred: KeyError
"Component with id '1907001786672': 2.0"
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\common\collections\component_map.py", line 71, in __getitem__
return self._dict[id(obj)][1]
KeyError: 1907001786672
During handling of the above exception, another exception occurred:
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\common\collections\component_map.py", line 73, in __getitem__
raise KeyError("Component with id '%s': %s" % (id(obj), str(obj)))
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\core\expr\calculus\diff_with_pyomo.py", line 331, in _diff_GeneralExpression
der_dict[node.expr] += der_dict[node]
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\core\expr\calculus\diff_with_pyomo.py", line 442, in _reverse_diff_helper
_diff_GeneralExpression(e, val_dict, der_dict)
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\core\expr\calculus\diff_with_pyomo.py", line 484, in reverse_sd
return _reverse_diff_helper(expr, False)
File "C:\Users\[REDACTED]\Repos\pyomo\pyomo\core\expr\calculus\derivatives.py", line 96, in differentiate
res = reverse_sd(expr=expr)
File "C:\Users\[REDACTED]\Desktop\diff_expr.py", line 16, in <module>
diff_expr = differentiate(
KeyError: "Component with id '1907001786672': 2.0"
```
### Information on your system
Pyomo version: 6.6.2
Python version: 3.10.10 | packaged by Anaconda, Inc. | (main, Mar 21 2023, 18:39:17) [MSC v.1916 64 bit (AMD64)]
Operating system: Windows 10
How Pyomo was installed (PyPI, conda, source): From sources
Solver (if applicable): n/a
| [
{
"content": "# ___________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright (c) 2008-2022\n# National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n... | [
{
"content": "# ___________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright (c) 2008-2022\n# National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n... | diff --git a/pyomo/core/expr/calculus/diff_with_pyomo.py b/pyomo/core/expr/calculus/diff_with_pyomo.py
index 952e8ec6dd3..0e3ba3cc2b2 100644
--- a/pyomo/core/expr/calculus/diff_with_pyomo.py
+++ b/pyomo/core/expr/calculus/diff_with_pyomo.py
@@ -328,7 +328,7 @@ def _diff_GeneralExpression(node, val_dict, der_dict):
val_dict: ComponentMap
der_dict: ComponentMap
"""
- der_dict[node.expr] += der_dict[node]
+ der_dict[node.arg(0)] += der_dict[node]
def _diff_ExternalFunctionExpression(node, val_dict, der_dict):
diff --git a/pyomo/core/tests/unit/test_derivs.py b/pyomo/core/tests/unit/test_derivs.py
index 9e89f2beac9..23a5a8bc7d1 100644
--- a/pyomo/core/tests/unit/test_derivs.py
+++ b/pyomo/core/tests/unit/test_derivs.py
@@ -230,6 +230,17 @@ def e2(m, i):
symbolic = reverse_sd(m.o.expr)
self.assertAlmostEqual(derivs[m.x], pyo.value(symbolic[m.x]), tol)
+ def test_constant_named_expressions(self):
+ m = pyo.ConcreteModel()
+ m.x = pyo.Var(initialize=3)
+ m.e = pyo.Expression(expr=2)
+
+ e = m.x * m.e
+ derivs = reverse_ad(e)
+ symbolic = reverse_sd(e)
+ self.assertAlmostEqual(derivs[m.x], pyo.value(symbolic[m.x]), tol + 3)
+ self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
+
def test_multiple_named_expressions(self):
m = pyo.ConcreteModel()
m.x = pyo.Var()
|
sopel-irc__sopel-1280 | [url] meaning of `exclude` changed?
i used to have the following in my `sopel.cfg`:
``` ini
[url]
exclude =
exclusion_char = !
```
... and it worked fine up to (and including) 6.1.1. After an upgrade to 6.3.0, the bot was silent on `.title http://example.com/`, all of a sudden - the above`exclude` pattern would match everything!
after removing the above block, the proper `.title` behavior was restored. the problem is the above is the default config generated when you run `sopel -w`: so by default, now, it seems that the url plugin config is basically broken and there's no way to configure the bot to _not_ be silent (unless you input an impossible regex) by default.
[url] 'function' object has no attribute 'priority'
Sopel v. 6.5.0 is not loading the `url` module properly. I am unable to get titles using `.title http://url.here`, and reloading the module gives this error:
````
<dgw> Sopel: reload url
<Sopel> AttributeError: 'function' object has no attribute 'priority' (file
"/usr/local/lib/python2.7/dist-packages/sopel/bot.py", line 213, in unregister)
````
Perhaps that's a red herring, because on startup Sopel prints to stdout: `Error in url setup procedure: nothing to repeat (../../../../../lib/python2.7/re.py:242)`
My config includes no `exclude` rules, and `exclusion_char = ^`. This occurs both with an empty `exclude` option in the config file and with no `exclude` line at all.
| [
{
"content": "# coding=utf-8\n\"\"\"Types for creating section definitions.\n\nA section definition consists of a subclass of ``StaticSection``, on which any\nnumber of subclasses of ``BaseValidated`` (a few common ones of which are\navailable in this module) are assigned as attributes. These descriptors define... | [
{
"content": "# coding=utf-8\n\"\"\"Types for creating section definitions.\n\nA section definition consists of a subclass of ``StaticSection``, on which any\nnumber of subclasses of ``BaseValidated`` (a few common ones of which are\navailable in this module) are assigned as attributes. These descriptors define... | diff --git a/sopel/config/types.py b/sopel/config/types.py
index 55d5167886..79b396e08f 100644
--- a/sopel/config/types.py
+++ b/sopel/config/types.py
@@ -222,7 +222,7 @@ def __init__(self, name, strip=True, default=None):
self.strip = strip
def parse(self, value):
- value = value.split(',')
+ value = list(filter(None, value.split(',')))
if self.strip:
return [v.strip() for v in value]
else:
|
Nitrate__Nitrate-381 | Mark Nitrate as not zip_safe
Add `zip_safe=False` to `setup.py` because Nitrate cannot run from a zip file directly.
| [
{
"content": "# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom setuptools import setup, find_packages\n\n\nwith open('VERSION.txt', 'r') as f:\n pkg_version = f.read().strip()\n\n\ndef get_long_description():\n with open('README.rst', 'r') as f:\n return f.read()\n\n\ninstall_requires = [\n 'beauti... | [
{
"content": "# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom setuptools import setup, find_packages\n\n\nwith open('VERSION.txt', 'r') as f:\n pkg_version = f.read().strip()\n\n\ndef get_long_description():\n with open('README.rst', 'r') as f:\n return f.read()\n\n\ninstall_requires = [\n 'beauti... | diff --git a/setup.py b/setup.py
index 65376dbb..187b670d 100644
--- a/setup.py
+++ b/setup.py
@@ -90,6 +90,7 @@ def get_long_description():
extras_require=extras_require,
packages=find_packages(),
include_package_data=True,
+ zip_safe=False,
classifiers=[
'Framework :: Django',
'Framework :: Django :: 1.11',
|
urllib3__urllib3-987 | urllib3 fails to install on centos7 due to old setuptools not supporting <=, < environment markers.
Current urllib3 fails to install on centos7. This bug was most likely introduced after https://github.com/shazow/urllib3/commit/9f5454eac808a105307b2d363c99ce97e5109821.
centos7 ships a very old version of setuptools (0.9.8) which does not support `<=` as an environment marker. See https://github.com/pypa/setuptools/issues/380.
```
$ python --version
Python 2.7.5
$ rpm -qa python-setuptools
python-setuptools-0.9.8-4.el7.noarch
$ lsb_release -a
...
Description: CentOS Linux release 7.2.1511 (Core)
Release: 7.2.1511
$ virtualenv venv
...
$ venv/bin/pip install urllib3
Downloading/unpacking urllib3
Downloading urllib3-1.18.tar.gz (183kB): 183kB downloaded
Running setup.py egg_info for package urllib3
error in urllib3 setup command: Invalid environment marker: python_version <= "2.7"
Complete output from command python setup.py egg_info:
error in urllib3 setup command: Invalid environment marker: python_version <= "2.7"
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /home/rene/src/venv/build/urllib3
Storing complete log in /home/rene/.pip/pip.log
```
Installing https://github.com/shazow/urllib3/commit/f620d997134708b09560ca5797aa79a59a2ef4c0 (commit before 9f5454eac808a105307b2d363c99ce97e5109821) works fine.
```
$ venv/bin/pip install git+git://github.com/shazow/urllib3.git@f620d997134708b09560ca5797aa79a59a2ef4c0
...
Successfully installed urllib3
Cleaning up...
```
But 9f5454eac808a105307b2d363c99ce97e5109821 fails.
```
$ venv/bin/pip install git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821
Downloading/unpacking git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821
Cloning git://github.com/shazow/urllib3.git (to 9f5454eac808a105307b2d363c99ce97e5109821) to /tmp/pip-lnVDAG-build
Could not find a tag or branch '9f5454eac808a105307b2d363c99ce97e5109821', assuming commit.
Running setup.py egg_info for package from git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821
error in urllib3 setup command: Invalid environment marker: python_version < "3.3"
Complete output from command python setup.py egg_info:
error in urllib3 setup command: Invalid environment marker: python_version < "3.3"
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /tmp/pip-lnVDAG-build
Storing complete log in /home/rene/.pip/pip.log
```
urllib3 1.17 setup.py does not ship with < or <= markers so my workaround right now is to install urllib3==1.17.
| [
{
"content": "#!/usr/bin/env python\n\nfrom setuptools import setup\n\nimport os\nimport re\nimport codecs\n\nbase_path = os.path.dirname(__file__)\n\n# Get the version (borrowed from SQLAlchemy)\nwith open(os.path.join(base_path, 'urllib3', '__init__.py')) as fp:\n VERSION = re.compile(r\".*__version__ = '(... | [
{
"content": "#!/usr/bin/env python\n\nfrom setuptools import setup\n\nimport os\nimport re\nimport codecs\n\nbase_path = os.path.dirname(__file__)\n\n# Get the version (borrowed from SQLAlchemy)\nwith open(os.path.join(base_path, 'urllib3', '__init__.py')) as fp:\n VERSION = re.compile(r\".*__version__ = '(... | diff --git a/CHANGES.rst b/CHANGES.rst
index 0fd23a0456..29a579b892 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,7 +5,10 @@ dev (master)
------------
* urllib3 now respects Retry-After headers on 413, 429, and 503 responses when
- using the default retry logic.
+ using the default retry logic. (Pull #955)
+
+* Remove markers from setup.py to assist ancient setuptools versions. (Issue
+ #986)
* ... [Short description of non-trivial change.] (Issue #)
diff --git a/setup.py b/setup.py
index 196e0e5f6c..93950e5d1a 100644
--- a/setup.py
+++ b/setup.py
@@ -59,8 +59,6 @@
'cryptography>=1.3.4',
'idna>=2.0.0',
'certifi',
- ],
- 'secure:python_version <= "2.7"': [
"ipaddress",
],
'socks': [
|
bookwyrm-social__bookwyrm-3193 | Switching editions changes "shelved" date
**Describe the bug**
When switching editions of a book already on your "To Read" list, the "shelved" date is changed to today's date.
**To Reproduce**
Steps to reproduce the behavior:
1. Pick any book on your "To read" list with more than one edition
2. Pick another edition and switch to this
3. Observe that the book's shelved date is now today
**Expected behavior**
This shouldn't changed the shelved date
**Instance**
https://books.theunseen.city
---
**Desktop (please complete the following information):**
- OS: MacOS 14.1
- Browser: Firefox
- Version: 20.0 (64-bit)
| [
{
"content": "\"\"\" the good stuff! the books! \"\"\"\nfrom functools import reduce\nimport operator\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.shortcuts import get_obj... | [
{
"content": "\"\"\" the good stuff! the books! \"\"\"\nfrom functools import reduce\nimport operator\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.shortcuts import get_obj... | diff --git a/bookwyrm/views/books/editions.py b/bookwyrm/views/books/editions.py
index 54d1bd84c1..5202531f5d 100644
--- a/bookwyrm/views/books/editions.py
+++ b/bookwyrm/views/books/editions.py
@@ -93,6 +93,7 @@ def switch_edition(request):
user=shelfbook.user,
shelf=shelfbook.shelf,
book=new_edition,
+ shelved_date=shelfbook.shelved_date,
)
shelfbook.delete()
|
hpcaitech__ColossalAI-5060 | [tensor] fix some unittests
[tensor] fix some unittests
[tensor] fix some unittests
[BUG]: gemini 插件微调时,疑似不能正确加载模型权重
### 🐛 Describe the bug
# 环境
```
------------ Environment ------------
Colossal-AI version: 0.3.4
PyTorch version: 2.0.1
System CUDA version: 11.7
CUDA version required by PyTorch: 11.7
```
# BUG 细节
微调代码修改自:https://github.com/hpcaitech/ColossalAI/blob/main/examples/language/llama2/finetune.py
加载模型:https://github.com/hpcaitech/ColossalAI/blob/main/examples/language/llama2/finetune.py#L237
除了plugin的类型其余变量都保持一致,发现zero2时,loss的表现正常,而使用gemini时,更像是从一个随机初始化的weight进行优化
zero2,loss 正常从比较低的水平开始下降:

gemini,loss 从特别高的水平下降:

### Environment
_No response_
| [
{
"content": "import argparse\nimport math\nimport os\nimport resource\nfrom contextlib import nullcontext\nfrom functools import partial\nfrom typing import Optional, Tuple\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom attn import SUPPORT_XFORMERS, replace_xformers\nfrom data_u... | [
{
"content": "import argparse\nimport math\nimport os\nimport resource\nfrom contextlib import nullcontext\nfrom functools import partial\nfrom typing import Optional, Tuple\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom attn import SUPPORT_XFORMERS, replace_xformers\nfrom data_u... | diff --git a/examples/language/llama2/finetune.py b/examples/language/llama2/finetune.py
index 33aa1d33e6ba..f7708b1a38ab 100644
--- a/examples/language/llama2/finetune.py
+++ b/examples/language/llama2/finetune.py
@@ -58,6 +58,7 @@ def tokenize_batch_for_finetune(batch, tokenizer: Optional[LlamaTokenizer] = Non
def all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor:
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
+ tensor = tensor.data
tensor.div_(dist.get_world_size())
return tensor
|
enthought__chaco-884 | ImportError: cannot import name 'BaseTool' from 'chaco.api'
**Problem Description**
ImportError: cannot import name 'BaseTool' from 'chaco.api' when running chaco/examples/demo/canvas/mptools.py
**Reproduction Steps:**
python chaco/examples/demo/canvas/mptools.py
**OS, Python version:** [MacOS, python3.11, python3.8 (with EDM)]
| [
{
"content": "\"\"\"\nA collection of Chaco tools that respond to a multi-pointer interface.\n\"\"\"\nfrom numpy import asarray, dot, sqrt\n\n# Enthought library imports\nfrom traits.api import (\n Delegate,\n Dict,\n Enum,\n Instance,\n Int,\n Property,\n Tuple,\n CArray,\n)\n\n# Chaco ... | [
{
"content": "\"\"\"\nA collection of Chaco tools that respond to a multi-pointer interface.\n\"\"\"\nfrom numpy import asarray, dot, sqrt\n\n# Enthought library imports\nfrom traits.api import (\n Delegate,\n Dict,\n Enum,\n Instance,\n Int,\n Property,\n Tuple,\n CArray,\n)\n\nfrom ena... | diff --git a/examples/demo/canvas/mptools.py b/examples/demo/canvas/mptools.py
index 77e13a22a..c8f4866e5 100644
--- a/examples/demo/canvas/mptools.py
+++ b/examples/demo/canvas/mptools.py
@@ -15,8 +15,9 @@
CArray,
)
+from enable.api import BaseTool
+
# Chaco imports
-from chaco.api import BaseTool
from chaco.chaco_traits import Optional
from chaco.tools.api import PanTool, DragZoom, LegendTool, RangeSelection
|
getredash__redash-3008 | GA Data Source throws an error when no rows returned
### Issue Summary
Google Analytics Data Source throws `Error running query: 'rows'` when the query result is empty.
I have a pretty simple query with dimensions and filters, like:
```json
{
"ids": "ga:177xxxxxx",
"start_date": "2018-10-08",
"end_date": "2018-10-12",
"metrics": "ga:uniqueEvents",
"dimensions": "ga:dimension1,ga:dimension3",
"filters": "ga:dimension2==userrole;ga:eventCategory==eventcategory;ga:eventAction==enentaction;ga:dimension1!=demo"
}
```
Sometimes it returns empty result as there is no data. This results in error in redash.
### Steps to Reproduce
1. Create the Google Analytics Data Source
2. Make some query returning zero rows
3. Execute it in query editor
`Error running query: 'rows'` will be thrown. While this might be considered not a bug, I'd expect just an empty result with no errors.
### Technical details:
* Redash Version: 5.0.1
* Browser/OS: Chrome/macOS
* How did you install Redash: docker-compose
GA Data Source throws an error when no rows returned
### Issue Summary
Google Analytics Data Source throws `Error running query: 'rows'` when the query result is empty.
I have a pretty simple query with dimensions and filters, like:
```json
{
"ids": "ga:177xxxxxx",
"start_date": "2018-10-08",
"end_date": "2018-10-12",
"metrics": "ga:uniqueEvents",
"dimensions": "ga:dimension1,ga:dimension3",
"filters": "ga:dimension2==userrole;ga:eventCategory==eventcategory;ga:eventAction==enentaction;ga:dimension1!=demo"
}
```
Sometimes it returns empty result as there is no data. This results in error in redash.
### Steps to Reproduce
1. Create the Google Analytics Data Source
2. Make some query returning zero rows
3. Execute it in query editor
`Error running query: 'rows'` will be thrown. While this might be considered not a bug, I'd expect just an empty result with no errors.
### Technical details:
* Redash Version: 5.0.1
* Browser/OS: Chrome/macOS
* How did you install Redash: docker-compose
| [
{
"content": "# -*- coding: utf-8 -*-\n\nimport logging\nfrom base64 import b64decode\nfrom datetime import datetime\nfrom urlparse import parse_qs, urlparse\n\nfrom redash.query_runner import *\nfrom redash.utils import json_dumps, json_loads\n\nlogger = logging.getLogger(__name__)\n\ntry:\n from oauth2clie... | [
{
"content": "# -*- coding: utf-8 -*-\n\nimport logging\nfrom base64 import b64decode\nfrom datetime import datetime\nfrom urlparse import parse_qs, urlparse\n\nfrom redash.query_runner import *\nfrom redash.utils import json_dumps, json_loads\n\nlogger = logging.getLogger(__name__)\n\ntry:\n from oauth2clie... | diff --git a/redash/query_runner/google_analytics.py b/redash/query_runner/google_analytics.py
index e8b70eb01f..71be522015 100644
--- a/redash/query_runner/google_analytics.py
+++ b/redash/query_runner/google_analytics.py
@@ -43,7 +43,7 @@ def parse_ga_response(response):
})
rows = []
- for r in response['rows']:
+ for r in response.get('rows', []):
d = {}
for c, value in enumerate(r):
column_name = response['columnHeaders'][c]['name']
|
docker__docker-py-1167 | Feature Request: docker.from_env(version='auto')
Feature request to add auto api version support for `docker.from_env()` similar to `docker.Client(version='auto')`?
I noticed that one of the suggestions from #402 for the `version='auto'` option was now available for `docker.Client()` but doesn't work for `docker.from_env()`.
| [
{
"content": "# Copyright 2013 dotCloud 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 requir... | [
{
"content": "# Copyright 2013 dotCloud 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 requir... | diff --git a/docker/client.py b/docker/client.py
index 758675369..dc28ac46c 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -114,7 +114,8 @@ def __init__(self, base_url=None, version=None,
@classmethod
def from_env(cls, **kwargs):
- return cls(**kwargs_from_env(**kwargs))
+ version = kwargs.pop('version', None)
+ return cls(version=version, **kwargs_from_env(**kwargs))
def _retrieve_server_version(self):
try:
diff --git a/tests/unit/client_test.py b/tests/unit/client_test.py
index b21f1d6ae..6ceb8cbbc 100644
--- a/tests/unit/client_test.py
+++ b/tests/unit/client_test.py
@@ -25,6 +25,14 @@ def test_from_env(self):
client = Client.from_env()
self.assertEqual(client.base_url, "https://192.168.59.103:2376")
+ def test_from_env_with_version(self):
+ os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376',
+ DOCKER_CERT_PATH=TEST_CERT_DIR,
+ DOCKER_TLS_VERIFY='1')
+ client = Client.from_env(version='2.32')
+ self.assertEqual(client.base_url, "https://192.168.59.103:2376")
+ self.assertEqual(client._version, '2.32')
+
class DisableSocketTest(base.BaseTestCase):
class DummySocket(object):
|
mathesar-foundation__mathesar-1707 | Explorations should not auto-save
New Explorations are currently persistent, any change made immediately saves the exploration. This behaviour is not preferred since we'd like the user to be able to run and discard queries.
[Mail thread containing related discussion](https://groups.google.com/a/mathesar.org/g/mathesar-developers/c/RQJSiDQu1Tg/m/uLHj30yFAgAJ).
New behaviour proposed:
* New Exploration: Auto-save is not preferred
- User opens Data Explorer
- User joins tables, does any number of operations
- This should not get saved automatically
- It should get saved when user manually clicks Save button
* Editing existing Exploration: ~~Auto-save is preferred~~ Auto save is not preferred (Refer https://github.com/centerofci/mathesar/issues/1590#issuecomment-1238204655)
- Users edits an existing exploration in the Data Explorer
- User makes changes to it
- ~~The changes are auto-saved~~ User has to click the Save button or Ctrl+s to save the changes
- We have undo-redo to improve the user's editing experience
Implement Exploration Page functionality
This is a placeholder issue to implement a page to view a single exploration.
| [
{
"content": "from django.shortcuts import render, redirect, get_object_or_404\n\nfrom mathesar.models.base import Database, Schema, Table\nfrom mathesar.api.serializers.databases import DatabaseSerializer, TypeSerializer\nfrom mathesar.api.serializers.schemas import SchemaSerializer\nfrom mathesar.api.serializ... | [
{
"content": "from django.shortcuts import render, redirect, get_object_or_404\n\nfrom mathesar.models.base import Database, Schema, Table\nfrom mathesar.api.serializers.databases import DatabaseSerializer, TypeSerializer\nfrom mathesar.api.serializers.schemas import SchemaSerializer\nfrom mathesar.api.serializ... | diff --git a/mathesar/views.py b/mathesar/views.py
index 753441223b..8b45f7f1a9 100644
--- a/mathesar/views.py
+++ b/mathesar/views.py
@@ -42,7 +42,7 @@ def get_queries_list(request, schema):
if schema is None:
return []
query_serializer = QuerySerializer(
- UIQuery.objects.all(),
+ UIQuery.objects.filter(base_table__schema=schema),
many=True,
context={'request': request}
)
diff --git a/mathesar_ui/src/api/queries/queryList.ts b/mathesar_ui/src/api/queries.ts
similarity index 66%
rename from mathesar_ui/src/api/queries/queryList.ts
rename to mathesar_ui/src/api/queries.ts
index 9ab20ac360..e3f8834157 100644
--- a/mathesar_ui/src/api/queries/queryList.ts
+++ b/mathesar_ui/src/api/queries.ts
@@ -1,13 +1,16 @@
import type { PaginatedResponse } from '@mathesar/utils/api';
import type { Column } from '@mathesar/api/tables/columns';
import type { JpPath } from '@mathesar/api/tables/joinable_tables';
+import type { SchemaEntry } from '@mathesar/AppTypes';
+
+export type QueryColumnAlias = string;
/**
* endpoint: /api/db/v0/queries/<query_id>/
*/
export interface QueryInstanceInitialColumn {
- alias: string;
+ alias: QueryColumnAlias;
id: Column['id'];
jp_path?: JpPath;
display_name: string;
@@ -53,6 +56,10 @@ export interface QueryInstance {
readonly transformations?: QueryInstanceTransformation[];
}
+export interface QueryGetResponse extends QueryInstance {
+ readonly schema: number;
+}
+
/**
* endpoint: /api/db/v0/queries/
*/
@@ -78,3 +85,35 @@ export interface QueryResultColumn {
}
export type QueryResultColumns = QueryResultColumn[];
+
+/**
+ * endpoint: /api/db/v0/queries/<query_id>/run/
+ */
+
+export interface QueryRunRequest {
+ base_table: QueryInstance['base_table'];
+ initial_columns: QueryInstanceInitialColumn[];
+ transformations?: QueryInstanceTransformation[];
+ parameters: {
+ order_by?: {
+ field: QueryColumnAlias;
+ direction: 'asc' | 'desc';
+ }[];
+ limit: number;
+ offset: number;
+ };
+}
+
+export type QueryColumnMetaData = QueryResultColumn;
+
+export interface QueryRunResponse {
+ query: {
+ schema: SchemaEntry['id'];
+ base_table: QueryInstance['base_table'];
+ initial_columns: QueryInstanceInitialColumn[];
+ transformations?: QueryInstanceTransformation[];
+ };
+ records: QueryResultRecords;
+ output_columns: QueryColumnAlias[];
+ column_metadata: Record<string, QueryColumnMetaData>;
+}
diff --git a/mathesar_ui/src/pages/database/AddEditSchemaModalForm.svelte b/mathesar_ui/src/components/NameAndDescInputModalForm.svelte
similarity index 89%
rename from mathesar_ui/src/pages/database/AddEditSchemaModalForm.svelte
rename to mathesar_ui/src/components/NameAndDescInputModalForm.svelte
index 92fb1f441f..ee82b00482 100644
--- a/mathesar_ui/src/pages/database/AddEditSchemaModalForm.svelte
+++ b/mathesar_ui/src/components/NameAndDescInputModalForm.svelte
@@ -1,4 +1,13 @@
<script lang="ts">
+ /**
+ * This component is currently used for objects where name and description
+ * need to be entered by the user. This is used in places such as:
+ * - Adding/Editing schema
+ * - Saving Exploration
+ *
+ * A more common modal-form component can be created by utilizing FormBuilder
+ * if such a need arises in the future.
+ */
import { tick } from 'svelte';
import type { ModalController } from '@mathesar-component-library';
import {
diff --git a/mathesar_ui/src/components/QueryName.svelte b/mathesar_ui/src/components/QueryName.svelte
index 5a0636fc47..52516da34b 100644
--- a/mathesar_ui/src/components/QueryName.svelte
+++ b/mathesar_ui/src/components/QueryName.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import type { QueryInstance } from '@mathesar/api/queries/queryList';
+ import type { QueryInstance } from '@mathesar/api/queries';
import { iconExploration } from '@mathesar/icons';
import NameWithIcon from './NameWithIcon.svelte';
diff --git a/mathesar_ui/src/components/SaveStatusIndicator.svelte b/mathesar_ui/src/components/SaveStatusIndicator.svelte
index a229b2ce95..dc5326b536 100644
--- a/mathesar_ui/src/components/SaveStatusIndicator.svelte
+++ b/mathesar_ui/src/components/SaveStatusIndicator.svelte
@@ -16,7 +16,7 @@
class:error={status === 'failure'}
>
{#if !status}
- *Unsaved
+ *Has unsaved changes
{:else if status === 'success'}
All changes saved
{:else if status === 'processing'}
diff --git a/mathesar_ui/src/components/breadcrumb/EntitySelector.svelte b/mathesar_ui/src/components/breadcrumb/EntitySelector.svelte
index 9f84c51a1c..ada1e65fab 100644
--- a/mathesar_ui/src/components/breadcrumb/EntitySelector.svelte
+++ b/mathesar_ui/src/components/breadcrumb/EntitySelector.svelte
@@ -7,12 +7,12 @@
import type { TableEntry } from '@mathesar/api/tables';
import {
getTablePageUrl,
- getDataExplorerPageUrl,
+ getExplorationPageUrl,
} from '@mathesar/routes/urls';
import type { Database, SchemaEntry } from '@mathesar/AppTypes';
import { iconTable } from '@mathesar/icons';
import { queries as queriesStore } from '@mathesar/stores/queries';
- import type { QueryInstance } from '@mathesar/api/queries/queryList';
+ import type { QueryInstance } from '@mathesar/api/queries';
import BreadcrumbSelector from './BreadcrumbSelector.svelte';
import type {
BreadcrumbSelectorEntry,
@@ -46,11 +46,11 @@
return {
type: 'simple',
label: queryInstance.name,
- href: getDataExplorerPageUrl(database.name, schema.id, queryInstance.id),
+ href: getExplorationPageUrl(database.name, schema.id, queryInstance.id),
icon: iconTable,
isActive() {
// TODO we don't have a store for what the current query is, so we fallback to comparing hrefs.
- const entryhref = getDataExplorerPageUrl(
+ const entryhref = getExplorationPageUrl(
database.name,
schema.id,
queryInstance.id,
diff --git a/mathesar_ui/src/components/routing/EventfulRoute.svelte b/mathesar_ui/src/components/routing/EventfulRoute.svelte
index 58ad63b67e..dfab775b33 100644
--- a/mathesar_ui/src/components/routing/EventfulRoute.svelte
+++ b/mathesar_ui/src/components/routing/EventfulRoute.svelte
@@ -7,6 +7,6 @@
</script>
<Route {path} {firstmatch} let:meta>
- <Observer {meta} on:routeUpdated on:routeLoaded />
+ <Observer {meta} on:load on:unload />
<slot {meta} />
</Route>
diff --git a/mathesar_ui/src/components/routing/MultiPathRoute.svelte b/mathesar_ui/src/components/routing/MultiPathRoute.svelte
new file mode 100644
index 0000000000..1d56f0f1f4
--- /dev/null
+++ b/mathesar_ui/src/components/routing/MultiPathRoute.svelte
@@ -0,0 +1,47 @@
+<script lang="ts">
+ import { tick } from 'svelte';
+ import type { TinroRouteMeta } from 'tinro';
+ import EventfulRoute from './EventfulRoute.svelte';
+ import type { RoutePath } from './utils';
+
+ export let paths: RoutePath[];
+
+ let currentPath:
+ | {
+ routePath: RoutePath;
+ meta: TinroRouteMeta;
+ }
+ | undefined;
+
+ function setPath(path: RoutePath, _meta: TinroRouteMeta) {
+ currentPath = {
+ routePath: path,
+ meta: _meta,
+ };
+ }
+
+ async function clearPath(path: RoutePath) {
+ /**
+ * This is important.
+ * This function body should only execute after a tick,
+ * once the next path without paths is loaded.
+ */
+ await tick();
+ if (currentPath?.routePath === path) {
+ currentPath = undefined;
+ }
+ }
+</script>
+
+{#each paths as rp (rp.name)}
+ <EventfulRoute
+ path={rp.path}
+ on:load={(e) => setPath(rp, e.detail)}
+ on:unload={() => clearPath(rp)}
+ firstmatch
+ />
+{/each}
+
+{#if currentPath}
+ <slot meta={currentPath.meta} path={currentPath.routePath.name} />
+{/if}
diff --git a/mathesar_ui/src/components/routing/Observer.svelte b/mathesar_ui/src/components/routing/Observer.svelte
index 1a36043b04..c0c08b3541 100644
--- a/mathesar_ui/src/components/routing/Observer.svelte
+++ b/mathesar_ui/src/components/routing/Observer.svelte
@@ -1,19 +1,25 @@
<script lang="ts">
- import { onMount, createEventDispatcher } from 'svelte';
+ import { createEventDispatcher, onMount } from 'svelte';
import type { TinroRouteMeta } from 'tinro';
const dispatch = createEventDispatcher<{
- routeUpdated: TinroRouteMeta;
- routeLoaded: TinroRouteMeta;
+ load: TinroRouteMeta;
+ update: TinroRouteMeta;
+ unload: undefined;
}>();
export let meta: TinroRouteMeta;
- $: if ($meta) {
- dispatch('routeUpdated', $meta);
- }
-
onMount(() => {
- dispatch('routeLoaded', $meta);
+ const unsubsriber = $meta.subscribe((metaInfo) => {
+ if (metaInfo) {
+ dispatch('load', metaInfo);
+ }
+ });
+
+ return () => {
+ unsubsriber();
+ dispatch('unload');
+ };
});
</script>
diff --git a/mathesar_ui/src/components/routing/utils.ts b/mathesar_ui/src/components/routing/utils.ts
new file mode 100644
index 0000000000..8b3218fbd3
--- /dev/null
+++ b/mathesar_ui/src/components/routing/utils.ts
@@ -0,0 +1 @@
+export type RoutePath = { name: string; path: string };
diff --git a/mathesar_ui/src/components/sheet/Sheet.svelte b/mathesar_ui/src/components/sheet/Sheet.svelte
index 27f5542cf8..968d984ce7 100644
--- a/mathesar_ui/src/components/sheet/Sheet.svelte
+++ b/mathesar_ui/src/components/sheet/Sheet.svelte
@@ -117,6 +117,15 @@
z-index: 5;
}
+ :global([data-sheet-element='cell'][data-cell-control='true']) {
+ font-size: var(--text-size-x-small);
+ padding: 0 1.5rem;
+ color: var(--color-text-muted);
+ display: inline-flex;
+ align-items: center;
+ height: 100%;
+ }
+
:global([data-sheet-element='row']) {
transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
}
diff --git a/mathesar_ui/src/components/sheet/SheetCell.svelte b/mathesar_ui/src/components/sheet/SheetCell.svelte
index 0b4427f91e..fb70966943 100644
--- a/mathesar_ui/src/components/sheet/SheetCell.svelte
+++ b/mathesar_ui/src/components/sheet/SheetCell.svelte
@@ -11,10 +11,12 @@
$: styleMap = $columnStyleMap.get(columnIdentifierKey);
export let isStatic = false;
+ export let isControlCell = false;
$: htmlAttributes = {
'data-sheet-element': 'cell',
'data-cell-static': isStatic ? true : undefined,
+ 'data-cell-control': isControlCell ? true : undefined,
};
</script>
diff --git a/mathesar_ui/src/icons.ts b/mathesar_ui/src/icons.ts
index 1f2c9e1953..9da34295e7 100644
--- a/mathesar_ui/src/icons.ts
+++ b/mathesar_ui/src/icons.ts
@@ -47,6 +47,7 @@ import {
faUnlink,
faUpload,
faUser,
+ faSave,
} from '@fortawesome/free-solid-svg-icons';
import type { IconProps } from '@mathesar-component-library/types';
@@ -84,6 +85,7 @@ export const iconSortAscending: IconProps = { data: faSortAmountDownAlt };
export const iconSortDescending: IconProps = { data: faSortAmountDown };
export const iconUndo: IconProps = { data: faUndo };
export const iconUnlink: IconProps = { data: faUnlink };
+export const iconSave: IconProps = { data: faSave };
// THINGS
//
diff --git a/mathesar_ui/src/pages/data-explorer/DataExplorerPage.svelte b/mathesar_ui/src/pages/data-explorer/DataExplorerPage.svelte
index 9e1c416724..b68a2b6d9e 100644
--- a/mathesar_ui/src/pages/data-explorer/DataExplorerPage.svelte
+++ b/mathesar_ui/src/pages/data-explorer/DataExplorerPage.svelte
@@ -1,21 +1,13 @@
<script lang="ts">
- import { router } from 'tinro';
- import type { Database, SchemaEntry } from '@mathesar/AppTypes';
+ import type { SchemaEntry } from '@mathesar/AppTypes';
import LayoutWithHeader from '@mathesar/layouts/LayoutWithHeader.svelte';
- import QueryBuilder from '@mathesar/systems/query-builder/QueryBuilder.svelte';
- import type QueryManager from '@mathesar/systems/query-builder/QueryManager';
- import { getSchemaPageUrl } from '@mathesar/routes/urls';
+ import { DataExplorer } from '@mathesar/systems/data-explorer';
+ import type { QueryManager } from '@mathesar/systems/data-explorer/types';
- export let database: Database;
export let schema: SchemaEntry;
export let queryManager: QueryManager;
$: ({ query } = queryManager);
-
- function gotoSchema() {
- const schemaURL = getSchemaPageUrl(database.name, schema.id);
- router.goto(schemaURL);
- }
</script>
<svelte:head>
@@ -23,5 +15,5 @@
</svelte:head>
<LayoutWithHeader fitViewport>
- <QueryBuilder {queryManager} on:close={gotoSchema} />
+ <DataExplorer {queryManager} />
</LayoutWithHeader>
diff --git a/mathesar_ui/src/pages/database/AddEditSchemaModal.svelte b/mathesar_ui/src/pages/database/AddEditSchemaModal.svelte
index cce21d7b2d..c6e3cea26e 100644
--- a/mathesar_ui/src/pages/database/AddEditSchemaModal.svelte
+++ b/mathesar_ui/src/pages/database/AddEditSchemaModal.svelte
@@ -6,7 +6,7 @@
createSchema,
updateSchema,
} from '@mathesar/stores/schemas';
- import AddEditSchemaModalForm from '@mathesar/pages/database/AddEditSchemaModalForm.svelte';
+ import NameAndDescInputModalForm from '@mathesar/components/NameAndDescInputModalForm.svelte';
import Identifier from '@mathesar/components/Identifier.svelte';
import { toast } from '@mathesar/stores/toast';
@@ -48,7 +48,7 @@
}
</script>
-<AddEditSchemaModalForm
+<NameAndDescInputModalForm
{controller}
{save}
{getNameValidationErrors}
@@ -62,4 +62,4 @@
Create Schema
{/if}
</span>
-</AddEditSchemaModalForm>
+</NameAndDescInputModalForm>
diff --git a/mathesar_ui/src/pages/exploration/ActionsPane.svelte b/mathesar_ui/src/pages/exploration/ActionsPane.svelte
new file mode 100644
index 0000000000..ac8bfd97f1
--- /dev/null
+++ b/mathesar_ui/src/pages/exploration/ActionsPane.svelte
@@ -0,0 +1,104 @@
+<script lang="ts">
+ import { router } from 'tinro';
+ import type { Database, SchemaEntry } from '@mathesar/AppTypes';
+ import { Button, Icon, iconError } from '@mathesar-component-library';
+ import QueryName from '@mathesar/components/QueryName.svelte';
+ import EntityType from '@mathesar/components/EntityType.svelte';
+ import { confirmDelete } from '@mathesar/stores/confirmation';
+ import { iconDelete, iconEdit, iconRefresh } from '@mathesar/icons';
+ import type { QueryRunner } from '@mathesar/systems/data-explorer/types';
+ import type { QueryInstance } from '@mathesar/api/queries';
+ import {
+ getSchemaPageUrl,
+ getExplorationEditorPageUrl,
+ } from '@mathesar/routes/urls';
+ import { deleteQuery } from '@mathesar/stores/queries';
+
+ export let database: Database;
+ export let schema: SchemaEntry;
+ export let query: QueryInstance;
+ export let queryRunner: QueryRunner;
+
+ $: ({ runState } = queryRunner);
+ $: isLoading = $runState?.state === 'processing';
+ $: isError = $runState?.state === 'failure';
+
+ function handleDeleteTable() {
+ void confirmDelete({
+ identifierType: 'Table',
+ onProceed: async () => {
+ await deleteQuery(query.id);
+ router.goto(getSchemaPageUrl(database.name, schema.id));
+ },
+ });
+ }
+</script>
+
+<div class="actions-pane">
+ <div class="heading">
+ <EntityType>Exploration</EntityType>
+ <h1><QueryName {query} /></h1>
+ </div>
+ <a href={getExplorationEditorPageUrl(database.name, schema.id, query.id)}>
+ <Button>
+ <Icon {...iconEdit} />
+ <span>Edit</span>
+ </Button>
+ </a>
+ <Button disabled={isLoading} size="medium" on:click={handleDeleteTable}>
+ <Icon {...iconDelete} />
+ <span>Delete</span>
+ </Button>
+ <div class="loading-info">
+ <Button
+ size="medium"
+ disabled={isLoading}
+ on:click={() => queryRunner.run()}
+ >
+ <Icon
+ {...isError && !isLoading ? iconError : iconRefresh}
+ spin={isLoading}
+ />
+ <span>
+ {#if isLoading}
+ Loading
+ {:else if isError}
+ Retry
+ {:else}
+ Refresh
+ {/if}
+ </span>
+ </Button>
+ </div>
+</div>
+
+<!--
+ This currently duplicates styles from table actions page.
+ TODO: Make ActionsPage a common layout component
+-->
+<style lang="scss">
+ .actions-pane {
+ border-bottom: 1px solid var(--color-gray-dark);
+ background-color: var(--color-white);
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding-right: 1rem;
+ }
+ .heading {
+ display: flex;
+ flex-direction: column;
+ border-right: 1px solid var(--color-gray-medium);
+ padding: 1rem;
+ margin-right: 0.5rem;
+ }
+ .heading h1 {
+ font-size: var(--text-size-x-large);
+ font-weight: 500;
+ margin-bottom: 0;
+ }
+ .loading-info {
+ margin-left: auto;
+ }
+</style>
diff --git a/mathesar_ui/src/pages/exploration/ExplorationPage.svelte b/mathesar_ui/src/pages/exploration/ExplorationPage.svelte
new file mode 100644
index 0000000000..8b2ee18964
--- /dev/null
+++ b/mathesar_ui/src/pages/exploration/ExplorationPage.svelte
@@ -0,0 +1,50 @@
+<script lang="ts">
+ import type { Database, SchemaEntry } from '@mathesar/AppTypes';
+ import LayoutWithHeader from '@mathesar/layouts/LayoutWithHeader.svelte';
+ import {
+ ExplorationResult,
+ QueryModel,
+ QueryRunner,
+ } from '@mathesar/systems/data-explorer';
+ import type { QueryInstance } from '@mathesar/api/queries';
+ import { currentDbAbstractTypes } from '@mathesar/stores/abstract-types';
+ import type { AbstractTypesMap } from '@mathesar/stores/abstract-types/types';
+ import ActionsPane from './ActionsPane.svelte';
+
+ export let database: Database;
+ export let schema: SchemaEntry;
+ export let query: QueryInstance;
+
+ let queryRunner: QueryRunner | undefined;
+
+ function createQueryRunner(
+ _query: QueryInstance,
+ abstractTypesMap: AbstractTypesMap,
+ ) {
+ queryRunner?.destroy();
+ queryRunner = new QueryRunner(new QueryModel(_query), abstractTypesMap);
+ }
+
+ $: createQueryRunner(query, $currentDbAbstractTypes.data);
+</script>
+
+<svelte:head>
+ <title>{query.name} | {schema.name} | Mathesar</title>
+</svelte:head>
+
+<LayoutWithHeader fitViewport>
+ {#if queryRunner}
+ <div class="exploration-page">
+ <ActionsPane {query} {queryRunner} {database} {schema} />
+ <ExplorationResult {queryRunner} />
+ </div>
+ {/if}
+</LayoutWithHeader>
+
+<style lang="scss">
+ .exploration-page {
+ display: grid;
+ grid-template: auto 1fr / 1fr;
+ height: 100%;
+ }
+</style>
diff --git a/mathesar_ui/src/pages/schema/SchemaPage.svelte b/mathesar_ui/src/pages/schema/SchemaPage.svelte
index f25dcfcbeb..39f8f3beca 100644
--- a/mathesar_ui/src/pages/schema/SchemaPage.svelte
+++ b/mathesar_ui/src/pages/schema/SchemaPage.svelte
@@ -8,6 +8,7 @@
import LayoutWithHeader from '@mathesar/layouts/LayoutWithHeader.svelte';
import {
getTablePageUrl,
+ getExplorationPageUrl,
getDataExplorerPageUrl,
getImportPageUrl,
getImportPreviewPageUrl,
@@ -19,6 +20,12 @@
export let database: Database;
export let schema: SchemaEntry;
+ /**
+ * This property will be used for the latest design changes
+ * Based on the subroute, the desired tab/section will be selected
+ */
+ export let section = 'overview';
+
$: tablesMap = $tablesStore.data;
$: queriesMap = $queries.data;
@@ -91,7 +98,7 @@
<ul class="entity-list">
{#each [...queriesMap.values()] as query (query.id)}
<li class="entity-list-item">
- <a href={getDataExplorerPageUrl(database.name, schema.id, query.id)}>
+ <a href={getExplorationPageUrl(database.name, schema.id, query.id)}>
<QueryName {query} />
</a>
</li>
diff --git a/mathesar_ui/src/routes/DataExplorerRoute.svelte b/mathesar_ui/src/routes/DataExplorerRoute.svelte
index 8e6c8c81de..5a28d57a1f 100644
--- a/mathesar_ui/src/routes/DataExplorerRoute.svelte
+++ b/mathesar_ui/src/routes/DataExplorerRoute.svelte
@@ -1,35 +1,36 @@
<script lang="ts">
- import { readable } from 'svelte/store';
import { router } from 'tinro';
- import type { TinroRouteMeta } from 'tinro';
-
import type { Database, SchemaEntry } from '@mathesar/AppTypes';
- import EventfulRoute from '@mathesar/components/routing/EventfulRoute.svelte';
- import QueryManager from '@mathesar/systems/query-builder/QueryManager';
- import QueryModel from '@mathesar/systems/query-builder/QueryModel';
- import { queries, getQuery } from '@mathesar/stores/queries';
+ import {
+ QueryManager,
+ QueryModel,
+ constructQueryModelFromTerseSummarizationHash,
+ } from '@mathesar/systems/data-explorer';
+ import { getQuery } from '@mathesar/stores/queries';
import { currentDbAbstractTypes } from '@mathesar/stores/abstract-types';
import type { CancellablePromise } from '@mathesar/component-library';
- import type { QueryInstance } from '@mathesar/api/queries/queryList';
+ import type { QueryInstance } from '@mathesar/api/queries';
import type { UnsavedQueryInstance } from '@mathesar/stores/queries';
- import { getAvailableName } from '@mathesar/utils/db';
import DataExplorerPage from '@mathesar/pages/data-explorer/DataExplorerPage.svelte';
import ErrorPage from '@mathesar/pages/ErrorPage.svelte';
- import { getDataExplorerPageUrl } from '@mathesar/routes/urls';
- import { constructQueryModelFromTerseSummarizationHash } from '@mathesar/systems/query-builder/urlSerializationUtils';
+ import {
+ getDataExplorerPageUrl,
+ getExplorationEditorPageUrl,
+ } from '@mathesar/routes/urls';
import AppendBreadcrumb from '@mathesar/components/breadcrumb/AppendBreadcrumb.svelte';
import { iconExploration } from '@mathesar/icons';
+ import { readable } from 'svelte/store';
export let database: Database;
export let schema: SchemaEntry;
+ export let queryId: number | undefined;
let is404 = false;
let queryManager: QueryManager | undefined;
let queryLoadPromise: CancellablePromise<QueryInstance>;
- $: queryStore = queryManager ? queryManager.query : readable(undefined);
- $: query = $queryStore;
+ $: ({ query } = queryManager ?? { query: readable(undefined) });
function createQueryManager(queryInstance: UnsavedQueryInstance) {
queryManager?.destroy();
@@ -40,7 +41,7 @@
is404 = false;
queryManager.on('save', async (instance) => {
try {
- const url = getDataExplorerPageUrl(
+ const url = getExplorationEditorPageUrl(
database.name,
schema.id,
instance.id,
@@ -66,45 +67,35 @@
// An unsaved query is already open
return;
}
- let newQueryModel = {
- name: getAvailableName(
- 'New_Exploration',
- new Set([...$queries.data.values()].map((e) => e.name)),
- ),
- };
const { hash } = $router;
if (hash) {
try {
- newQueryModel = {
- ...newQueryModel,
- ...constructQueryModelFromTerseSummarizationHash(hash),
- };
+ const newQueryModel =
+ constructQueryModelFromTerseSummarizationHash(hash);
router.location.hash.clear();
createQueryManager(newQueryModel);
- queryManager?.save();
return;
} catch {
// fail silently
console.error('Unable to create query model from hash', hash);
}
}
- createQueryManager(newQueryModel);
+ createQueryManager({});
}
- async function loadSavedQuery(meta: TinroRouteMeta) {
- const queryId = parseInt(meta.params.queryId, 10);
- if (Number.isNaN(queryId)) {
+ async function loadSavedQuery(_queryId: number) {
+ if (Number.isNaN(_queryId)) {
removeQueryManager();
return;
}
- if (queryManager && queryManager.getQueryModel().id === queryId) {
+ if (queryManager && queryManager.getQueryModel().id === _queryId) {
// The requested query is already open
return;
}
queryLoadPromise?.cancel();
- queryLoadPromise = getQuery(queryId);
+ queryLoadPromise = getQuery(_queryId);
try {
const queryInstance = await queryLoadPromise;
createQueryManager(queryInstance);
@@ -113,32 +104,42 @@
removeQueryManager();
}
}
-</script>
-<AppendBreadcrumb
- item={{
- type: 'simple',
- href: getDataExplorerPageUrl(database.name, schema.id, query?.id),
- label: query?.name || 'Data Explorer',
- icon: iconExploration,
- }}
-/>
+ function createOrLoadQuery(_queryId?: number) {
+ if (_queryId) {
+ void loadSavedQuery(_queryId);
+ } else {
+ createNewQuery();
+ }
+ }
+
+ $: createOrLoadQuery(queryId);
+</script>
-<EventfulRoute
- path="/:queryId"
- on:routeUpdated={(e) => loadSavedQuery(e.detail)}
- on:routeLoaded={(e) => loadSavedQuery(e.detail)}
-/>
-<EventfulRoute
- path="/"
- on:routeUpdated={createNewQuery}
- on:routeLoaded={createNewQuery}
-/>
+{#if $query?.id}
+ <AppendBreadcrumb
+ item={{
+ type: 'simple',
+ href: getExplorationEditorPageUrl(database.name, schema.id, $query.id),
+ label: $query?.name ? `Edit: ${$query?.name}` : 'Data Explorer',
+ icon: iconExploration,
+ }}
+ />
+{:else}
+ <AppendBreadcrumb
+ item={{
+ type: 'simple',
+ href: getDataExplorerPageUrl(database.name, schema.id),
+ label: 'Data Explorer',
+ icon: iconExploration,
+ }}
+ />
+{/if}
<!--TODO: Add loading state-->
{#if queryManager}
- <DataExplorerPage {database} {schema} {queryManager} />
+ <DataExplorerPage {schema} {queryManager} />
{:else if is404}
<ErrorPage>Exploration not found.</ErrorPage>
{/if}
diff --git a/mathesar_ui/src/routes/ExplorationRoute.svelte b/mathesar_ui/src/routes/ExplorationRoute.svelte
new file mode 100644
index 0000000000..ff83905eee
--- /dev/null
+++ b/mathesar_ui/src/routes/ExplorationRoute.svelte
@@ -0,0 +1,32 @@
+<script lang="ts">
+ import type { Database, SchemaEntry } from '@mathesar/AppTypes';
+ import AppendBreadcrumb from '@mathesar/components/breadcrumb/AppendBreadcrumb.svelte';
+ import { getExplorationPageUrl } from '@mathesar/routes/urls';
+ import { iconExploration } from '@mathesar/icons';
+ import ExplorationPage from '@mathesar/pages/exploration/ExplorationPage.svelte';
+ import { queries } from '@mathesar/stores/queries';
+ import ErrorPage from '@mathesar/pages/ErrorPage.svelte';
+
+ export let database: Database;
+ export let schema: SchemaEntry;
+ export let queryId: number;
+
+ $: query = $queries.data.get(queryId);
+</script>
+
+{#if query}
+ <AppendBreadcrumb
+ item={{
+ type: 'simple',
+ href: getExplorationPageUrl(database.name, schema.id, queryId),
+ label: query?.name ?? 'Exploration',
+ icon: iconExploration,
+ }}
+ />
+
+ <ExplorationPage {database} {schema} {query} />
+{:else if Number.isNaN(queryId)}
+ <ErrorPage>The specified URL is not found.</ErrorPage>
+{:else}
+ <ErrorPage>Table with id {queryId} not found.</ErrorPage>
+{/if}
diff --git a/mathesar_ui/src/routes/SchemaRoute.svelte b/mathesar_ui/src/routes/SchemaRoute.svelte
index a9c223657e..09055a9776 100644
--- a/mathesar_ui/src/routes/SchemaRoute.svelte
+++ b/mathesar_ui/src/routes/SchemaRoute.svelte
@@ -7,9 +7,11 @@
import SchemaPage from '@mathesar/pages/schema/SchemaPage.svelte';
import { currentSchemaId, schemas } from '@mathesar/stores/schemas';
import AppendBreadcrumb from '@mathesar/components/breadcrumb/AppendBreadcrumb.svelte';
+ import MultiPathRoute from '@mathesar/components/routing/MultiPathRoute.svelte';
import DataExplorerRoute from './DataExplorerRoute.svelte';
import TableRoute from './TableRoute.svelte';
import ImportRoute from './ImportRoute.svelte';
+ import ExplorationRoute from './ExplorationRoute.svelte';
export let database: Database;
export let schemaId: number;
@@ -27,25 +29,53 @@
{#if schema}
<AppendBreadcrumb item={{ type: 'schema', database, schema }} />
- <Route path="/">
- <SchemaPage {database} {schema} />
- </Route>
-
- <Route path="/import/*">
+ <Route path="/import/*" firstmatch>
<ImportRoute {database} {schema} />
</Route>
- <Route path="/data-explorer/*">
- <DataExplorerRoute {database} {schema} />
- </Route>
-
- <Route path="/:tableId/*" let:meta firstmatch>
+ <Route path="/tables/:tableId/*" let:meta firstmatch>
<TableRoute
{database}
{schema}
tableId={parseInt(meta.params.tableId, 10)}
/>
</Route>
+
+ <MultiPathRoute
+ paths={[
+ { name: 'edit-exploration', path: '/explorations/edit/:queryId' },
+ { name: 'new-exploration', path: '/data-explorer/' },
+ ]}
+ let:path
+ let:meta
+ >
+ <DataExplorerRoute
+ {database}
+ {schema}
+ queryId={path === 'edit-exploration'
+ ? parseInt(meta.params.queryId, 10)
+ : undefined}
+ />
+ </MultiPathRoute>
+
+ <Route path="/explorations/:queryId" let:meta firstmatch>
+ <ExplorationRoute
+ {database}
+ {schema}
+ queryId={parseInt(meta.params.queryId, 10)}
+ />
+ </Route>
+
+ <MultiPathRoute
+ paths={[
+ { name: 'tables', path: '/tables/' },
+ { name: 'explorations', path: '/explorations/' },
+ { name: 'overview', path: '/' },
+ ]}
+ let:path
+ >
+ <SchemaPage {database} {schema} section={path} />
+ </MultiPathRoute>
{:else}
<ErrorPage>Schema not found.</ErrorPage>
{/if}
diff --git a/mathesar_ui/src/routes/urls.ts b/mathesar_ui/src/routes/urls.ts
index ef16259698..76b60e465d 100644
--- a/mathesar_ui/src/routes/urls.ts
+++ b/mathesar_ui/src/routes/urls.ts
@@ -27,20 +27,32 @@ export function getImportPreviewPageUrl(
export function getDataExplorerPageUrl(
databaseName: string,
schemaId: number,
- queryId?: number,
): string {
- if (queryId !== undefined) {
- return `/${databaseName}/${schemaId}/data-explorer/${queryId}/`;
- }
return `/${databaseName}/${schemaId}/data-explorer/`;
}
+export function getExplorationPageUrl(
+ databaseName: string,
+ schemaId: number,
+ queryId: number,
+): string {
+ return `/${databaseName}/${schemaId}/explorations/${queryId}/`;
+}
+
+export function getExplorationEditorPageUrl(
+ databaseName: string,
+ schemaId: number,
+ queryId: number,
+): string {
+ return `/${databaseName}/${schemaId}/explorations/edit/${queryId}/`;
+}
+
export function getTablePageUrl(
databaseName: string,
schemaId: number,
tableId: number,
): string {
- return `/${databaseName}/${schemaId}/${tableId}/`;
+ return `/${databaseName}/${schemaId}/tables/${tableId}/`;
}
export function getRecordPageUrl(
@@ -49,5 +61,5 @@ export function getRecordPageUrl(
tableId: number,
recordId: unknown,
): string {
- return `/${databaseName}/${schemaId}/${tableId}/${String(recordId)}`;
+ return `/${databaseName}/${schemaId}/tables/${tableId}/${String(recordId)}`;
}
diff --git a/mathesar_ui/src/stores/queries.ts b/mathesar_ui/src/stores/queries.ts
index 6fb4fbf705..584a150ad8 100644
--- a/mathesar_ui/src/stores/queries.ts
+++ b/mathesar_ui/src/stores/queries.ts
@@ -1,11 +1,16 @@
import { derived, writable, get } from 'svelte/store';
import type { Readable, Writable, Unsubscriber } from 'svelte/store';
-import { getAPI, postAPI, putAPI } from '@mathesar/utils/api';
+import { deleteAPI, getAPI, postAPI, putAPI } from '@mathesar/utils/api';
import type { RequestStatus, PaginatedResponse } from '@mathesar/utils/api';
import { preloadCommonData } from '@mathesar/utils/preloadData';
import CacheManager from '@mathesar/utils/CacheManager';
import type { SchemaEntry } from '@mathesar/AppTypes';
-import type { QueryInstance } from '@mathesar/api/queries/queryList';
+import type {
+ QueryInstance,
+ QueryGetResponse,
+ QueryRunRequest,
+ QueryRunResponse,
+} from '@mathesar/api/queries';
import { CancellablePromise } from '@mathesar-component-library';
import { currentSchemaId } from './schemas';
@@ -60,6 +65,12 @@ function setSchemaQueriesStore(
return store;
}
+function findSchemaStoreForTable(id: QueryInstance['id']) {
+ return [...schemasCacheManager.cache.values()].find((entry) =>
+ get(entry).data.has(id),
+ );
+}
+
export async function refetchQueriesForSchema(
schemaId: SchemaEntry['id'],
): Promise<QueriesStoreSubstance | undefined> {
@@ -151,14 +162,10 @@ export const queries: Readable<QueriesStoreSubstance> = derived(
export function createQuery(
newQuery: UnsavedQueryInstance,
-): CancellablePromise<QueryInstance> {
- const promise = postAPI<QueryInstance>('/api/db/v0/queries/', newQuery);
- void promise.then(() => {
- // TODO: Get schemaId as a query property
- const schemaId = get(currentSchemaId);
- if (schemaId) {
- void refetchQueriesForSchema(schemaId);
- }
+): CancellablePromise<QueryGetResponse> {
+ const promise = postAPI<QueryGetResponse>('/api/db/v0/queries/', newQuery);
+ void promise.then((instance) => {
+ void refetchQueriesForSchema(instance.schema);
return undefined;
});
return promise;
@@ -221,3 +228,22 @@ export function getQuery(
}
return new CancellablePromise((resolve) => resolve());
}
+
+export function runQuery(
+ request: QueryRunRequest,
+): CancellablePromise<QueryRunResponse> {
+ return postAPI('/api/db/v0/queries/run/', request);
+}
+
+export function deleteQuery(queryId: number): CancellablePromise<void> {
+ const promise = deleteAPI<void>(`/api/db/v0/queries/${queryId}/`);
+
+ void promise.then(() => {
+ findSchemaStoreForTable(queryId)?.update((storeData) => {
+ storeData.data.delete(queryId);
+ return { ...storeData, data: new Map(storeData.data) };
+ });
+ return undefined;
+ });
+ return promise;
+}
diff --git a/mathesar_ui/src/systems/query-builder/QueryBuilder.svelte b/mathesar_ui/src/systems/data-explorer/QueryBuilder.svelte
similarity index 57%
rename from mathesar_ui/src/systems/query-builder/QueryBuilder.svelte
rename to mathesar_ui/src/systems/data-explorer/QueryBuilder.svelte
index 664a63685d..777d9f2e1f 100644
--- a/mathesar_ui/src/systems/query-builder/QueryBuilder.svelte
+++ b/mathesar_ui/src/systems/data-explorer/QueryBuilder.svelte
@@ -1,26 +1,33 @@
<script lang="ts">
- import { createEventDispatcher } from 'svelte';
import {
Icon,
- LabeledInput,
InputGroup,
Button,
+ SpinnerButton,
} from '@mathesar-component-library';
import EditableTitle from '@mathesar/components/EditableTitle.svelte';
import SelectTableWithinCurrentSchema from '@mathesar/components/SelectTableWithinCurrentSchema.svelte';
import SaveStatusIndicator from '@mathesar/components/SaveStatusIndicator.svelte';
+ import NameAndDescInputModalForm from '@mathesar/components/NameAndDescInputModalForm.svelte';
import { tables as tablesDataStore } from '@mathesar/stores/tables';
import type { TableEntry } from '@mathesar/api/tables';
import { queries } from '@mathesar/stores/queries';
import { getAvailableName } from '@mathesar/utils/db';
- import { iconExploration, iconRedo, iconUndo } from '@mathesar/icons';
+ import {
+ iconExploration,
+ iconRedo,
+ iconUndo,
+ iconSave,
+ } from '@mathesar/icons';
+ import { modal } from '@mathesar/stores/modal';
+ import { toast } from '@mathesar/stores/toast';
import type QueryManager from './QueryManager';
import type { ColumnWithLink } from './utils';
import ColumnSelectionPane from './column-selection-pane/ColumnSelectionPane.svelte';
import ResultPane from './result-pane/ResultPane.svelte';
import OutputConfigSidebar from './output-config-sidebar/OutputConfigSidebar.svelte';
- const dispatch = createEventDispatcher();
+ const saveModalController = modal.spawnModalController();
export let queryManager: QueryManager;
@@ -52,7 +59,7 @@
queryManager.selectColumn(alias);
}
- function handleQueryNameChange(e: Event) {
+ function handleNameChange(e: Event) {
const target = e.target as HTMLInputElement;
if (target.value.trim() === '') {
target.value = getAvailableName(
@@ -62,24 +69,87 @@
}
void queryManager.update((q) => q.withName(target.value));
}
+
+ function getNameValidationErrors(name: string) {
+ const trimmedName = name.trim();
+ if (!trimmedName) {
+ return ['Name cannot be empty.'];
+ }
+ const isDuplicate = Array.from($queries.data ?? []).some(
+ ([, s]) => s.name.toLowerCase().trim() === trimmedName,
+ );
+ if (isDuplicate) {
+ return ['An exploration with that name already exists.'];
+ }
+ return [];
+ }
+
+ async function save() {
+ try {
+ await queryManager.save();
+ } catch (err) {
+ toast.fromError(err);
+ }
+ }
+
+ // TODO: Handle description
+ async function create(name: string) {
+ try {
+ await queryManager.update((q) => q.withName(name));
+ await save();
+ } catch (err) {
+ toast.fromError(err);
+ }
+ }
+
+ async function saveExistingOrCreateNew() {
+ if ($query.isSaved()) {
+ await save();
+ } else {
+ saveModalController.open();
+ }
+ }
</script>
-<div class="query-builder">
+<div class="data-explorer">
<div class="header">
<div class="title-wrapper">
<div class="icon">
<Icon {...iconExploration} size="1.5em" />
</div>
- <EditableTitle
- value={$query.name}
- size={1.266}
- on:change={handleQueryNameChange}
- />
+ {#if $query.isSaved()}
+ <EditableTitle
+ value={$query.name}
+ size={1.266}
+ on:change={handleNameChange}
+ />
+ <div class="base-table-holder">
+ Based on {currentTable?.name}
+ </div>
+ {:else}
+ <div class="title">Exploring</div>
+ <div class="base-table-holder">
+ <SelectTableWithinCurrentSchema
+ autoSelect="none"
+ table={currentTable}
+ on:change={(e) => onBaseTableChange(e.detail)}
+ />
+ </div>
+ {/if}
</div>
- <SaveStatusIndicator status={$state.saveState?.state} />
<div class="actions">
+ {#if $query.isSaved()}
+ <SaveStatusIndicator status={$state.saveState?.state} />
+ {/if}
+ <!-- TODO: Change disabled condition to is_valid(query) -->
+ <SpinnerButton
+ label="Save"
+ icon={iconSave}
+ disabled={!$query.base_table}
+ onClick={saveExistingOrCreateNew}
+ />
<InputGroup>
<Button
appearance="default"
@@ -98,34 +168,39 @@
<span>Redo</span>
</Button>
</InputGroup>
- <Button appearance="default" on:click={() => dispatch('close')}
- >Close</Button
- >
</div>
</div>
<div class="content-pane">
- <div class="input-sidebar">
- <div class="base-table-selector">
- <LabeledInput label="Select Base Table" layout="stacked">
- <SelectTableWithinCurrentSchema
- autoSelect="clear"
- table={currentTable}
- on:change={(e) => onBaseTableChange(e.detail)}
- />
- </LabeledInput>
+ {#if !$query.base_table}
+ <div class="help-text">Please select a table to start exploring</div>
+ {:else}
+ <div class="input-sidebar">
+ <ColumnSelectionPane
+ {queryManager}
+ on:add={(e) => addColumn(e.detail)}
+ />
</div>
- <ColumnSelectionPane {queryManager} on:add={(e) => addColumn(e.detail)} />
- </div>
- <!-- Do not use inputColumnManager in ResultPane because
- we'd also use ResultPane for query page where input column
- details would not be available-->
- <ResultPane {queryManager} />
- <OutputConfigSidebar {queryManager} />
+ <!-- Do not use inputColumnManager in ResultPane because
+ we'd also use ResultPane for query page where input column
+ details would not be available-->
+ <ResultPane queryRunner={queryManager} />
+ <OutputConfigSidebar {queryManager} />
+ {/if}
</div>
</div>
+<NameAndDescInputModalForm
+ controller={saveModalController}
+ save={create}
+ {getNameValidationErrors}
+ getInitialName={() => $query.name ?? ''}
+ getInitialDescription={() => ''}
+>
+ <span slot="title"> Save Exploration </span>
+</NameAndDescInputModalForm>
+
<style lang="scss">
- .query-builder {
+ .data-explorer {
position: absolute;
left: 0;
right: 0;
@@ -136,17 +211,27 @@
display: flex;
align-items: center;
height: 4rem;
- border-bottom: 1px solid var(--color-gray-dark);
+ border-bottom: 1px solid var(--color-gray-medium);
position: relative;
overflow: hidden;
+ background: var(--color-gray-lighter);
.title-wrapper {
display: flex;
align-items: center;
overflow: hidden;
padding: 0.7rem 1rem;
- margin-right: 1rem;
- border-right: 1px solid var(--color-gray-medium);
+
+ .title {
+ font-size: 1.266rem;
+ }
+
+ .base-table-holder {
+ flex-grow: 0;
+ flex-shrink: 0;
+ margin-left: 0.6rem;
+ min-width: 14rem;
+ }
}
.icon {
@@ -181,6 +266,10 @@
right: 0;
overflow-x: auto;
+ .help-text {
+ padding: 1rem;
+ }
+
.input-sidebar {
width: 20rem;
border-right: 1px solid var(--color-gray-medium);
@@ -189,17 +278,6 @@
flex-basis: 20rem;
display: flex;
flex-direction: column;
-
- .base-table-selector {
- border-bottom: 1px solid var(--color-gray-medium);
- padding: 1rem;
- background: var(--color-gray-light);
- flex-grow: 0;
- flex-shrink: 0;
- :global(label) {
- font-weight: 500;
- }
- }
}
}
}
diff --git a/mathesar_ui/src/systems/query-builder/QueryFilterTransformationModel.ts b/mathesar_ui/src/systems/data-explorer/QueryFilterTransformationModel.ts
similarity index 97%
rename from mathesar_ui/src/systems/query-builder/QueryFilterTransformationModel.ts
rename to mathesar_ui/src/systems/data-explorer/QueryFilterTransformationModel.ts
index 4df9ad0dbd..57c017cc7c 100644
--- a/mathesar_ui/src/systems/query-builder/QueryFilterTransformationModel.ts
+++ b/mathesar_ui/src/systems/data-explorer/QueryFilterTransformationModel.ts
@@ -1,4 +1,4 @@
-import type { QueryInstanceFilterTransformation } from '@mathesar/api/queries/queryList';
+import type { QueryInstanceFilterTransformation } from '@mathesar/api/queries';
export interface QueryFilterTransformationEntry {
columnIdentifier: string;
diff --git a/mathesar_ui/src/systems/query-builder/QueryListEntry.ts b/mathesar_ui/src/systems/data-explorer/QueryListEntry.ts
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/QueryListEntry.ts
rename to mathesar_ui/src/systems/data-explorer/QueryListEntry.ts
diff --git a/mathesar_ui/src/systems/query-builder/QueryManager.ts b/mathesar_ui/src/systems/data-explorer/QueryManager.ts
similarity index 61%
rename from mathesar_ui/src/systems/query-builder/QueryManager.ts
rename to mathesar_ui/src/systems/data-explorer/QueryManager.ts
index 88e8c8472e..7553026d90 100644
--- a/mathesar_ui/src/systems/query-builder/QueryManager.ts
+++ b/mathesar_ui/src/systems/data-explorer/QueryManager.ts
@@ -4,23 +4,16 @@ import {
EventHandler,
ImmutableMap,
isDefinedNonNullable,
+ CancellablePromise,
} from '@mathesar-component-library';
-import type { CancellablePromise } from '@mathesar-component-library/types';
import { getAPI } from '@mathesar/utils/api';
import type { RequestStatus } from '@mathesar/utils/api';
import CacheManager from '@mathesar/utils/CacheManager';
-import type {
- QueryInstance,
- QueryResultColumn,
- QueryResultColumns,
- QueryResultRecords,
-} from '@mathesar/api/queries/queryList';
+import type { QueryInstance } from '@mathesar/api/queries';
import type { TableEntry } from '@mathesar/api/tables';
import type { JoinableTablesResult } from '@mathesar/api/tables/joinable_tables';
import { createQuery, putQuery } from '@mathesar/stores/queries';
import { getTable } from '@mathesar/stores/tables';
-import Pagination from '@mathesar/utils/Pagination';
-import { toast } from '@mathesar/stores/toast';
import type { AbstractTypesMap } from '@mathesar/stores/abstract-types/types';
import { validateFilterEntry } from '@mathesar/components/filter-entry';
import type QueryModel from './QueryModel';
@@ -40,15 +33,13 @@ import type {
} from './utils';
import QueryFilterTransformationModel from './QueryFilterTransformationModel';
import QuerySummarizationTransformationModel from './QuerySummarizationTransformationModel';
+import QueryRunner from './QueryRunner';
function validateQuery(
queryModel: QueryModel,
columnMap: ProcessedQueryResultColumnMap,
): boolean {
- const general =
- isDefinedNonNullable(queryModel.base_table) &&
- isDefinedNonNullable(queryModel.name) &&
- queryModel.name.trim() !== '';
+ const general = isDefinedNonNullable(queryModel.base_table);
if (!general) {
return false;
}
@@ -67,14 +58,10 @@ function validateQuery(
});
}
-export default class QueryManager extends EventHandler<{
- save: QueryInstance;
-}> {
- query: Writable<QueryModel>;
-
- undoRedoManager: QueryUndoRedoManager;
+export default class QueryManager extends QueryRunner<{ save: QueryInstance }> {
+ private undoRedoManager: QueryUndoRedoManager;
- cacheManagers: {
+ private cacheManagers: {
inputColumns: CacheManager<number, InputColumnsStoreSubstance>;
} = {
inputColumns: new CacheManager(5),
@@ -83,29 +70,22 @@ export default class QueryManager extends EventHandler<{
state: Writable<{
inputColumnsFetchState?: RequestStatus;
saveState?: RequestStatus;
- columnsFetchState?: RequestStatus;
- recordsFetchState?: RequestStatus;
isUndoPossible: boolean;
isRedoPossible: boolean;
- lastFetchType: 'columns' | 'records' | 'both';
}> = writable({
isUndoPossible: false,
isRedoPossible: false,
- lastFetchType: 'both',
});
- pagination: Writable<Pagination> = writable(new Pagination({ size: 100 }));
-
- records: Writable<QueryResultRecords> = writable({ count: 0, results: [] });
-
- abstractTypeMap: AbstractTypesMap;
-
inputColumns: Writable<InputColumnsStoreSubstance> = writable({
baseTableColumns: new Map(),
tablesThatReferenceBaseTable: new Map(),
columnInformationMap: new Map(),
});
+ private eventHandler: EventHandler<{ save: QueryInstance }> =
+ new EventHandler();
+
// Processed columns
processedInitialColumns: Writable<ProcessedQueryResultColumnMap> = writable(
@@ -120,29 +100,19 @@ export default class QueryManager extends EventHandler<{
new ImmutableMap(),
);
- // Display stores
-
- selectedColumnAlias: Writable<QueryResultColumn['alias'] | undefined> =
- writable(undefined);
-
// Promises
- baseTableFetchPromise: CancellablePromise<TableEntry> | undefined;
+ private baseTableFetchPromise: CancellablePromise<TableEntry> | undefined;
- joinableColumnsfetchPromise:
+ private joinableColumnsfetchPromise:
| CancellablePromise<JoinableTablesResult>
| undefined;
- querySavePromise: CancellablePromise<QueryInstance> | undefined;
-
- queryColumnsFetchPromise: CancellablePromise<QueryResultColumns> | undefined;
-
- queryRecordsFetchPromise: CancellablePromise<QueryResultRecords> | undefined;
+ private querySavePromise: CancellablePromise<QueryInstance> | undefined;
+ // NEW CHANGES
constructor(query: QueryModel, abstractTypeMap: AbstractTypesMap) {
- super();
- this.abstractTypeMap = abstractTypeMap;
- this.query = writable(query);
+ super(query, abstractTypeMap);
this.reprocessColumns('both');
this.undoRedoManager = new QueryUndoRedoManager();
const inputColumnTreePromise = this.calculateInputColumnTree();
@@ -156,7 +126,6 @@ export default class QueryManager extends EventHandler<{
this.undoRedoManager.pushState(query, isQueryValid);
return query;
});
- void this.fetchColumnsAndRecords();
}
private async calculateInputColumnTree(): Promise<void> {
@@ -241,16 +210,6 @@ export default class QueryManager extends EventHandler<{
}
}
- async fetchColumnsAndRecords(): Promise<
- [QueryResultColumns | undefined, QueryResultRecords | undefined]
- > {
- this.state.update((state) => ({
- ...state,
- lastFetchType: 'both',
- }));
- return Promise.all([this.fetchColumns(), this.fetchResults()]);
- }
-
/**
* We are not creating a derived store so that we need to control
* the callback only for essential scenarios and not everytime
@@ -338,95 +297,26 @@ export default class QueryManager extends EventHandler<{
}
}
- private resetProcessedColumns(): void {
- this.processedResultColumns.set(new ImmutableMap());
- }
-
- private setProcessedColumnsFromResults(
- resultColumns: QueryResultColumn[],
- ): void {
- const newColumns = new ImmutableMap(
- resultColumns.map((column) => [
- column.alias,
- processColumn(column, this.abstractTypeMap),
- ]),
- );
- this.processedResultColumns.set(newColumns);
- }
-
private async updateQuery(queryModel: QueryModel): Promise<{
clientValidationState: RequestStatus;
- query?: QueryInstance;
}> {
this.query.set(queryModel);
- this.state.update((_state) => ({
- ..._state,
- saveState: { state: 'processing' },
- }));
-
- try {
- this.querySavePromise?.cancel();
- if (get(this.state).inputColumnsFetchState?.state !== 'success') {
- await this.calculateInputColumnTree();
- }
- const isQueryValid = validateQuery(
- queryModel,
- get(this.processedInitialColumns).withEntries(
- get(this.processedVirtualColumns),
- ),
- );
- if (!isQueryValid) {
- this.state.update((_state) => ({
- ..._state,
- saveState: {
- state: 'failure',
- errors: ['Query validation failed'],
- },
- }));
- return {
- clientValidationState: {
- state: 'failure',
- errors: ['TODO: Place validation errors here '],
- },
- };
- }
-
- const queryJSON = queryModel.toJSON();
- if (typeof queryJSON.id !== 'undefined') {
- // TODO: Figure out a better way to help TS identify this as a saved instance
- this.querySavePromise = putQuery(queryJSON as QueryInstance);
- } else {
- this.querySavePromise = createQuery(queryJSON);
- }
- const result = await this.querySavePromise;
- this.query.update((qr) => qr.withId(result.id).model);
- this.state.update((_state) => ({
- ..._state,
- saveState: { state: 'success' },
- }));
- await this.dispatch('save', result);
- return {
- clientValidationState: { state: 'success' },
- query: result,
- };
- } catch (err) {
- const errors =
- err instanceof Error
- ? [err.message]
- : ['An error occurred while trying to save the query'];
- this.state.update((_state) => ({
- ..._state,
- saveState: {
- state: 'failure',
- errors,
- },
- }));
- toast.error(`Unable to save query: ${errors.join(',')}`);
+ if (get(this.state).inputColumnsFetchState?.state !== 'success') {
+ await this.calculateInputColumnTree();
}
- return {
- clientValidationState: { state: 'success' },
- query: undefined,
- };
+ const isQueryValid = validateQuery(
+ queryModel,
+ get(this.processedInitialColumns).withEntries(
+ get(this.processedVirtualColumns),
+ ),
+ );
+ const clientValidationState: RequestStatus = isQueryValid
+ ? { state: 'success' }
+ : {
+ state: 'failure',
+ errors: ['TODO: Place validation errors here '],
+ };
+ return { clientValidationState };
}
private setUndoRedoStates(): void {
@@ -437,130 +327,11 @@ export default class QueryManager extends EventHandler<{
}));
}
- private async fetchColumns(): Promise<QueryResultColumns | undefined> {
- const q = this.getQueryModel();
-
- if (typeof q.id === 'undefined') {
- this.state.update((_state) => ({
- ..._state,
- columnsFetchState: { state: 'success' },
- }));
- this.resetProcessedColumns();
- return undefined;
- }
-
- try {
- this.state.update((_state) => ({
- ..._state,
- columnsFetchState: { state: 'processing' },
- }));
- this.queryColumnsFetchPromise?.cancel();
- this.queryColumnsFetchPromise = getAPI(
- `/api/db/v0/queries/${q.id}/columns/`,
- );
- const result = await this.queryColumnsFetchPromise;
- this.setProcessedColumnsFromResults(result);
- this.state.update((_state) => ({
- ..._state,
- columnsFetchState: { state: 'success' },
- }));
- return result;
- } catch (err) {
- this.state.update((_state) => ({
- ..._state,
- columnsFetchState: {
- state: 'failure',
- errors:
- err instanceof Error
- ? [err.message]
- : ['An error occurred while trying to fetch query columns'],
- },
- }));
- }
- return undefined;
- }
-
- private async fetchResults(): Promise<QueryResultRecords | undefined> {
- const q = this.getQueryModel();
-
- if (typeof q.id === 'undefined') {
- this.state.update((_state) => ({
- ..._state,
- recordsFetchState: { state: 'success' },
- }));
- this.records.set({ count: 0, results: [] });
- return undefined;
- }
-
- try {
- this.state.update((_state) => ({
- ..._state,
- recordsFetchState: { state: 'processing' },
- }));
- this.queryRecordsFetchPromise?.cancel();
- const { limit, offset } = get(this.pagination).recordsRequestParams();
- this.queryRecordsFetchPromise = getAPI(
- `/api/db/v0/queries/${q.id}/records/?limit=${limit}&offset=${offset}`,
- );
- const result = await this.queryRecordsFetchPromise;
- this.records.set({
- count: result.count,
- results: result.results ?? [],
- });
- this.state.update((_state) => ({
- ..._state,
- recordsFetchState: { state: 'success' },
- }));
- return result;
- } catch (err) {
- this.state.update((_state) => ({
- ..._state,
- recordsFetchState: {
- state: 'failure',
- errors:
- err instanceof Error
- ? [err.message]
- : ['An error occurred while trying to fetch query records'],
- },
- }));
- }
- return undefined;
- }
-
- async setPagination(
- pagination: Pagination,
- ): Promise<QueryResultRecords | undefined> {
- this.pagination.set(pagination);
- this.state.update((state) => ({
- ...state,
- lastFetchType: 'records',
- }));
- const result = await this.fetchResults();
- return result;
- }
-
- private resetPaginationPane(): void {
- this.pagination.update(
- (pagination) =>
- new Pagination({
- ...pagination,
- page: 1,
- }),
- );
- }
-
- private resetResults(): void {
- this.queryColumnsFetchPromise?.cancel();
- this.queryRecordsFetchPromise?.cancel();
- this.records.set({ count: 0, results: [] });
- this.resetProcessedColumns();
- this.selectedColumnAlias.set(undefined);
+ private resetState(): void {
this.state.update((state) => ({
...state,
- columnsFetchState: undefined,
- recordsFetchState: undefined,
}));
- this.resetPaginationPane();
+ this.resetResults();
}
async update(
@@ -574,7 +345,9 @@ export default class QueryManager extends EventHandler<{
if (isValid) {
switch (updateDiff.type) {
case 'baseTable':
- this.resetResults();
+ this.resetState();
+ this.undoRedoManager.clear();
+ this.setUndoRedoStates();
await this.calculateInputColumnTree();
break;
case 'initialColumnName':
@@ -583,15 +356,14 @@ export default class QueryManager extends EventHandler<{
case 'initialColumnsArray':
if (!updateDiff.diff.initial_columns?.length) {
// All columns have been deleted
- this.resetResults();
+ this.resetState();
} else {
this.reprocessColumns('initial');
- await this.fetchColumnsAndRecords();
+ await this.run();
}
break;
case 'transformations':
- this.resetPaginationPane();
- await this.fetchColumnsAndRecords();
+ await this.resetPaginationAndRun();
break;
default:
break;
@@ -599,13 +371,6 @@ export default class QueryManager extends EventHandler<{
}
}
- // Meant to be used directly outside query manager
- async save(): Promise<void> {
- await this.updateQuery(this.getQueryModel());
- this.resetPaginationPane();
- await this.fetchColumnsAndRecords();
- }
-
private async performUndoRedoSync(query?: QueryModel): Promise<void> {
if (query) {
const currentQueryModelData = this.getQueryModel();
@@ -617,7 +382,7 @@ export default class QueryManager extends EventHandler<{
this.reprocessColumns('both');
await this.updateQuery(queryToSet);
this.setUndoRedoStates();
- await this.fetchColumnsAndRecords();
+ await this.run();
} else {
this.setUndoRedoStates();
}
@@ -633,28 +398,49 @@ export default class QueryManager extends EventHandler<{
await this.performUndoRedoSync(query);
}
- getQueryModel(): QueryModel {
- return get(this.query);
- }
-
- selectColumn(alias: QueryResultColumn['alias']): void {
- if (
- get(this.query).initial_columns.some((column) => column.alias === alias)
- ) {
- this.selectedColumnAlias.set(alias);
- } else {
- this.selectedColumnAlias.set(undefined);
+ /**
+ * @throws Error if unable to save
+ */
+ async save(): Promise<QueryModel> {
+ const queryJSON = this.getQueryModel().toJSON();
+ this.state.update((_state) => ({
+ ..._state,
+ saveState: { state: 'processing' },
+ }));
+ try {
+ this.querySavePromise?.cancel();
+ // TODO: Check for latest validation status here
+ if (queryJSON.id !== undefined) {
+ // TODO: Figure out a better way to help TS identify this as a saved instance
+ this.querySavePromise = putQuery(queryJSON as QueryInstance);
+ } else {
+ this.querySavePromise = createQuery(queryJSON);
+ }
+ const result = await this.querySavePromise;
+ this.query.update((qr) => qr.withId(result.id).model);
+ await this.dispatch('save', result);
+ this.state.update((_state) => ({
+ ..._state,
+ saveState: { state: 'success' },
+ }));
+ return this.getQueryModel();
+ } catch (err) {
+ const errors =
+ err instanceof Error
+ ? [err.message]
+ : ['An error occurred while trying to save the query'];
+ this.state.update((_state) => ({
+ ..._state,
+ saveState: {
+ state: 'failure',
+ errors,
+ },
+ }));
+ throw err;
}
}
- clearSelectedColumn(): void {
- this.selectedColumnAlias.set(undefined);
- }
-
destroy(): void {
super.destroy();
- this.queryColumnsFetchPromise?.cancel();
- this.queryColumnsFetchPromise?.cancel();
- this.queryRecordsFetchPromise?.cancel();
}
}
diff --git a/mathesar_ui/src/systems/query-builder/QueryModel.ts b/mathesar_ui/src/systems/data-explorer/QueryModel.ts
similarity index 92%
rename from mathesar_ui/src/systems/query-builder/QueryModel.ts
rename to mathesar_ui/src/systems/data-explorer/QueryModel.ts
index 3c9fa4380b..85dd355b75 100644
--- a/mathesar_ui/src/systems/query-builder/QueryModel.ts
+++ b/mathesar_ui/src/systems/data-explorer/QueryModel.ts
@@ -1,7 +1,7 @@
import type {
QueryInstanceInitialColumn,
QueryInstanceTransformation,
-} from '@mathesar/api/queries/queryList';
+} from '@mathesar/api/queries';
import type { UnsavedQueryInstance } from '@mathesar/stores/queries';
import QueryFilterTransformationModel from './QueryFilterTransformationModel';
import QuerySummarizationTransformationModel from './QuerySummarizationTransformationModel';
@@ -156,22 +156,6 @@ export default class QueryModel {
};
}
- withTransformations(
- transformations?: QueryInstanceTransformation[],
- ): QueryModelUpdateDiff {
- const model = new QueryModel({
- ...this,
- transformations,
- });
- return {
- model,
- type: 'transformations',
- diff: {
- transformations,
- },
- };
- }
-
withTransformationModels(
transformationModels?: QueryTransformationModel[],
): QueryModelUpdateDiff {
@@ -203,4 +187,8 @@ export default class QueryModel {
),
};
}
+
+ isSaved(): boolean {
+ return !!this.id;
+ }
}
diff --git a/mathesar_ui/src/systems/data-explorer/QueryRunner.ts b/mathesar_ui/src/systems/data-explorer/QueryRunner.ts
new file mode 100644
index 0000000000..06db737ae2
--- /dev/null
+++ b/mathesar_ui/src/systems/data-explorer/QueryRunner.ts
@@ -0,0 +1,152 @@
+import { get, writable } from 'svelte/store';
+import type { Writable } from 'svelte/store';
+import type { RequestStatus } from '@mathesar/utils/api';
+import {
+ ImmutableMap,
+ CancellablePromise,
+ EventHandler,
+} from '@mathesar-component-library';
+import Pagination from '@mathesar/utils/Pagination';
+import type {
+ QueryResultRecords,
+ QueryRunResponse,
+ QueryResultColumn,
+} from '@mathesar/api/queries';
+import { runQuery } from '@mathesar/stores/queries';
+import type { AbstractTypesMap } from '@mathesar/stores/abstract-types/types';
+import type QueryModel from './QueryModel';
+import { processColumns } from './utils';
+import type { ProcessedQueryResultColumnMap } from './utils';
+
+// TODO: Find a better way to implement type safety here
+type QueryRunEvent = { run: QueryRunResponse };
+type Events = Record<string, unknown> & Partial<QueryRunEvent>;
+
+export default class QueryRunner<
+ T extends Events = Events,
+> extends EventHandler<T & QueryRunEvent> {
+ query: Writable<QueryModel>;
+
+ abstractTypeMap: AbstractTypesMap;
+
+ runState: Writable<RequestStatus | undefined> = writable();
+
+ pagination: Writable<Pagination> = writable(new Pagination({ size: 100 }));
+
+ records: Writable<QueryResultRecords> = writable({ count: 0, results: [] });
+
+ processedColumns: Writable<ProcessedQueryResultColumnMap> = writable(
+ new ImmutableMap(),
+ );
+
+ // Display stores
+
+ selectedColumnAlias: Writable<QueryResultColumn['alias'] | undefined> =
+ writable(undefined);
+
+ private runPromise: CancellablePromise<QueryRunResponse> | undefined;
+
+ constructor(query: QueryModel, abstractTypeMap: AbstractTypesMap) {
+ super();
+ this.abstractTypeMap = abstractTypeMap;
+ this.query = writable(query);
+ void this.run();
+ }
+
+ async run(): Promise<QueryRunResponse | undefined> {
+ this.runPromise?.cancel();
+ const queryModel = this.getQueryModel();
+
+ if (queryModel.base_table === undefined) {
+ const records = { count: 0, results: [] };
+ this.processedColumns.set(new ImmutableMap());
+ this.records.set(records);
+ this.runState.set({ state: 'success' });
+ return undefined;
+ }
+
+ try {
+ const paginationRequest = get(this.pagination).recordsRequestParams();
+ this.runState.set({ state: 'processing' });
+ this.runPromise = runQuery({
+ base_table: queryModel.base_table,
+ initial_columns: queryModel.initial_columns,
+ transformations: queryModel.transformationModels.map((transformation) =>
+ transformation.toJSON(),
+ ),
+ parameters: {
+ ...paginationRequest,
+ },
+ });
+ const response = await this.runPromise;
+ this.processedColumns.set(processColumns(response, this.abstractTypeMap));
+ this.records.set(response.records);
+ await this.dispatch('run', response);
+ this.runState.set({ state: 'success' });
+ return response;
+ } catch (err) {
+ const errorMessage =
+ err instanceof Error
+ ? err.message
+ : 'Unable to run query due to an unknown reason';
+ this.runState.set({ state: 'failure', errors: [errorMessage] });
+ }
+ return undefined;
+ }
+
+ async setPagination(
+ pagination: Pagination,
+ ): Promise<QueryResultRecords | undefined> {
+ this.pagination.set(pagination);
+ const result = await this.run();
+ return result?.records;
+ }
+
+ protected resetPagination(): void {
+ this.pagination.update(
+ (pagination) =>
+ new Pagination({
+ ...pagination,
+ page: 1,
+ }),
+ );
+ }
+
+ protected resetResults(): void {
+ this.selectedColumnAlias.set(undefined);
+ this.runPromise?.cancel();
+ this.resetPagination();
+ this.records.set({ count: 0, results: [] });
+ this.processedColumns.set(new ImmutableMap());
+ this.runState.set(undefined);
+ }
+
+ protected async resetPaginationAndRun(): Promise<
+ QueryRunResponse | undefined
+ > {
+ this.resetPagination();
+ return this.run();
+ }
+
+ selectColumn(alias: QueryResultColumn['alias']): void {
+ if (
+ get(this.query).initial_columns.some((column) => column.alias === alias)
+ ) {
+ this.selectedColumnAlias.set(alias);
+ } else {
+ this.selectedColumnAlias.set(undefined);
+ }
+ }
+
+ clearSelectedColumn(): void {
+ this.selectedColumnAlias.set(undefined);
+ }
+
+ getQueryModel(): QueryModel {
+ return get(this.query);
+ }
+
+ destroy(): void {
+ this.runPromise?.cancel();
+ }
+}
diff --git a/mathesar_ui/src/systems/query-builder/QuerySummarizationTransformationModel.ts b/mathesar_ui/src/systems/data-explorer/QuerySummarizationTransformationModel.ts
similarity index 96%
rename from mathesar_ui/src/systems/query-builder/QuerySummarizationTransformationModel.ts
rename to mathesar_ui/src/systems/data-explorer/QuerySummarizationTransformationModel.ts
index 7b6d23e67e..5fc75c9693 100644
--- a/mathesar_ui/src/systems/query-builder/QuerySummarizationTransformationModel.ts
+++ b/mathesar_ui/src/systems/data-explorer/QuerySummarizationTransformationModel.ts
@@ -1,5 +1,5 @@
-import type { QueryInstanceSummarizationTransformation } from '@mathesar/api/queries/queryList';
-import { ImmutableMap } from '@mathesar/component-library';
+import type { QueryInstanceSummarizationTransformation } from '@mathesar/api/queries';
+import { ImmutableMap } from '@mathesar-component-library';
export interface QuerySummarizationAggregationEntry {
inputAlias: string;
diff --git a/mathesar_ui/src/systems/query-builder/QueryUndoRedoManager.ts b/mathesar_ui/src/systems/data-explorer/QueryUndoRedoManager.ts
similarity index 96%
rename from mathesar_ui/src/systems/query-builder/QueryUndoRedoManager.ts
rename to mathesar_ui/src/systems/data-explorer/QueryUndoRedoManager.ts
index 447139cb9f..ffa958b9e4 100644
--- a/mathesar_ui/src/systems/query-builder/QueryUndoRedoManager.ts
+++ b/mathesar_ui/src/systems/data-explorer/QueryUndoRedoManager.ts
@@ -58,4 +58,8 @@ export default class QueryUndoRedoManager {
}
return undefined;
}
+
+ clear(): void {
+ this.current = undefined;
+ }
}
diff --git a/mathesar_ui/src/systems/query-builder/column-selection-pane/ColumnSelectionPane.svelte b/mathesar_ui/src/systems/data-explorer/column-selection-pane/ColumnSelectionPane.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/column-selection-pane/ColumnSelectionPane.svelte
rename to mathesar_ui/src/systems/data-explorer/column-selection-pane/ColumnSelectionPane.svelte
diff --git a/mathesar_ui/src/systems/query-builder/column-selection-pane/SelectableColumn.svelte b/mathesar_ui/src/systems/data-explorer/column-selection-pane/SelectableColumn.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/column-selection-pane/SelectableColumn.svelte
rename to mathesar_ui/src/systems/data-explorer/column-selection-pane/SelectableColumn.svelte
diff --git a/mathesar_ui/src/systems/query-builder/column-selection-pane/SelectableColumnTree.svelte b/mathesar_ui/src/systems/data-explorer/column-selection-pane/SelectableColumnTree.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/column-selection-pane/SelectableColumnTree.svelte
rename to mathesar_ui/src/systems/data-explorer/column-selection-pane/SelectableColumnTree.svelte
diff --git a/mathesar_ui/src/systems/query-builder/column-selection-pane/TableGroupCollapsible.svelte b/mathesar_ui/src/systems/data-explorer/column-selection-pane/TableGroupCollapsible.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/column-selection-pane/TableGroupCollapsible.svelte
rename to mathesar_ui/src/systems/data-explorer/column-selection-pane/TableGroupCollapsible.svelte
diff --git a/mathesar_ui/src/systems/data-explorer/index.ts b/mathesar_ui/src/systems/data-explorer/index.ts
new file mode 100644
index 0000000000..06babd50dc
--- /dev/null
+++ b/mathesar_ui/src/systems/data-explorer/index.ts
@@ -0,0 +1,6 @@
+export { default as DataExplorer } from './QueryBuilder.svelte';
+export { default as QueryManager } from './QueryManager';
+export { default as QueryRunner } from './QueryRunner';
+export { default as QueryModel } from './QueryModel';
+export { default as ExplorationResult } from './result-pane/Results.svelte';
+export * from './urlSerializationUtils';
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/FilterTransformation.svelte b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/FilterTransformation.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/FilterTransformation.svelte
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/FilterTransformation.svelte
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/OutputConfigSidebar.svelte b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/OutputConfigSidebar.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/OutputConfigSidebar.svelte
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/OutputConfigSidebar.svelte
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/TransformationsPane.svelte b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/TransformationsPane.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/TransformationsPane.svelte
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/TransformationsPane.svelte
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/summarization/Aggregation.svelte b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/summarization/Aggregation.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/summarization/Aggregation.svelte
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/summarization/Aggregation.svelte
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/summarization/SummarizationTransformation.svelte b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/summarization/SummarizationTransformation.svelte
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/summarization/SummarizationTransformation.svelte
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/summarization/SummarizationTransformation.svelte
diff --git a/mathesar_ui/src/systems/query-builder/output-config-sidebar/transformationUtils.ts b/mathesar_ui/src/systems/data-explorer/output-config-sidebar/transformationUtils.ts
similarity index 100%
rename from mathesar_ui/src/systems/query-builder/output-config-sidebar/transformationUtils.ts
rename to mathesar_ui/src/systems/data-explorer/output-config-sidebar/transformationUtils.ts
diff --git a/mathesar_ui/src/systems/data-explorer/result-pane/ResultPane.svelte b/mathesar_ui/src/systems/data-explorer/result-pane/ResultPane.svelte
new file mode 100644
index 0000000000..483988fc06
--- /dev/null
+++ b/mathesar_ui/src/systems/data-explorer/result-pane/ResultPane.svelte
@@ -0,0 +1,83 @@
+<script lang="ts">
+ import { Button, Spinner, Icon } from '@mathesar-component-library';
+ import { iconRefresh } from '@mathesar/icons';
+ import type QueryRunner from '../QueryRunner';
+ import Results from './Results.svelte';
+
+ export let queryRunner: QueryRunner;
+
+ $: ({ query, runState } = queryRunner);
+ $: ({ base_table, initial_columns } = $query);
+
+ $: columnRunState = $runState?.state;
+ $: recordRunState = $runState?.state;
+</script>
+
+<section data-identifier="result">
+ <header>
+ <span class="title">Result</span>
+ {#if base_table && initial_columns.length}
+ <span class="info">
+ {#if columnRunState === 'processing' || recordRunState === 'processing'}
+ Running query
+ <Spinner />
+ {:else if columnRunState === 'failure' || recordRunState === 'failure'}
+ Query failed to run
+ <Button
+ appearance="plain"
+ size="small"
+ class="padding-zero"
+ on:click={() => queryRunner.run()}
+ >
+ <Icon {...iconRefresh} size="0.6rem" />
+ <span>Retry</span>
+ </Button>
+ {/if}
+ </span>
+ {/if}
+ </header>
+ {#if !initial_columns.length}
+ <div class="empty-state">
+ Please add a column from the column selection pane to get started.
+ </div>
+ {:else}
+ <Results {queryRunner} />
+ {/if}
+</section>
+
+<style lang="scss">
+ section {
+ position: relative;
+ flex-grow: 1;
+ overflow: hidden;
+ flex-shrink: 0;
+ margin: 10px;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid #e5e5e5;
+ border-radius: 4px;
+
+ header {
+ padding: 8px 10px;
+ border-bottom: 1px solid #e5e5e5;
+ display: flex;
+ align-items: center;
+
+ .title {
+ font-weight: 600;
+ }
+ .info {
+ margin-left: 8px;
+ color: #71717a;
+ font-size: 0.875rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ }
+ }
+
+ .empty-state {
+ padding: 1rem;
+ }
+ }
+</style>
diff --git a/mathesar_ui/src/systems/data-explorer/result-pane/Results.svelte b/mathesar_ui/src/systems/data-explorer/result-pane/Results.svelte
new file mode 100644
index 0000000000..4e9122d89a
--- /dev/null
+++ b/mathesar_ui/src/systems/data-explorer/result-pane/Results.svelte
@@ -0,0 +1,273 @@
+<script lang="ts">
+ import { Button, ImmutableMap } from '@mathesar-component-library';
+ import {
+ Sheet,
+ SheetHeader,
+ SheetVirtualRows,
+ SheetRow,
+ SheetCell,
+ SheetCellResizer,
+ } from '@mathesar/components/sheet';
+ import PaginationGroup from '@mathesar/components/PaginationGroup.svelte';
+ import CellFabric from '@mathesar/components/cell-fabric/CellFabric.svelte';
+ import ColumnName from '@mathesar/components/column/ColumnName.svelte';
+ import type QueryRunner from '../QueryRunner';
+
+ export let queryRunner: QueryRunner;
+
+ const ID_ROW_CONTROL_COLUMN = 'row-control';
+
+ $: ({
+ query,
+ processedColumns,
+ records,
+ selectedColumnAlias,
+ pagination,
+ runState,
+ } = queryRunner);
+ $: ({ initial_columns } = $query);
+
+ $: columnRunState = $runState?.state;
+ $: recordRunState = $runState?.state;
+
+ $: errors = $runState?.state === 'failure' ? $runState.errors : [];
+ $: columnList = [...$processedColumns.values()];
+ $: sheetColumns = columnList.length
+ ? [{ id: ID_ROW_CONTROL_COLUMN }, ...columnList]
+ : [];
+ // Show a dummy ghost row when there are no records
+ $: showDummyGhostRow =
+ recordRunState === 'success' && !$records.results.length;
+ $: sheetItemCount = showDummyGhostRow ? 1 : $records.results.length;
+
+ const columnWidths = new ImmutableMap([[ID_ROW_CONTROL_COLUMN, 70]]);
+
+ function checkAndUnselectColumn(e: MouseEvent) {
+ const target = e.target as HTMLElement;
+ if (
+ target.closest(
+ '[data-sheet-element="header"] [data-sheet-element="cell"]',
+ )
+ ) {
+ return;
+ }
+ if ($selectedColumnAlias) {
+ const closestCell = target.closest(
+ '[data-sheet-element="row"] [data-sheet-element="cell"]',
+ );
+ if (
+ closestCell &&
+ closestCell.querySelector(
+ `[data-column-identifier="${$selectedColumnAlias}"]`,
+ )
+ ) {
+ return;
+ }
+ }
+ queryRunner.clearSelectedColumn();
+ }
+</script>
+
+<div data-identifier="query-run-result">
+ {#if !initial_columns.length}
+ <div class="empty-state">
+ This exploration does not contain any columns. Edit the exploration to add
+ columns to it.
+ </div>
+ {:else if errors.length}
+ <div class="empty-state errors">
+ {#each errors as error}
+ <p>{error}</p>
+ {/each}
+ </div>
+ {:else}
+ <Sheet
+ columns={sheetColumns}
+ getColumnIdentifier={(c) => c.id}
+ {columnWidths}
+ on:click={checkAndUnselectColumn}
+ usesVirtualList
+ >
+ <SheetHeader>
+ <SheetCell
+ columnIdentifierKey={ID_ROW_CONTROL_COLUMN}
+ isStatic
+ isControlCell
+ let:htmlAttributes
+ let:style
+ >
+ <div {...htmlAttributes} {style} />
+ </SheetCell>
+
+ {#each columnList as processedQueryColumn (processedQueryColumn.id)}
+ <SheetCell
+ columnIdentifierKey={processedQueryColumn.id}
+ let:htmlAttributes
+ let:style
+ >
+ <div {...htmlAttributes} {style}>
+ <Button
+ appearance="plain"
+ class="column-name-wrapper {$selectedColumnAlias ===
+ processedQueryColumn.column.alias
+ ? 'selected'
+ : ''}"
+ on:click={() => {
+ queryRunner.selectColumn(processedQueryColumn.column.alias);
+ }}
+ >
+ <!--TODO: Use a separate prop to identify column that isn't fetched yet
+ instead of type:unknown-->
+ <ColumnName
+ isLoading={columnRunState === 'processing' &&
+ processedQueryColumn.column.type === 'unknown'}
+ column={{
+ ...processedQueryColumn.column,
+ name:
+ processedQueryColumn.column.display_name ??
+ processedQueryColumn.column.alias,
+ }}
+ />
+ </Button>
+ <SheetCellResizer columnIdentifierKey={processedQueryColumn.id} />
+ </div>
+ </SheetCell>
+ {/each}
+ </SheetHeader>
+
+ <SheetVirtualRows
+ itemCount={sheetItemCount}
+ paddingBottom={30}
+ itemSize={() => 30}
+ let:items
+ >
+ {#each items as item (item.key)}
+ {#if $records.results[item.index] || showDummyGhostRow}
+ <SheetRow style={item.style} let:htmlAttributes let:styleString>
+ <div {...htmlAttributes} style={styleString}>
+ <SheetCell
+ columnIdentifierKey={ID_ROW_CONTROL_COLUMN}
+ isStatic
+ isControlCell
+ let:htmlAttributes
+ let:style
+ >
+ <div {...htmlAttributes} {style}>
+ {$pagination.offset + item.index + 1}
+ </div>
+ </SheetCell>
+
+ {#each columnList as processedQueryColumn (processedQueryColumn.id)}
+ <SheetCell
+ columnIdentifierKey={processedQueryColumn.id}
+ let:htmlAttributes
+ let:style
+ >
+ <div
+ {...htmlAttributes}
+ {style}
+ class={$selectedColumnAlias ===
+ processedQueryColumn.column.alias
+ ? 'selected'
+ : ''}
+ >
+ {#if $records.results[item.index]}
+ <CellFabric
+ columnFabric={processedQueryColumn}
+ value={$records.results[item.index][
+ processedQueryColumn.id
+ ]}
+ showAsSkeleton={recordRunState === 'processing'}
+ disabled={true}
+ />
+ {/if}
+ </div>
+ </SheetCell>
+ {/each}
+ </div>
+ </SheetRow>
+ {/if}
+ {/each}
+ </SheetVirtualRows>
+ </Sheet>
+ <div data-identifier="status-bar">
+ {#if $records.count}
+ <div>
+ Showing {$pagination.leftBound}-{Math.min(
+ $records.count,
+ $pagination.rightBound,
+ )} of {$records.count}
+ </div>
+ {:else if recordRunState === 'success'}
+ No results found
+ {/if}
+ <PaginationGroup
+ pagination={$pagination}
+ totalCount={$records.count}
+ on:change={(e) => {
+ void queryRunner.setPagination(e.detail);
+ }}
+ />
+ </div>
+ {/if}
+</div>
+
+<style lang="scss">
+ [data-identifier='query-run-result'] {
+ position: relative;
+ flex-grow: 1;
+ overflow: hidden;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+
+ .empty-state {
+ padding: 1rem;
+
+ &.errors {
+ color: var(--danger-color);
+ }
+
+ p {
+ margin: 0;
+ }
+ }
+
+ :global(.sheet) {
+ bottom: 2.7rem;
+ }
+
+ [data-identifier='status-bar'] {
+ flex-grow: 0;
+ flex-shrink: 0;
+ border-top: 1px solid #dfdfdf;
+ padding: 0.2rem 0.6rem;
+ background: #fafafa;
+ display: flex;
+ align-items: center;
+ margin-top: auto;
+ height: 2.7rem;
+
+ :global(.pagination-group) {
+ margin-left: auto;
+ }
+ }
+
+ :global(button.column-name-wrapper) {
+ flex: 1;
+ padding: 6px 8px;
+ overflow: hidden;
+ height: 100%;
+ display: block;
+ overflow: hidden;
+ text-align: left;
+ }
+
+ :global(.column-name-wrapper.selected) {
+ background: #dedede !important;
+ }
+ :global([data-sheet-element='cell'].selected) {
+ background: #fafafa;
+ }
+ }
+</style>
diff --git a/mathesar_ui/src/systems/data-explorer/types.ts b/mathesar_ui/src/systems/data-explorer/types.ts
new file mode 100644
index 0000000000..fdb47f4958
--- /dev/null
+++ b/mathesar_ui/src/systems/data-explorer/types.ts
@@ -0,0 +1,2 @@
+export type { default as QueryManager } from './QueryManager';
+export type { default as QueryRunner } from './QueryRunner';
diff --git a/mathesar_ui/src/systems/query-builder/urlSerializationUtils.ts b/mathesar_ui/src/systems/data-explorer/urlSerializationUtils.ts
similarity index 91%
rename from mathesar_ui/src/systems/query-builder/urlSerializationUtils.ts
rename to mathesar_ui/src/systems/data-explorer/urlSerializationUtils.ts
index 20726ad2c4..ea12564ba5 100644
--- a/mathesar_ui/src/systems/query-builder/urlSerializationUtils.ts
+++ b/mathesar_ui/src/systems/data-explorer/urlSerializationUtils.ts
@@ -47,9 +47,10 @@ export function constructQueryModelFromTerseSummarizationHash(
if (!groupedColumn) {
return {};
}
- const aggregatedColumns = terseSummarization.columns.filter(
+ const firstNonGroupColumn = terseSummarization.columns.find(
(entry) => entry.id !== groupedColumnId,
);
+ const aggregatedColumns = firstNonGroupColumn ? [firstNonGroupColumn] : [];
return {
base_table: terseSummarization.baseTableId,
@@ -72,13 +73,13 @@ export function constructQueryModelFromTerseSummarizationHash(
aggregation_expressions: aggregatedColumns.map((entry) => ({
input_alias: entry.name,
output_alias: `${entry.name} (aggregated)`,
- function: 'aggregate_to_array',
+ function: 'count',
})),
},
display_names: aggregatedColumns.reduce(
(displayNames, entry) => ({
...displayNames,
- [`${entry.name} (aggregated)`]: `${entry.name} (aggregated)`,
+ [`${entry.name} (aggregated)`]: `Count(${entry.name})`,
}),
{} as Record<string, string>,
),
diff --git a/mathesar_ui/src/systems/query-builder/utils.ts b/mathesar_ui/src/systems/data-explorer/utils.ts
similarity index 89%
rename from mathesar_ui/src/systems/query-builder/utils.ts
rename to mathesar_ui/src/systems/data-explorer/utils.ts
index 5bb671abc2..26c3055acc 100644
--- a/mathesar_ui/src/systems/query-builder/utils.ts
+++ b/mathesar_ui/src/systems/data-explorer/utils.ts
@@ -1,6 +1,9 @@
import { ImmutableMap } from '@mathesar-component-library';
import type { ComponentAndProps } from '@mathesar-component-library/types';
-import type { QueryResultColumn } from '@mathesar/api/queries/queryList';
+import type {
+ QueryResultColumn,
+ QueryRunResponse,
+} from '@mathesar/api/queries';
import {
getAbstractTypeForDbType,
getFiltersForAbstractType,
@@ -24,6 +27,14 @@ import type {
import type { Column } from '@mathesar/api/tables/columns';
import type QueryModel from './QueryModel';
+export type ColumnOperationalState =
+ | {
+ state: 'processing';
+ processType?: 'creation' | 'deletion' | 'modification';
+ }
+ | { state: 'success' }
+ | { state: 'failure'; errors: string[] };
+
export interface ProcessedQueryResultColumn extends CellColumnFabric {
id: QueryResultColumn['alias'];
column: QueryResultColumn;
@@ -31,6 +42,8 @@ export interface ProcessedQueryResultColumn extends CellColumnFabric {
inputComponentAndProps: ComponentAndProps;
allowedFiltersMap: ReturnType<typeof getFiltersForAbstractType>;
preprocFunctions: AbstractTypePreprocFunctionDefinition[];
+ // Make this mandatory later
+ operationalState?: ColumnOperationalState;
}
export type ProcessedQueryResultColumnMap = ImmutableMap<
@@ -317,3 +330,32 @@ export function getTablesThatReferenceBaseTable(
return references;
}
+
+/** ======== */
+
+export function processColumns(
+ columnInformation: Pick<
+ QueryRunResponse,
+ 'output_columns' | 'column_metadata'
+ >,
+ abstractTypeMap: AbstractTypesMap,
+): ProcessedQueryResultColumnMap {
+ return new ImmutableMap(
+ columnInformation.output_columns.map((alias) => {
+ const columnMetaData = columnInformation.column_metadata[alias];
+ return [
+ alias,
+ processColumn(
+ {
+ alias,
+ display_name: columnMetaData.display_name ?? alias,
+ type: columnMetaData.type ?? 'unknown',
+ type_options: columnMetaData.type_options,
+ display_options: columnMetaData.display_options,
+ },
+ abstractTypeMap,
+ ),
+ ];
+ }),
+ );
+}
diff --git a/mathesar_ui/src/systems/query-builder/result-pane/ResultPane.svelte b/mathesar_ui/src/systems/query-builder/result-pane/ResultPane.svelte
deleted file mode 100644
index 09004f4389..0000000000
--- a/mathesar_ui/src/systems/query-builder/result-pane/ResultPane.svelte
+++ /dev/null
@@ -1,320 +0,0 @@
-<script lang="ts">
- import { Button, Spinner, Icon } from '@mathesar-component-library';
- import {
- Sheet,
- SheetHeader,
- SheetVirtualRows,
- SheetRow,
- SheetCell,
- SheetCellResizer,
- } from '@mathesar/components/sheet';
- import PaginationGroup from '@mathesar/components/PaginationGroup.svelte';
- import CellFabric from '@mathesar/components/cell-fabric/CellFabric.svelte';
- import ColumnName from '@mathesar/components/column/ColumnName.svelte';
- import { iconRefresh } from '@mathesar/icons';
- import type QueryManager from '../QueryManager';
-
- export let queryManager: QueryManager;
-
- $: ({
- query,
- processedResultColumns,
- records,
- state,
- selectedColumnAlias,
- pagination,
- } = queryManager);
- $: ({ base_table, initial_columns } = $query);
-
- $: columnRunState = $state.columnsFetchState?.state;
- $: recordRunState = $state.recordsFetchState?.state;
- $: lastFetchTypeEqualsRecords = $state.lastFetchType === 'records';
-
- $: columnRunErrors =
- $state.columnsFetchState?.state === 'failure'
- ? $state.columnsFetchState.errors
- : [];
- $: recordRunErrors =
- $state.recordsFetchState?.state === 'failure'
- ? $state.recordsFetchState.errors
- : [];
- // Prioritize showing column errors over record fetch errors
- $: errors = columnRunErrors.length > 0 ? columnRunErrors : recordRunErrors;
- $: columnList = [...$processedResultColumns.values()];
- // Show a dummy ghost row when there are no records
- $: showDummyGhostRow =
- recordRunState === 'success' && !$records.results.length;
- $: sheetItemCount = showDummyGhostRow ? 1 : $records.results.length;
-
- function checkAndUnselectColumn(e: MouseEvent) {
- const target = e.target as HTMLElement;
- if (
- target.closest(
- '[data-sheet-element="header"] [data-sheet-element="cell"]',
- )
- ) {
- return;
- }
- if ($selectedColumnAlias) {
- const closestCell = target.closest(
- '[data-sheet-element="row"] [data-sheet-element="cell"]',
- );
- if (
- closestCell &&
- closestCell.querySelector(
- `[data-column-identifier="${$selectedColumnAlias}"]`,
- )
- ) {
- return;
- }
- }
- queryManager.clearSelectedColumn();
- }
-</script>
-
-<section data-identifier="result">
- <header>
- <span class="title">Result</span>
- {#if base_table && initial_columns.length}
- <span class="info">
- {#if columnRunState === 'processing' || recordRunState === 'processing'}
- Running query
- <Spinner />
- {:else if columnRunState === 'failure' || recordRunState === 'failure'}
- Query failed to run
- <Button
- appearance="plain"
- size="small"
- class="padding-zero"
- on:click={() => queryManager.fetchColumnsAndRecords()}
- >
- <Icon {...iconRefresh} size="0.6rem" />
- <span>Retry</span>
- </Button>
- {/if}
- </span>
- {/if}
- </header>
- <div data-identifier="result-content">
- {#if !base_table}
- <div class="empty-state">
- Please select the base table to get started.
- </div>
- {:else if !initial_columns.length}
- <div class="empty-state">
- Please add a column from the column selection pane to get started.
- </div>
- {:else if errors.length}
- <div class="empty-state errors">
- {#each errors as error}
- <p>{error}</p>
- {/each}
- </div>
- {:else}
- <Sheet
- columns={columnList}
- getColumnIdentifier={(c) => c.id}
- on:click={checkAndUnselectColumn}
- usesVirtualList
- >
- <SheetHeader>
- {#each columnList as processedQueryColumn (processedQueryColumn.id)}
- <SheetCell
- columnIdentifierKey={processedQueryColumn.id}
- let:htmlAttributes
- let:style
- >
- <div {...htmlAttributes} {style}>
- <Button
- appearance="plain"
- class="column-name-wrapper {$selectedColumnAlias ===
- processedQueryColumn.column.alias
- ? 'selected'
- : ''}"
- on:click={() => {
- queryManager.selectColumn(
- processedQueryColumn.column.alias,
- );
- }}
- >
- <!--TODO: Use a separate prop to identify column that isn't fetched yet
- instead of type:unknown-->
- <ColumnName
- isLoading={columnRunState === 'processing' &&
- processedQueryColumn.column.type === 'unknown'}
- column={{
- ...processedQueryColumn.column,
- name:
- processedQueryColumn.column.display_name ??
- processedQueryColumn.column.alias,
- }}
- />
- </Button>
- <SheetCellResizer
- columnIdentifierKey={processedQueryColumn.id}
- />
- </div>
- </SheetCell>
- {/each}
- </SheetHeader>
-
- <SheetVirtualRows
- itemCount={sheetItemCount}
- paddingBottom={30}
- itemSize={() => 30}
- let:items
- >
- {#each items as item (item.key)}
- {#if $records.results[item.index] || showDummyGhostRow}
- <SheetRow style={item.style} let:htmlAttributes let:styleString>
- <div {...htmlAttributes} style={styleString}>
- {#each columnList as processedQueryColumn (processedQueryColumn.id)}
- <SheetCell
- columnIdentifierKey={processedQueryColumn.id}
- let:htmlAttributes
- let:style
- >
- <div
- {...htmlAttributes}
- {style}
- class={$selectedColumnAlias ===
- processedQueryColumn.column.alias
- ? 'selected'
- : ''}
- >
- {#if $records.results[item.index]}
- <CellFabric
- columnFabric={processedQueryColumn}
- value={$records.results[item.index][
- processedQueryColumn.id
- ]}
- showAsSkeleton={recordRunState === 'processing' &&
- (lastFetchTypeEqualsRecords ||
- $records.results[item.index][
- processedQueryColumn.id
- ] === undefined)}
- disabled={true}
- />
- {/if}
- </div>
- </SheetCell>
- {/each}
- </div>
- </SheetRow>
- {/if}
- {/each}
- </SheetVirtualRows>
- </Sheet>
- <div data-identifier="status-bar">
- {#if $records.count}
- <div>
- Showing {$pagination.leftBound}-{Math.min(
- $records.count,
- $pagination.rightBound,
- )} of {$records.count}
- </div>
- {:else if recordRunState === 'success'}
- No results found
- {/if}
- <PaginationGroup
- pagination={$pagination}
- totalCount={$records.count}
- on:change={(e) => {
- void queryManager.setPagination(e.detail);
- }}
- />
- </div>
- {/if}
- </div>
-</section>
-
-<style lang="scss">
- section {
- position: relative;
- flex-grow: 1;
- overflow: hidden;
- flex-shrink: 0;
- margin: 10px;
- display: flex;
- flex-direction: column;
- border: 1px solid #e5e5e5;
- border-radius: 4px;
-
- header {
- padding: 8px 10px;
- border-bottom: 1px solid #e5e5e5;
- display: flex;
- align-items: center;
-
- .title {
- font-weight: 600;
- }
- .info {
- margin-left: 8px;
- color: #71717a;
- font-size: 0.875rem;
- display: inline-flex;
- align-items: center;
- gap: 4px;
- }
- }
-
- [data-identifier='result-content'] {
- position: relative;
- flex-grow: 1;
- overflow: hidden;
- flex-shrink: 0;
- display: flex;
- flex-direction: column;
-
- .empty-state {
- padding: 1rem;
-
- &.errors {
- color: var(--danger-color);
- }
-
- p {
- margin: 0;
- }
- }
-
- :global(.sheet) {
- bottom: 2.7rem;
- }
-
- [data-identifier='status-bar'] {
- flex-grow: 0;
- flex-shrink: 0;
- border-top: 1px solid #dfdfdf;
- padding: 0.2rem 0.6rem;
- background: #fafafa;
- display: flex;
- align-items: center;
- margin-top: auto;
- height: 2.7rem;
-
- :global(.pagination-group) {
- margin-left: auto;
- }
- }
- }
-
- :global(button.column-name-wrapper) {
- flex: 1;
- padding: 6px 8px;
- overflow: hidden;
- height: 100%;
- display: block;
- overflow: hidden;
- text-align: left;
- }
-
- :global(.column-name-wrapper.selected) {
- background: #dedede !important;
- }
- :global([data-sheet-element='cell'].selected) {
- background: #fafafa;
- }
- }
-</style>
diff --git a/mathesar_ui/src/systems/table-view/actions-pane/ActionsPane.svelte b/mathesar_ui/src/systems/table-view/actions-pane/ActionsPane.svelte
index 4fb000356c..94cc7432bd 100644
--- a/mathesar_ui/src/systems/table-view/actions-pane/ActionsPane.svelte
+++ b/mathesar_ui/src/systems/table-view/actions-pane/ActionsPane.svelte
@@ -20,7 +20,7 @@
} from '@mathesar/icons';
import { getTabularDataStoreFromContext } from '@mathesar/stores/table-data';
import { States } from '@mathesar/utils/api';
- import { constructDataExplorerUrlToSummarizeFromGroup } from '@mathesar/systems/query-builder/urlSerializationUtils';
+ import { constructDataExplorerUrlToSummarizeFromGroup } from '@mathesar/systems/data-explorer';
import Filter from './record-operations/Filter.svelte';
import Sort from './record-operations/Sort.svelte';
import Group from './record-operations/Group.svelte';
diff --git a/mathesar_ui/src/systems/table-view/header/Header.svelte b/mathesar_ui/src/systems/table-view/header/Header.svelte
index 12e9e10e04..6c8383050a 100644
--- a/mathesar_ui/src/systems/table-view/header/Header.svelte
+++ b/mathesar_ui/src/systems/table-view/header/Header.svelte
@@ -30,6 +30,7 @@
<SheetCell
columnIdentifierKey={ID_ROW_CONTROL_COLUMN}
isStatic
+ isControlCell
let:htmlAttributes
let:style
>
diff --git a/mathesar_ui/src/systems/table-view/row/Row.svelte b/mathesar_ui/src/systems/table-view/row/Row.svelte
index e96115d82f..83b96db7ca 100644
--- a/mathesar_ui/src/systems/table-view/row/Row.svelte
+++ b/mathesar_ui/src/systems/table-view/row/Row.svelte
@@ -84,15 +84,11 @@
<SheetCell
columnIdentifierKey={ID_ROW_CONTROL_COLUMN}
isStatic
+ isControlCell
let:htmlAttributes
let:style
>
- <div
- class="row-control"
- {...htmlAttributes}
- {style}
- on:click={handleRowClick}
- >
+ <div {...htmlAttributes} {style} on:click={handleRowClick}>
{#if row.record}
<RowControl
{primaryKeyColumnId}
@@ -147,15 +143,6 @@
display: none;
}
- .row-control {
- font-size: var(--text-size-x-small);
- padding: 0 1.5rem;
- color: var(--color-text-muted);
- display: inline-flex;
- align-items: center;
- height: 100%;
- }
-
&.is-add-placeholder {
cursor: pointer;
diff --git a/mathesar_ui/src/utils/preloadData.ts b/mathesar_ui/src/utils/preloadData.ts
index 63bd1d8518..9e7aff8dff 100644
--- a/mathesar_ui/src/utils/preloadData.ts
+++ b/mathesar_ui/src/utils/preloadData.ts
@@ -4,7 +4,7 @@ import type {
AbstractTypeResponse,
} from '@mathesar/AppTypes';
import type { TableEntry } from '@mathesar/api/tables';
-import type { QueryInstance } from '@mathesar/api/queries/queryList';
+import type { QueryInstance } from '@mathesar/api/queries';
interface CommonData {
databases: Database[];
|
aws-powertools__powertools-lambda-python-984 | Logger: log_event does not serialize classes
**What were you trying to accomplish?**
I was trying to log the received S3 event. Please note that i am using the data classes present in this library for reading the event
```python
@event_source(data_class=S3Event)
@log.inject_lambda_context(
log_event=True
)
def lambda_handler(event: S3Event, context: LambdaContext):
```
## Expected Behavior
The logged event should have all the information from the S3 event
## Current Behavior
This is the output i get in the log (trimmed)
```json
{
"level": "INFO",
"message": "<aws_lambda_powertools.utilities.data_classes.s3_event.S3Event object at 0x7f0be7efb2b0>",
"timestamp": "2022-01-11 06:36:20,111+0000",
}
```
It looks to be that it was unable to properly represent the S3Event object as a string
## Possible Solution
Implement __repr__ and __str__ methods in S3Event class or in the parent DictWrapper class
## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1. Implement a lambda which receives and S3 event like the following
```python
@event_source(data_class=S3Event)
@log.inject_lambda_context(
log_event=True
)
def lambda_handler(event: S3Event, context: LambdaContext):
pass
```
2. Setup the lambda trigger as S3 object creation event
3. Upload a file in the S3 bucket where trigger is setup
4. See the logs in cloud watch
## Environment
* **Powertools version used**: 1.24.0
* **Packaging format (Layers, PyPi)**: PyPi
* **AWS Lambda function runtime:** 3.9
* **Debugging logs**
> [How to enable debug mode](https://awslabs.github.io/aws-lambda-powertools-python/#debug-mode)**
```python
# paste logs here
```
| [
{
"content": "import functools\nimport inspect\nimport logging\nimport os\nimport random\nimport sys\nfrom typing import IO, Any, Callable, Dict, Iterable, Optional, TypeVar, Union\n\nimport jmespath\n\nfrom ..shared import constants\nfrom ..shared.functions import resolve_env_var_choice, resolve_truthy_env_var... | [
{
"content": "import functools\nimport inspect\nimport logging\nimport os\nimport random\nimport sys\nfrom typing import IO, Any, Callable, Dict, Iterable, Optional, TypeVar, Union\n\nimport jmespath\n\nfrom ..shared import constants\nfrom ..shared.functions import resolve_env_var_choice, resolve_truthy_env_var... | diff --git a/aws_lambda_powertools/logging/logger.py b/aws_lambda_powertools/logging/logger.py
index 938742fb0a3..49321181b48 100644
--- a/aws_lambda_powertools/logging/logger.py
+++ b/aws_lambda_powertools/logging/logger.py
@@ -349,7 +349,7 @@ def decorate(event, context, **kwargs):
if log_event:
logger.debug("Event received")
- self.info(event)
+ self.info(getattr(event, "raw_event", event))
return lambda_handler(event, context)
diff --git a/tests/functional/test_logger.py b/tests/functional/test_logger.py
index 6b05119b88b..20b0a74fc64 100644
--- a/tests/functional/test_logger.py
+++ b/tests/functional/test_logger.py
@@ -17,6 +17,7 @@
from aws_lambda_powertools.logging.formatter import BasePowertoolsFormatter
from aws_lambda_powertools.logging.logger import set_package_logger
from aws_lambda_powertools.shared import constants
+from aws_lambda_powertools.utilities.data_classes import S3Event, event_source
@pytest.fixture
@@ -635,3 +636,21 @@ def test_use_datetime(stdout, service_name, utc):
assert re.fullmatch(
f"custom timestamp: milliseconds=[0-9]+ microseconds=[0-9]+ timezone={re.escape(expected_tz)}", log["timestamp"]
)
+
+
+def test_inject_lambda_context_log_event_request_data_classes(lambda_context, stdout, lambda_event, service_name):
+ # GIVEN Logger is initialized
+ logger = Logger(service=service_name, stream=stdout)
+
+ # WHEN a lambda function is decorated with logger instructed to log event
+ # AND the event is an event source data class
+ @event_source(data_class=S3Event)
+ @logger.inject_lambda_context(log_event=True)
+ def handler(event, context):
+ logger.info("Hello")
+
+ handler(lambda_event, lambda_context)
+
+ # THEN logger should log event received from Lambda
+ logged_event, _ = capture_multiple_logging_statements_output(stdout)
+ assert logged_event["message"] == lambda_event
|
googleapis__google-auth-library-python-671 | Use extra for asyncio dependencies
Hello! The latest release for this library pulls in aiohttp and its dependencies unconditionally, which adds non-trivial burden to projects that don’t need it. Would you consider using a packaging extra so that people can opt-in?
TODO: undo pin of 'aiohttp' once 'aioresponses' releases a fix
Environment details
- OS: $ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G6020
- Python version: 3.6, 3.7, 3.8
- pip version: pip 20.2.4
- `google-auth` version: 5906c8583ca351b5385a079a30521a9a8a0c7c59
#### Steps to reproduce
1. nox -s unit
There are 9 tests that fail, all with the same error:
`TypeError: __init__() missing 1 required positional argument: 'limit'`
```
====================================================== short test summary info =======================================================
FAILED tests_async/transport/test_aiohttp_requests.py::TestCombinedResponse::test_content_compressed - TypeError: __init__() missin...
FAILED tests_async/transport/test_aiohttp_requests.py::TestResponse::test_headers_prop - TypeError: __init__() missing 1 required p...
FAILED tests_async/transport/test_aiohttp_requests.py::TestResponse::test_status_prop - TypeError: __init__() missing 1 required po...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_request - TypeError: __init__() missing 1 requir...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_ctx - TypeError: __init__() missing 1 required p...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_http_headers - TypeError: __init__() missing 1 r...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_regexp_example - TypeError: __init__() missing 1...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_request_no_refresh - TypeError: __init__() missi...
FAILED tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_request_refresh - TypeError: __init__() missing ...
============================================ 9 failed, 609 passed, 12 warnings in 33.41s =============================================
```
Here is the traceback for one of the failing tests:
```
____________________________________________ TestCombinedResponse.test_content_compressed ____________________________________________
self = <tests_async.transport.test_aiohttp_requests.TestCombinedResponse object at 0x108803160>
urllib3_mock = <function decompress at 0x10880a820>
@mock.patch(
"google.auth.transport._aiohttp_requests.urllib3.response.MultiDecoder.decompress",
return_value="decompressed",
autospec=True,
)
@pytest.mark.asyncio
async def test_content_compressed(self, urllib3_mock):
rm = core.RequestMatch(
"url", headers={"Content-Encoding": "gzip"}, payload="compressed"
)
> response = await rm.build_response(core.URL("url"))
tests_async/transport/test_aiohttp_requests.py:72:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../../.virtualenv/google-auth-library-python/lib/python3.8/site-packages/aioresponses/core.py:192: in build_response
resp = self._build_response(
../../../.virtualenv/google-auth-library-python/lib/python3.8/site-packages/aioresponses/core.py:173: in _build_response
resp.content = stream_reader_factory(loop)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
loop = <Mock id='4437587472'>
def stream_reader_factory( # noqa
loop: 'Optional[asyncio.AbstractEventLoop]' = None
):
protocol = ResponseHandler(loop=loop)
> return StreamReader(protocol, loop=loop)
E TypeError: __init__() missing 1 required positional argument: 'limit'
../../../.virtualenv/google-auth-library-python/lib/python3.8/site-packages/aioresponses/compat.py:48: TypeError
========================================================== warnings summary ==========================================================
```
The root cause is a change in aiohttp version 3.7.0 which was released a few hours ago. The signature for StreamReader has changed, making the optional argument `limit` a required argument.
https://github.com/aio-libs/aiohttp/blob/56e78836aa7c67292ace9e256711699d51d57285/aiohttp/streams.py#L106
This change breaks aioresponses:
https://github.com/pnuckowski/aioresponses/blob/e61977f42a0164e0c572031dfb18ae95ba198df0/aioresponses/compat.py#L44
Add support for Python 3.9
| [
{
"content": "import synthtool as s\nfrom synthtool import gcp\n\ncommon = gcp.CommonTemplates()\n\n# ----------------------------------------------------------------------------\n# Add templated files\n# ----------------------------------------------------------------------------\ntemplated_files = common.py_l... | [
{
"content": "import synthtool as s\nfrom synthtool import gcp\n\ncommon = gcp.CommonTemplates()\n\n# ----------------------------------------------------------------------------\n# Add templated files\n# ----------------------------------------------------------------------------\ntemplated_files = common.py_l... | diff --git a/.gitignore b/.gitignore
index f01e60ec0..1f0b7e3c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,6 +30,7 @@ scripts/local_test_setup
tests/data/key.json
tests/data/key.p12
tests/data/user-key.json
+system_tests/data/
# PyCharm configuration:
.idea
diff --git a/.kokoro/build.sh b/.kokoro/build.sh
index 3a63e98c6..1f96e21d7 100755
--- a/.kokoro/build.sh
+++ b/.kokoro/build.sh
@@ -15,7 +15,11 @@
set -eo pipefail
-cd github/google-auth-library-python
+if [[ -z "${PROJECT_ROOT:-}" ]]; then
+ PROJECT_ROOT="github/google-auth-library-python"
+fi
+
+cd "${PROJECT_ROOT}"
# Disable buffering, so that the logs stream through.
export PYTHONUNBUFFERED=1
@@ -27,19 +31,33 @@ env | grep KOKORO
export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json
# Setup project id.
-export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.json")
+export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.txt")
+
+# Activate gcloud with service account credentials
+gcloud auth activate-service-account --key-file=$GOOGLE_APPLICATION_CREDENTIALS
+gcloud config set project ${PROJECT_ID}
+
+# Decrypt system test secrets
+./scripts/decrypt-secrets.sh
# Remove old nox
-python3.6 -m pip uninstall --yes --quiet nox-automation
+python3 -m pip uninstall --yes --quiet nox-automation
# Install nox
-python3.6 -m pip install --upgrade --quiet nox
-python3.6 -m nox --version
+python3 -m pip install --upgrade --quiet nox
+python3 -m nox --version
# If NOX_SESSION is set, it only runs the specified session,
# otherwise run all the sessions.
if [[ -n "${NOX_SESSION:-}" ]]; then
- python3.6 -m nox -s "${NOX_SESSION:-}"
+ python3 -m nox -s ${NOX_SESSION:-}
else
- python3.6 -m nox
+ python3 -m nox
fi
+
+
+# Decrypt system test secrets
+./scripts/decrypt-secrets.sh
+
+# Run system tests which use a different noxfile
+python3 -m nox -f system_tests/noxfile.py
\ No newline at end of file
diff --git a/.kokoro/continuous/common.cfg b/.kokoro/continuous/common.cfg
index c587b4104..10910e357 100644
--- a/.kokoro/continuous/common.cfg
+++ b/.kokoro/continuous/common.cfg
@@ -11,7 +11,7 @@ action {
gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
# Download resources for system tests (service account key, etc.)
-gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-python"
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-auth-library-python"
# Use the trampoline script to run in docker.
build_file: "google-auth-library-python/.kokoro/trampoline.sh"
diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg
index 111810782..d0f5783d5 100644
--- a/.kokoro/docs/docs-presubmit.cfg
+++ b/.kokoro/docs/docs-presubmit.cfg
@@ -15,3 +15,14 @@ env_vars: {
key: "TRAMPOLINE_IMAGE_UPLOAD"
value: "false"
}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/google-auth-library-python/.kokoro/build.sh"
+}
+
+# Only run this nox session.
+env_vars: {
+ key: "NOX_SESSION"
+ value: "docs docfx"
+}
diff --git a/.kokoro/presubmit/common.cfg b/.kokoro/presubmit/common.cfg
index c587b4104..10910e357 100644
--- a/.kokoro/presubmit/common.cfg
+++ b/.kokoro/presubmit/common.cfg
@@ -11,7 +11,7 @@ action {
gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
# Download resources for system tests (service account key, etc.)
-gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-python"
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-auth-library-python"
# Use the trampoline script to run in docker.
build_file: "google-auth-library-python/.kokoro/trampoline.sh"
diff --git a/synth.metadata b/synth.metadata
index 5e1ef9a55..0de642bf7 100644
--- a/synth.metadata
+++ b/synth.metadata
@@ -4,14 +4,14 @@
"git": {
"name": ".",
"remote": "https://github.com/googleapis/google-auth-library-python.git",
- "sha": "9c4200dff31986b7ff300126e9aa35d14aa84dba"
+ "sha": "f062da8392c32fb3306cdc6e4dbae78212aa0dc7"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "da5c6050d13b4950c82666a81d8acd25157664ae"
+ "sha": "16ec872dd898d7de6e1822badfac32484b5d9031"
}
}
],
diff --git a/synth.py b/synth.py
index 49bf2dda6..f692f7010 100644
--- a/synth.py
+++ b/synth.py
@@ -10,8 +10,8 @@
s.move(
templated_files / ".kokoro",
excludes=[
- ".kokoro/continuous/common.cfg",
- ".kokoro/presubmit/common.cfg",
- ".kokoro/build.sh",
+ "continuous/common.cfg",
+ "presubmit/common.cfg",
+ "build.sh",
],
) # just move kokoro configs
diff --git a/system_tests/__init__.py b/system_tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/system_tests/noxfile.py b/system_tests/noxfile.py
index dcfe8ee81..5d0014bc8 100644
--- a/system_tests/noxfile.py
+++ b/system_tests/noxfile.py
@@ -30,7 +30,7 @@
import py.path
HERE = os.path.abspath(os.path.dirname(__file__))
-LIBRARY_DIR = os.path.join(HERE, "..")
+LIBRARY_DIR = os.path.abspath(os.path.dirname(HERE))
DATA_DIR = os.path.join(HERE, "data")
SERVICE_ACCOUNT_FILE = os.path.join(DATA_DIR, "service_account.json")
AUTHORIZED_USER_FILE = os.path.join(DATA_DIR, "authorized_user.json")
@@ -169,7 +169,7 @@ def configure_cloud_sdk(session, application_default_credentials, project=False)
# Test sesssions
TEST_DEPENDENCIES_ASYNC = ["aiohttp", "pytest-asyncio", "nest-asyncio"]
-TEST_DEPENDENCIES_SYNC = ["pytest", "requests"]
+TEST_DEPENDENCIES_SYNC = ["pytest", "requests", "mock"]
PYTHON_VERSIONS_ASYNC = ["3.7"]
PYTHON_VERSIONS_SYNC = ["2.7", "3.7"]
@@ -249,6 +249,7 @@ def app_engine(session):
session.log("Skipping App Engine tests.")
return
+ session.install(LIBRARY_DIR)
# Unlike the default tests above, the App Engine system test require a
# 'real' gcloud sdk installation that is configured to deploy to an
# app engine project.
@@ -269,9 +270,8 @@ def app_engine(session):
application_url = GAE_APP_URL_TMPL.format(GAE_TEST_APP_SERVICE, project_id)
# Vendor in the test application's dependencies
- session.chdir(os.path.join(HERE, "../app_engine_test_app"))
+ session.chdir(os.path.join(HERE, "system_tests_sync/app_engine_test_app"))
session.install(*TEST_DEPENDENCIES_SYNC)
- session.install(LIBRARY_DIR)
session.run(
"pip", "install", "--target", "lib", "-r", "requirements.txt", silent=True
)
@@ -288,7 +288,7 @@ def app_engine(session):
@nox.session(python=PYTHON_VERSIONS_SYNC)
def grpc(session):
session.install(LIBRARY_DIR)
- session.install(*TEST_DEPENDENCIES_SYNC, "google-cloud-pubsub==1.0.0")
+ session.install(*TEST_DEPENDENCIES_SYNC, "google-cloud-pubsub==1.7.0")
session.env[EXPLICIT_CREDENTIALS_ENV] = SERVICE_ACCOUNT_FILE
session.run("pytest", "system_tests_sync/test_grpc.py")
diff --git a/system_tests/secrets.tar.enc b/system_tests/secrets.tar.enc
new file mode 100644
index 000000000..29e06923f
Binary files /dev/null and b/system_tests/secrets.tar.enc differ
diff --git a/system_tests/system_tests_async/__init__.py b/system_tests/system_tests_async/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/system_tests/system_tests_async/conftest.py b/system_tests/system_tests_async/conftest.py
index ecff74c96..47a473e7f 100644
--- a/system_tests/system_tests_async/conftest.py
+++ b/system_tests/system_tests_async/conftest.py
@@ -71,7 +71,8 @@ async def _token_info(access_token=None, id_token=None):
url = _helpers.update_query(sync_conftest.TOKEN_INFO_URL, query_params)
response = await http_request(url=url, method="GET")
- data = await response.data.read()
+
+ data = await response.content()
return json.loads(data.decode("utf-8"))
diff --git a/system_tests/system_tests_async/test_default.py b/system_tests/system_tests_async/test_default.py
index 383cbff01..32299c059 100644
--- a/system_tests/system_tests_async/test_default.py
+++ b/system_tests/system_tests_async/test_default.py
@@ -15,14 +15,13 @@
import os
import pytest
-import google.auth
+from google.auth import _default_async
EXPECT_PROJECT_ID = os.environ.get("EXPECT_PROJECT_ID")
@pytest.mark.asyncio
async def test_application_default_credentials(verify_refresh):
- credentials, project_id = google.auth.default_async()
- #breakpoint()
+ credentials, project_id = _default_async.default_async()
if EXPECT_PROJECT_ID is not None:
assert project_id is not None
diff --git a/system_tests/system_tests_sync/app_engine_test_app/requirements.txt b/system_tests/system_tests_sync/app_engine_test_app/requirements.txt
index e390e141f..bd5c476ab 100644
--- a/system_tests/system_tests_sync/app_engine_test_app/requirements.txt
+++ b/system_tests/system_tests_sync/app_engine_test_app/requirements.txt
@@ -1,3 +1,3 @@
urllib3
# Relative path to google-auth-python's source.
-../..
+../../..
diff --git a/system_tests/system_tests_sync/secrets.tar.enc b/system_tests/system_tests_sync/secrets.tar.enc
index af10c7134..29e06923f 100644
Binary files a/system_tests/system_tests_sync/secrets.tar.enc and b/system_tests/system_tests_sync/secrets.tar.enc differ
diff --git a/system_tests/system_tests_sync/test_grpc.py b/system_tests/system_tests_sync/test_grpc.py
index 650fa96a4..7dcbd4c43 100644
--- a/system_tests/system_tests_sync/test_grpc.py
+++ b/system_tests/system_tests_sync/test_grpc.py
@@ -17,8 +17,6 @@
import google.auth.jwt
import google.auth.transport.grpc
from google.cloud import pubsub_v1
-from google.cloud.pubsub_v1.gapic import publisher_client
-from google.cloud.pubsub_v1.gapic.transports import publisher_grpc_transport
def test_grpc_request_with_regular_credentials(http_request):
@@ -27,13 +25,8 @@ def test_grpc_request_with_regular_credentials(http_request):
credentials, ["https://www.googleapis.com/auth/pubsub"]
)
- transport = publisher_grpc_transport.PublisherGrpcTransport(
- address=publisher_client.PublisherClient.SERVICE_ADDRESS,
- credentials=credentials,
- )
-
# Create a pub/sub client.
- client = pubsub_v1.PublisherClient(transport=transport)
+ client = pubsub_v1.PublisherClient(credentials=credentials)
# list the topics and drain the iterator to test that an authorized API
# call works.
@@ -48,13 +41,8 @@ def test_grpc_request_with_jwt_credentials():
credentials, audience=audience
)
- transport = publisher_grpc_transport.PublisherGrpcTransport(
- address=publisher_client.PublisherClient.SERVICE_ADDRESS,
- credentials=credentials,
- )
-
# Create a pub/sub client.
- client = pubsub_v1.PublisherClient(transport=transport)
+ client = pubsub_v1.PublisherClient(credentials=credentials)
# list the topics and drain the iterator to test that an authorized API
# call works.
@@ -68,13 +56,8 @@ def test_grpc_request_with_on_demand_jwt_credentials():
credentials
)
- transport = publisher_grpc_transport.PublisherGrpcTransport(
- address=publisher_client.PublisherClient.SERVICE_ADDRESS,
- credentials=credentials,
- )
-
# Create a pub/sub client.
- client = pubsub_v1.PublisherClient(transport=transport)
+ client = pubsub_v1.PublisherClient(credentials=credentials)
# list the topics and drain the iterator to test that an authorized API
# call works.
diff --git a/system_tests/system_tests_sync/test_mtls_http.py b/system_tests/system_tests_sync/test_mtls_http.py
index 7c5649685..bcf2a59da 100644
--- a/system_tests/system_tests_sync/test_mtls_http.py
+++ b/system_tests/system_tests_sync/test_mtls_http.py
@@ -13,8 +13,11 @@
# limitations under the License.
import json
-from os import path
+import mock
+import os
import time
+from os import path
+
import google.auth
import google.auth.credentials
|
pypa__cibuildwheel-977 | on windows, setup_py_python_requires attempts to open utf-8 setup.py as Windows-1252 and fails
### Description
This [setup.py file](https://github.com/fgregg/fastcluster/blob/master/setup.py) is valid utf-8, and has a few non-ascii characters. In a windows build, `setup_py_python_requires` appears to be opening this file as if it was encoded like Windows-1252 and thus fails on some non-ascii characters.
### Build log
https://github.com/fgregg/fastcluster/runs/4660766954?check_suite_focus=true#step:5:40
### CI config
https://github.com/fgregg/fastcluster/blob/master/.github/workflows/pythonpackage.yml#L41-L47
| [
{
"content": "import ast\nimport sys\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nimport tomli\n\nif sys.version_info < (3, 8):\n Constant = ast.Str\n\n def get_constant(x: ast.Str) -> str:\n return x.s\n\nelse:\n Constant = ast.Constant\n... | [
{
"content": "import ast\nimport sys\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nimport tomli\n\nif sys.version_info < (3, 8):\n Constant = ast.Str\n\n def get_constant(x: ast.Str) -> str:\n return x.s\n\nelse:\n Constant = ast.Constant\n... | diff --git a/cibuildwheel/projectfiles.py b/cibuildwheel/projectfiles.py
index c4f63c176..fece392f8 100644
--- a/cibuildwheel/projectfiles.py
+++ b/cibuildwheel/projectfiles.py
@@ -70,7 +70,7 @@ def get_requires_python_str(package_dir: Path) -> Optional[str]:
pass
try:
- with (package_dir / "setup.py").open() as f2:
+ with (package_dir / "setup.py").open(encoding="utf8") as f2:
return setup_py_python_requires(f2.read())
except FileNotFoundError:
pass
diff --git a/unit_test/projectfiles_test.py b/unit_test/projectfiles_test.py
index c62df6a9c..6c55d46a1 100644
--- a/unit_test/projectfiles_test.py
+++ b/unit_test/projectfiles_test.py
@@ -25,7 +25,7 @@ def test_read_setup_py_simple(tmp_path):
def test_read_setup_py_full(tmp_path):
- with open(tmp_path / "setup.py", "w") as f:
+ with open(tmp_path / "setup.py", "w", encoding="utf8") as f:
f.write(
dedent(
"""
@@ -35,6 +35,7 @@ def test_read_setup_py_full(tmp_path):
setuptools.setup(
name = "hello",
+ description = "≥“”ü",
other = 23,
example = ["item", "other"],
python_requires = "1.24",
@@ -43,7 +44,9 @@ def test_read_setup_py_full(tmp_path):
)
)
- assert setup_py_python_requires(tmp_path.joinpath("setup.py").read_text()) == "1.24"
+ assert (
+ setup_py_python_requires(tmp_path.joinpath("setup.py").read_text(encoding="utf8")) == "1.24"
+ )
assert get_requires_python_str(tmp_path) == "1.24"
|
Lightning-AI__pytorch-lightning-799 | Optional dependencies are required for deprecated logging module
🐛 Bug
There is a backwards compatibility issues coming from PR #767. Notably, if a user doesn't have any of the extra logging dependencies then they'll be an import error.
### To Reproduce
1. Remove all logging dependencies from your environment (E.g. comet)
2. Depend on the deprecated pytorch_lightning.logging package and run
### Expected behavior
We expect to maintain backwards compatibility here so optional dependencies shouldn't be required.
| [
{
"content": "\"\"\"\n.. warning:: `logging` package has been renamed to `loggers` since v0.6.1 and will be removed in v0.8.0\n\"\"\"\n\nimport warnings\n\nwarnings.warn(\"`logging` package has been renamed to `loggers` since v0.6.1\"\n \" and will be removed in v0.8.0\", DeprecationWarning)\n\nfro... | [
{
"content": "\"\"\"\n.. warning:: `logging` package has been renamed to `loggers` since v0.6.1 and will be removed in v0.8.0\n\"\"\"\n\nimport warnings\n\nwarnings.warn(\"`logging` package has been renamed to `loggers` since v0.6.1\"\n \" and will be removed in v0.8.0\", DeprecationWarning)\n\nfro... | diff --git a/pytorch_lightning/logging/__init__.py b/pytorch_lightning/logging/__init__.py
index 93515eb1eff31..ecd4c3b01e9f4 100644
--- a/pytorch_lightning/logging/__init__.py
+++ b/pytorch_lightning/logging/__init__.py
@@ -8,6 +8,3 @@
" and will be removed in v0.8.0", DeprecationWarning)
from pytorch_lightning.loggers import * # noqa: F403
-from pytorch_lightning.loggers import ( # noqa: E402
- base, comet, mlflow, neptune, tensorboard, test_tube, wandb
-)
|
pymeasure__pymeasure-852 | How to include Channels in API documentation
In #819 I encountered the question, how to include the Channel best into the documentation.
It does not seem right, to put the channel in the same level as the instruments of that manufacturer.
Any ideas?
| [
{
"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2023 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restr... | [
{
"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2023 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restr... | diff --git a/docs/dev/adding_instruments/channels.rst b/docs/dev/adding_instruments/channels.rst
index dda8dea9d8..55873e202c 100644
--- a/docs/dev/adding_instruments/channels.rst
+++ b/docs/dev/adding_instruments/channels.rst
@@ -25,6 +25,17 @@ All the channel communication is routed through the instrument's methods (`write
However, :meth:`Channel.insert_id <pymeasure.instruments.Channel.insert_id>` uses `str.format` to insert the channel's id at any occurence of the class attribute :attr:`Channel.placeholder`, which defaults to :code:`"ch"`, in the written commands.
For example :code:`"Ch{ch}:VOLT?"` will be sent as :code:`"Ch3:VOLT?"` to the device, if the channel's id is "3".
+Please add the channel to the documentation. In the instrument's documentation file, you may add
+
+.. code::
+
+ .. autoclass:: pymeasure.instruments.MANUFACTURER.INSTRUMENT.CHANNEL
+ :members:
+ :show-inheritance:
+
+`MANUFACTURER` is the folder name of the manufacturer and `INSTRUMENT` the file name of the instrument definition, which contains the `CHANNEL` class.
+You may link in the instrument's docstring to the channel with :code:`:class:\`CHANNEL\``
+
In order to add a channel to an instrument or to another channel (nesting channels is possible), create the channels with the class :class:`~pymeasure.instruments.common_base.CommonBase.ChannelCreator` as class attributes.
Its constructor accepts a single channel class or list of classes and a list of corresponding ids.
Instead of lists, you may also use tuples.
diff --git a/pymeasure/instruments/siglenttechnologies/siglent_spdbase.py b/pymeasure/instruments/siglenttechnologies/siglent_spdbase.py
index a596ecd0c1..9e7808d061 100644
--- a/pymeasure/instruments/siglenttechnologies/siglent_spdbase.py
+++ b/pymeasure/instruments/siglenttechnologies/siglent_spdbase.py
@@ -157,6 +157,8 @@ def configure_timer(self, step, voltage, current, duration):
class SPDBase(Instrument):
""" The base class for Siglent SPDxxxxX instruments.
+
+ Uses :class:`SPDChannel` for measurement channels.
"""
def __init__(self, adapter, **kwargs):
|
voxel51__fiftyone-1179 | [BUG] Cannot open desktop App with fiftyone==0.12.0 source install
On a source install of `fiftyone==0.12.0`, the desktop App cannot be opened:
```shell
fiftyone app launch --desktop
```
```
Usage Error: Couldn't find a script named "start-app"
```
The `start-app` script in the last release was
https://github.com/voxel51/fiftyone/blob/d383bfb0fd88a04a3352f06ddaa48599d0e8ce2a/app/package.json#L11)
I tried updating
https://github.com/voxel51/fiftyone/blob/da5d83a3e5b1578ba162f2453f26a1139991d370/fiftyone/core/service.py#L456
to both `yarn dev` and `yarn start` per the now-available scripts
https://github.com/voxel51/fiftyone/blob/da5d83a3e5b1578ba162f2453f26a1139991d370/app/package.json#L9-L10
but neither caused the App window to appear for me (but no error either, just hung).
| [
{
"content": "\"\"\"\nFiftyOne Services.\n\n| Copyright 2017-2021, Voxel51, Inc.\n| `voxel51.com <https://voxel51.com/>`_\n|\n\"\"\"\nimport logging\nimport multiprocessing\nimport os\nimport re\nimport subprocess\nimport sys\n\nfrom packaging.version import Version\nimport psutil\nimport requests\nfrom retryin... | [
{
"content": "\"\"\"\nFiftyOne Services.\n\n| Copyright 2017-2021, Voxel51, Inc.\n| `voxel51.com <https://voxel51.com/>`_\n|\n\"\"\"\nimport logging\nimport multiprocessing\nimport os\nimport re\nimport subprocess\nimport sys\n\nfrom packaging.version import Version\nimport psutil\nimport requests\nfrom retryin... | diff --git a/app/package.json b/app/package.json
index b9960a8bdaf..4e209df7539 100644
--- a/app/package.json
+++ b/app/package.json
@@ -6,10 +6,11 @@
"private": true,
"main": "index.js",
"scripts": {
+ "build": "yarn workspace @fiftyone/app build",
"dev": "yarn workspace @fiftyone/app dev",
+ "postinstall": "patch-package",
"start": "yarn workspace @fiftyone/app start",
- "build": "yarn workspace @fiftyone/app build",
- "postinstall": "patch-package"
+ "start-desktop": "yarn workspace FiftyOne start-desktop"
},
"devDependencies": {
"patch-package": "^6.4.7",
diff --git a/app/packages/desktop/package.json b/app/packages/desktop/package.json
index 5d8934b0fce..22ce28e1396 100644
--- a/app/packages/desktop/package.json
+++ b/app/packages/desktop/package.json
@@ -8,13 +8,14 @@
"private": true,
"prettier": "@fiftyone/prettier-config",
"scripts": {
- "build-desktop": "yarn build-desktop-source && yarn pull-desktop-source && tsc -p tsconfig.json",
- "build-desktop-source": "yarn workspace @fiftyone/app build-bare",
- "pull-desktop-source": "yarn workspace @fiftyone/app copy-to-desktop",
- "start-desktop": "cross-env DEBUG_APP=true electron ./dist/main.js",
- "package-mac": "yarn build-desktop && electron-builder build --mac",
- "package-linux": "yarn build-desktop && electron-builder build --linux",
- "package-win": "yarn build-desktop && electron-builder build --win --x64"
+ "build": "yarn build-source && yarn build-desktop",
+ "build-desktop": "yarn pull-source && tsc -p tsconfig.json",
+ "build-source": "yarn workspace @fiftyone/app build-bare",
+ "pull-source": "yarn workspace @fiftyone/app copy-to-desktop",
+ "start-desktop": "yarn build-desktop && cross-env DEBUG_APP=true electron ./dist/main.js",
+ "package-mac": "yarn build && electron-builder build --mac",
+ "package-linux": "yarn build && electron-builder build --linux",
+ "package-win": "yarn build && electron-builder build --win --x64"
},
"build": {
"productName": "FiftyOne",
diff --git a/fiftyone/core/service.py b/fiftyone/core/service.py
index 2e79b1651b1..4a2a16862e7 100644
--- a/fiftyone/core/service.py
+++ b/fiftyone/core/service.py
@@ -453,7 +453,7 @@ def command(self):
def find_app(self):
if foc.DEV_INSTALL:
- return ["yarn", "start-app"]
+ return ["yarn", "start-desktop"]
for path in etau.list_files("./"):
if path.endswith(".tar.gz"):
|
apache__tvm-12178 | Exercise TVM under minimal configuration in CI
We have seen a couple bugs due to microTVM being presumed-ON in config.cmake. Namely, you get python errors importing TVM right now when USE_MICRO is OFF. We should have a regression test that verifies basic functionality with everything (or nearly everything) OFF.
Context: apache/tvm#9617
And another micro-related issue of the same kind, which i don't have handy right now.
cc @gigiblender
| [
{
"content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache Lic... | [
{
"content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache Lic... | diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8dc03ee0f40e..a6be494a3a53 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -794,3 +794,5 @@ find_and_set_linker(${USE_ALTERNATIVE_LINKER})
if(${SUMMARIZE})
print_summary()
endif()
+
+dump_options_to_file("${TVM_ALL_OPTIONS}")
diff --git a/Jenkinsfile b/Jenkinsfile
index a2fe67d4b5f3..0114bf755cb7 100755
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -52,6 +52,7 @@ import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
ci_lint = 'tlcpack/ci-lint:20220715-060127-37f9d3c49'
ci_gpu = 'tlcpack/ci-gpu:20220801-060139-d332eb374'
ci_cpu = 'tlcpack/ci-cpu:20220715-060127-37f9d3c49'
+ci_minimal = 'tlcpack/ci-minimal:20220725-133226-d3cefdaf1'
ci_wasm = 'tlcpack/ci-wasm:20220715-060127-37f9d3c49'
ci_i386 = 'tlcpack/ci-i386:20220715-060127-37f9d3c49'
ci_cortexm = 'tlcpack/ci-cortexm:v0.01'
@@ -66,6 +67,7 @@ properties([
parameters([
string(name: 'ci_arm_param', defaultValue: ''),
string(name: 'ci_cpu_param', defaultValue: ''),
+ string(name: 'ci_minimal_param', defaultValue: ''),
string(name: 'ci_gpu_param', defaultValue: ''),
string(name: 'ci_hexagon_param', defaultValue: ''),
string(name: 'ci_i386_param', defaultValue: ''),
@@ -79,6 +81,7 @@ properties([
// is used)
built_ci_arm = null;
built_ci_cpu = null;
+ built_ci_minimal = null;
built_ci_gpu = null;
built_ci_hexagon = null;
built_ci_i386 = null;
@@ -273,7 +276,7 @@ def prepare() {
if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
sh(
- script: "./tests/scripts/determine_docker_images.py ci_arm=${ci_arm} ci_cpu=${ci_cpu} ci_gpu=${ci_gpu} ci_hexagon=${ci_hexagon} ci_i386=${ci_i386} ci_lint=${ci_lint} ci_cortexm=${ci_cortexm} ci_wasm=${ci_wasm} ",
+ script: "./tests/scripts/determine_docker_images.py ci_arm=${ci_arm} ci_cpu=${ci_cpu} ci_minimal=${ci_minimal} ci_gpu=${ci_gpu} ci_hexagon=${ci_hexagon} ci_i386=${ci_i386} ci_lint=${ci_lint} ci_cortexm=${ci_cortexm} ci_wasm=${ci_wasm} ",
label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
)
// Pull image names from the results of should_rebuild_docker.py
@@ -287,6 +290,11 @@ def prepare() {
label: "Find docker image name for ci_cpu",
returnStdout: true,
).trim()
+ ci_minimal = sh(
+ script: "cat .docker-image-names/ci_minimal",
+ label: "Find docker image name for ci_minimal",
+ returnStdout: true,
+ ).trim()
ci_gpu = sh(
script: "cat .docker-image-names/ci_gpu",
label: "Find docker image name for ci_gpu",
@@ -321,6 +329,7 @@ def prepare() {
ci_arm = params.ci_arm_param ?: ci_arm
ci_cpu = params.ci_cpu_param ?: ci_cpu
+ ci_minimal = params.ci_minimal_param ?: ci_minimal
ci_gpu = params.ci_gpu_param ?: ci_gpu
ci_hexagon = params.ci_hexagon_param ?: ci_hexagon
ci_i386 = params.ci_i386_param ?: ci_i386
@@ -332,6 +341,7 @@ def prepare() {
echo "Docker images being used in this build:"
echo " ci_arm = ${ci_arm}"
echo " ci_cpu = ${ci_cpu}"
+ echo " ci_minimal = ${ci_minimal}"
echo " ci_gpu = ${ci_gpu}"
echo " ci_hexagon = ${ci_hexagon}"
echo " ci_i386 = ${ci_i386}"
@@ -483,6 +493,17 @@ def build_docker_images() {
}
}
},
+ 'ci_minimal': {
+ node('CPU') {
+ timeout(time: max_time, unit: 'MINUTES') {
+ init_git()
+ // We're purposefully not setting the built image here since they
+ // are not yet being uploaded to tlcpack
+ // ci_minimal = build_image('ci_minimal')
+ built_ci_minimal = build_image('ci_minimal');
+ }
+ }
+ },
'ci_gpu': {
node('CPU') {
timeout(time: max_time, unit: 'MINUTES') {
@@ -629,7 +650,6 @@ def cpp_unittest(image) {
)
}
-
def add_microtvm_permissions() {
sh(
script: 'find build/microtvm_template_projects -type f | grep qemu-hack | xargs chmod +x',
@@ -820,6 +840,56 @@ stage('Build') {
Utils.markStageSkippedForConditional('BUILD: CPU')
}
},
+ 'BUILD: CPU MINIMAL': {
+ if (!skip_ci && is_docs_only_build != 1) {
+ node('CPU-SMALL') {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/build-cpu-minimal") {
+ docker_init(ci_minimal)
+ init_git()
+ sh (
+ script: "${docker_run} ${ci_minimal} ./tests/scripts/task_config_build_minimal.sh build",
+ label: 'Create CPU minimal cmake config',
+ )
+ make(ci_minimal, 'build', '-j2')
+ sh(
+ script: """
+ set -eux
+ retry() {
+ local retries=\$1
+ shift
+
+ local count=0
+ until "\$@"; do
+ exit=\$?
+ wait=\$((2 ** \$count))
+ count=\$((\$count + 1))
+ if [ \$count -lt \$retries ]; then
+ echo "Retry \$count/\$retries exited \$exit, retrying in \$wait seconds..."
+ sleep \$wait
+ else
+ echo "Retry \$count/\$retries exited \$exit, no more retries left."
+ return \$exit
+ fi
+ done
+ return 0
+ }
+
+ md5sum build/libtvm.so
+ retry 3 aws s3 cp --no-progress build/libtvm.so s3://${s3_prefix}/cpu-minimal/build/libtvm.so
+ md5sum build/libtvm_runtime.so
+ retry 3 aws s3 cp --no-progress build/libtvm_runtime.so s3://${s3_prefix}/cpu-minimal/build/libtvm_runtime.so
+ md5sum build/config.cmake
+ retry 3 aws s3 cp --no-progress build/config.cmake s3://${s3_prefix}/cpu-minimal/build/config.cmake
+ """,
+ label: 'Upload artifacts to S3',
+ )
+
+ }
+ }
+ } else {
+ Utils.markStageSkippedForConditional('BUILD: CPU MINIMAL')
+ }
+ },
'BUILD: WASM': {
if (!skip_ci && is_docs_only_build != 1) {
node('CPU-SMALL') {
@@ -4848,6 +4918,69 @@ def shard_run_test_Cortex_M_8_of_8() {
}
+def run_unittest_minimal() {
+ if (!skip_ci && is_docs_only_build != 1) {
+ node('CPU-SMALL') {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/ut-python-cpu-minimal") {
+ timeout(time: max_time, unit: 'MINUTES') {
+ try {
+ docker_init(ci_minimal)
+ init_git()
+ withEnv(['PLATFORM=minimal'], {
+ sh(
+ script: """
+ set -eux
+ retry() {
+ local retries=\$1
+ shift
+
+ local count=0
+ until "\$@"; do
+ exit=\$?
+ wait=\$((2 ** \$count))
+ count=\$((\$count + 1))
+ if [ \$count -lt \$retries ]; then
+ echo "Retry \$count/\$retries exited \$exit, retrying in \$wait seconds..."
+ sleep \$wait
+ else
+ echo "Retry \$count/\$retries exited \$exit, no more retries left."
+ return \$exit
+ fi
+ done
+ return 0
+ }
+
+ retry 3 aws s3 cp --no-progress s3://${s3_prefix}/cpu-minimal/build/libtvm.so build/libtvm.so
+ md5sum build/libtvm.so
+ retry 3 aws s3 cp --no-progress s3://${s3_prefix}/cpu-minimal/build/libtvm_runtime.so build/libtvm_runtime.so
+ md5sum build/libtvm_runtime.so
+ retry 3 aws s3 cp --no-progress s3://${s3_prefix}/cpu-minimal/build/config.cmake build/config.cmake
+ md5sum build/config.cmake
+ """,
+ label: 'Download artifacts from S3',
+ )
+
+ cpp_unittest(ci_minimal)
+ python_unittest(ci_minimal)
+ })
+ } finally {
+ sh(
+ script: """
+ set -eux
+ aws s3 cp --no-progress build/pytest-results s3://${s3_prefix}/pytest-results/unittest_CPU_MINIMAL --recursive
+ """,
+ label: 'Upload JUnits to S3',
+ )
+
+ junit 'build/pytest-results/*.xml'
+ }
+ }
+ }
+ }
+ } else {
+ Utils.markStageSkippedForConditional('unittest: CPU MINIMAL')
+ }
+}
def test() {
stage('Test') {
@@ -5008,6 +5141,9 @@ stage('Test') {
'test: Cortex-M 8 of 8': {
shard_run_test_Cortex_M_8_of_8()
},
+ 'unittest: CPU MINIMAL': {
+ run_unittest_minimal()
+ },
'unittest: CPU': {
if (!skip_ci && is_docs_only_build != 1) {
node('CPU-SMALL') {
@@ -5379,6 +5515,7 @@ def deploy() {
def tag = "${date_Ymd_HMS}-${upstream_revision.substring(0, 8)}"
update_docker(built_ci_arm, "tlcpackstaging/ci_arm:${tag}")
update_docker(built_ci_cpu, "tlcpackstaging/ci_cpu:${tag}")
+ update_docker(built_ci_minimal, "tlcpackstaging/ci_minimal:${tag}")
update_docker(built_ci_gpu, "tlcpackstaging/ci_gpu:${tag}")
update_docker(built_ci_hexagon, "tlcpackstaging/ci_hexagon:${tag}")
update_docker(built_ci_i386, "tlcpackstaging/ci_i386:${tag}")
diff --git a/ci/jenkins/Build.groovy.j2 b/ci/jenkins/Build.groovy.j2
index a4316a268e9a..21b8b2c65f8b 100644
--- a/ci/jenkins/Build.groovy.j2
+++ b/ci/jenkins/Build.groovy.j2
@@ -33,7 +33,6 @@ def cpp_unittest(image) {
)
}
-
def add_microtvm_permissions() {
{% for folder in microtvm_template_projects %}
sh(
@@ -123,6 +122,24 @@ stage('Build') {
Utils.markStageSkippedForConditional('BUILD: CPU')
}
},
+ 'BUILD: CPU MINIMAL': {
+ if (!skip_ci && is_docs_only_build != 1) {
+ node('CPU-SMALL') {
+ ws({{ m.per_exec_ws('tvm/build-cpu-minimal') }}) {
+ docker_init(ci_minimal)
+ init_git()
+ sh (
+ script: "${docker_run} ${ci_minimal} ./tests/scripts/task_config_build_minimal.sh build",
+ label: 'Create CPU minimal cmake config',
+ )
+ make(ci_minimal, 'build', '-j2')
+ {{ m.upload_artifacts(tag='cpu-minimal', filenames=tvm_lib) }}
+ }
+ }
+ } else {
+ Utils.markStageSkippedForConditional('BUILD: CPU MINIMAL')
+ }
+ },
'BUILD: WASM': {
if (!skip_ci && is_docs_only_build != 1) {
node('CPU-SMALL') {
diff --git a/ci/jenkins/Jenkinsfile.j2 b/ci/jenkins/Jenkinsfile.j2
index 63131ff7ffc2..f91cf88a40b3 100644
--- a/ci/jenkins/Jenkinsfile.j2
+++ b/ci/jenkins/Jenkinsfile.j2
@@ -54,6 +54,7 @@ import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
ci_lint = 'tlcpack/ci-lint:20220715-060127-37f9d3c49'
ci_gpu = 'tlcpack/ci-gpu:20220801-060139-d332eb374'
ci_cpu = 'tlcpack/ci-cpu:20220715-060127-37f9d3c49'
+ci_minimal = 'tlcpack/ci-minimal:20220725-133226-d3cefdaf1'
ci_wasm = 'tlcpack/ci-wasm:20220715-060127-37f9d3c49'
ci_i386 = 'tlcpack/ci-i386:20220715-060127-37f9d3c49'
ci_cortexm = 'tlcpack/ci-cortexm:v0.01'
diff --git a/ci/jenkins/Test.groovy.j2 b/ci/jenkins/Test.groovy.j2
index b2afdacad7d1..09550a469701 100644
--- a/ci/jenkins/Test.groovy.j2
+++ b/ci/jenkins/Test.groovy.j2
@@ -211,6 +211,19 @@
)
{% endcall %}
+def run_unittest_minimal() {
+ {% call m.test_step_body(
+ name="unittest: CPU MINIMAL",
+ node="CPU-SMALL",
+ ws="tvm/ut-python-cpu-minimal",
+ platform="minimal",
+ docker_image="ci_minimal",
+ ) %}
+ {{ m.download_artifacts(tag='cpu-minimal', filenames=tvm_lib) }}
+ cpp_unittest(ci_minimal)
+ python_unittest(ci_minimal)
+ {% endcall %}
+}
def test() {
stage('Test') {
@@ -223,6 +236,9 @@ stage('Test') {
{{ method_name }}()
},
{% endfor %}
+ 'unittest: CPU MINIMAL': {
+ run_unittest_minimal()
+ },
{% call m.test_step(
name="unittest: CPU",
node="CPU-SMALL",
diff --git a/ci/jenkins/generate.py b/ci/jenkins/generate.py
index 82bf4e5aaa1f..3d0198ba6fd9 100644
--- a/ci/jenkins/generate.py
+++ b/ci/jenkins/generate.py
@@ -40,6 +40,10 @@
"name": "ci_cpu",
"platform": "CPU",
},
+ {
+ "name": "ci_minimal",
+ "platform": "CPU",
+ },
{
"name": "ci_gpu",
"platform": "CPU",
diff --git a/ci/jenkins/macros.j2 b/ci/jenkins/macros.j2
index 99b7dc1bcd90..082446cb11b6 100644
--- a/ci/jenkins/macros.j2
+++ b/ci/jenkins/macros.j2
@@ -84,6 +84,29 @@ def {{ method_name }}() {
{% endfor %}
{% endmacro %}
+{% macro test_step_body(name, node, ws, docker_image, platform) %}
+{% set test_dir_name = name.replace(":", "").replace(" ", "-").replace("-", "_")|string %}
+ if (!skip_ci && is_docs_only_build != 1) {
+ node('{{ node }}') {
+ ws({{ per_exec_ws(ws) }}) {
+ timeout(time: max_time, unit: 'MINUTES') {
+ try {
+ docker_init({{ docker_image }})
+ init_git()
+ withEnv(['PLATFORM={{ platform }}'], {
+ {{ caller() | indent(width=8) | trim }}
+ })
+ } finally {
+ {{ junit_to_s3(test_dir_name) | indent(width=0) }}
+ junit 'build/pytest-results/*.xml'
+ }
+ }
+ }
+ }
+ } else {
+ Utils.markStageSkippedForConditional('{{ name }}')
+ }
+{% endmacro %}
{% macro test_step(name, node, ws, docker_image, platform) %}
{% set test_dir_name = name.replace(":", "").replace(" ", "-").replace("-", "_")|string %}
diff --git a/cmake/utils/Summary.cmake b/cmake/utils/Summary.cmake
index 7059135fb22b..1b973f253a00 100644
--- a/cmake/utils/Summary.cmake
+++ b/cmake/utils/Summary.cmake
@@ -67,3 +67,10 @@ macro(print_summary)
message(STATUS ${OUT} " : " ${OPTION_VALUE})
endforeach()
endmacro()
+
+function(dump_options_to_file tvm_options)
+ file(REMOVE ${CMAKE_BINARY_DIR}/TVMBuildOptions.txt)
+ foreach(option ${tvm_options})
+ file(APPEND ${CMAKE_BINARY_DIR}/TVMBuildOptions.txt "${option} ${${option}} \n")
+ endforeach()
+endfunction()
diff --git a/docker/Dockerfile.ci_minimal b/docker/Dockerfile.ci_minimal
new file mode 100644
index 000000000000..cf548989eba2
--- /dev/null
+++ b/docker/Dockerfile.ci_minimal
@@ -0,0 +1,57 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# CI docker minimal CPU env
+FROM ubuntu:18.04
+
+COPY utils/apt-install-and-clear.sh /usr/local/bin/apt-install-and-clear
+
+RUN apt-get update --fix-missing
+
+COPY install/ubuntu_install_core.sh /install/ubuntu_install_core.sh
+RUN bash /install/ubuntu_install_core.sh
+
+COPY install/ubuntu_install_googletest.sh /install/ubuntu_install_googletest.sh
+RUN bash /install/ubuntu_install_googletest.sh
+
+COPY install/ubuntu1804_install_python.sh /install/ubuntu1804_install_python.sh
+RUN bash /install/ubuntu1804_install_python.sh
+
+# Globally disable pip cache
+RUN pip config set global.no-cache-dir false
+
+COPY install/ubuntu_install_python_package.sh /install/ubuntu_install_python_package.sh
+RUN bash /install/ubuntu_install_python_package.sh
+
+COPY install/ubuntu1804_manual_install_llvm.sh /install/ubuntu1804_manual_install_llvm.sh
+RUN bash /install/ubuntu1804_manual_install_llvm.sh
+
+# Rust env (build early; takes a while)
+COPY install/ubuntu_install_rust.sh /install/ubuntu_install_rust.sh
+RUN bash /install/ubuntu_install_rust.sh
+ENV RUSTUP_HOME /opt/rust
+ENV CARGO_HOME /opt/rust
+ENV PATH $PATH:$CARGO_HOME/bin
+
+# AutoTVM deps
+COPY install/ubuntu_install_redis.sh /install/ubuntu_install_redis.sh
+RUN bash /install/ubuntu_install_redis.sh
+
+# sccache
+COPY install/ubuntu_install_sccache.sh /install/ubuntu_install_sccache.sh
+RUN bash /install/ubuntu_install_sccache.sh
+ENV PATH /opt/sccache:$PATH
\ No newline at end of file
diff --git a/docker/install/ubuntu1804_manual_install_llvm.sh b/docker/install/ubuntu1804_manual_install_llvm.sh
new file mode 100755
index 000000000000..f0e9abd1d9fd
--- /dev/null
+++ b/docker/install/ubuntu1804_manual_install_llvm.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+set -e
+set -u
+set -o pipefail
+
+git clone --depth 1 --branch release/11.x https://github.com/llvm/llvm-project.git
+pushd llvm-project
+mkdir build
+pushd build
+cmake \
+ -G Ninja \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_INSTALL_PREFIX=/usr \
+ -DLLVM_ENABLE_ASSERTIONS=ON \
+ -DLLVM_ENABLE_PROJECTS="llvm;clang" \
+ ../llvm
+ninja install
+popd
+popd
+rm -rf llvm-project
+
diff --git a/tests/python/ci/test_ci.py b/tests/python/ci/test_ci.py
index 5ab5e6950494..1c2ab1ffb787 100644
--- a/tests/python/ci/test_ci.py
+++ b/tests/python/ci/test_ci.py
@@ -914,6 +914,7 @@ def test_open_docker_update_pr(
"ci_lint",
"ci_gpu",
"ci_cpu",
+ "ci_minimal",
"ci_wasm",
"ci_i386",
"ci_cortexm",
diff --git a/tests/python/unittest/test_meta_schedule_task_scheduler.py b/tests/python/unittest/test_meta_schedule_task_scheduler.py
index fc2497f05303..3edd81ee9a11 100644
--- a/tests/python/unittest/test_meta_schedule_task_scheduler.py
+++ b/tests/python/unittest/test_meta_schedule_task_scheduler.py
@@ -23,6 +23,7 @@
import pytest
import tvm
import tvm.testing
+from tvm.support import libinfo
from tvm import meta_schedule as ms
from tvm._ffi.base import TVMError
from tvm.meta_schedule.testing.dummy_object import DummyBuilder, DummyRunner
diff --git a/tests/scripts/ci.py b/tests/scripts/ci.py
index f5c60c94502a..4cc19462c907 100755
--- a/tests/scripts/ci.py
+++ b/tests/scripts/ci.py
@@ -595,6 +595,19 @@ def add_subparser(
"frontend": ("run frontend tests", ["./tests/scripts/task_python_frontend_cpu.sh"]),
},
),
+ generate_command(
+ name="minimal",
+ help="Run minimal CPU build and test(s)",
+ options={
+ "cpp": CPP_UNITTEST,
+ "unittest": (
+ "run unit tests",
+ [
+ "./tests/scripts/task_python_unittest.sh",
+ ],
+ ),
+ },
+ ),
generate_command(
name="i386",
help="Run i386 build and test(s)",
diff --git a/tests/scripts/task_config_build_minimal.sh b/tests/scripts/task_config_build_minimal.sh
new file mode 100755
index 000000000000..651f54cea21b
--- /dev/null
+++ b/tests/scripts/task_config_build_minimal.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+set -euxo pipefail
+
+BUILD_DIR=$1
+mkdir -p "$BUILD_DIR"
+cd "$BUILD_DIR"
+cp ../cmake/config.cmake .
+
+echo set\(USE_SORT ON\) >> config.cmake
+echo set\(USE_LLVM llvm-config\) >> config.cmake
+echo set\(USE_RELAY_DEBUG ON\) >> config.cmake
+echo set\(CMAKE_BUILD_TYPE=Debug\) >> config.cmake
+echo set\(CMAKE_CXX_FLAGS \"-Werror -Wp,-D_GLIBCXX_ASSERTIONS\"\) >> config.cmake
+echo set\(HIDE_PRIVATE_SYMBOLS ON\) >> config.cmake
+echo set\(USE_LIBBACKTRACE ON\) >> config.cmake
+echo set\(USE_CCACHE OFF\) >> config.cmake
+echo set\(SUMMARIZE ON\) >> config.cmake
diff --git a/tests/scripts/task_cpp_unittest.sh b/tests/scripts/task_cpp_unittest.sh
index 8ae2e9b1109f..27899d06d703 100755
--- a/tests/scripts/task_cpp_unittest.sh
+++ b/tests/scripts/task_cpp_unittest.sh
@@ -45,20 +45,22 @@ python3 tests/scripts/task_build.py \
--cmake-target cpptest \
--build-dir "${BUILD_DIR}"
-# crttest requires USE_MICRO to be enabled, which is currently the case
-# with all CI configs
-pushd "${BUILD_DIR}"
-ninja crttest
-popd
-
+# crttest requries USE_MICRO to be enabled.
+if grep -Fq "USE_MICRO ON" ${BUILD_DIR}/TVMBuildOptions.txt; then
+ pushd "${BUILD_DIR}"
+ ninja crttest
+ popd
+fi
pushd "${BUILD_DIR}"
ctest --gtest_death_test_style=threadsafe
popd
-# Test MISRA-C runtime
-pushd apps/bundle_deploy
-rm -rf build
-make test_dynamic test_static
-popd
+# Test MISRA-C runtime. It requires USE_MICRO to be enabled.
+if grep -Fq "USE_MICRO ON" ${BUILD_DIR}/TVMBuildOptions.txt; then
+ pushd apps/bundle_deploy
+ rm -rf build
+ make test_dynamic test_static
+ popd
+fi
|
apache__airflow-11723 | All task logging goes to the log for try_number 1
**Apache Airflow version**: 2.0.0a1
**What happened**:
When a task fails on the first try, the log output for additional tries go to the log for the first attempt.
**What you expected to happen**:
The logs should go to the correct log file. For the default configuration, the log filename template is `log_filename_template = {{ ti.dag_id }}/{{ ti.task_id }}/{{ ts }}/{{ try_number }}.log`, so additional numbered `.log` files should be created.
**How to reproduce it**:
Create a test dag:
```
from datetime import timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.utils.dates import days_ago
with DAG(
dag_id="trynumber_demo",
default_args={"start_date": days_ago(2), "retries": 1, "retry_delay": timedelta(0)},
schedule_interval=None,
) as dag:
def demo_task(ti=None):
print("Running demo_task, try_number =", ti.try_number)
if ti.try_number <= 1:
raise ValueError("Shan't")
task = PythonOperator(task_id="demo_task", python_callable=demo_task)
```
and trigger this dag:
```
$ airflow dags trigger trynumber_demo
```
then observe that `triggernumber_demo/demo_task/<execution_date>/` only contains 1.log, which contains the full output for 2 runs:
```
[...]
--------------------------------------------------------------------------------
[2020-10-21 13:29:07,958] {taskinstance.py:1020} INFO - Starting attempt 1 of 2
[2020-10-21 13:29:07,959] {taskinstance.py:1021} INFO -
--------------------------------------------------------------------------------
[...]
[2020-10-21 13:29:08,163] {logging_mixin.py:110} INFO - Running demo_task, try_number = 1
[2020-10-21 13:29:08,164] {taskinstance.py:1348} ERROR - Shan't
Traceback (most recent call last):
[...]
ValueError: Shan't
[2020-10-21 13:29:08,168] {taskinstance.py:1392} INFO - Marking task as UP_FOR_RETRY. dag_id=trynumber_demo, task_id=demo_task, execution_date=20201021T122907, start_date=20201021T122907, end_date=20201021T122908
[...]
[2020-10-21 13:29:09,121] {taskinstance.py:1019} INFO -
--------------------------------------------------------------------------------
[2020-10-21 13:29:09,121] {taskinstance.py:1020} INFO - Starting attempt 2 of 2
[2020-10-21 13:29:09,121] {taskinstance.py:1021} INFO -
--------------------------------------------------------------------------------
[...]
[2020-10-21 13:29:09,333] {logging_mixin.py:110} INFO - Running demo_task, try_number = 2
[2020-10-21 13:29:09,334] {python.py:141} INFO - Done. Returned value was: None
[2020-10-21 13:29:09,355] {taskinstance.py:1143} INFO - Marking task as SUCCESS.dag_id=trynumber_demo, task_id=demo_task, execution_date=20201021T122907, start_date=20201021T122909, end_date=20201021T122909
[2020-10-21 13:29:09,404] {local_task_job.py:117} INFO - Task exited with return code 0
```
The `TaskInstance()` created for the run needs to first be refreshed from the database, before setting the logging context.
| [
{
"content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (th... | [
{
"content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (th... | diff --git a/airflow/cli/commands/task_command.py b/airflow/cli/commands/task_command.py
index 145d78b917b1d..6d48907aa6d70 100644
--- a/airflow/cli/commands/task_command.py
+++ b/airflow/cli/commands/task_command.py
@@ -171,6 +171,7 @@ def task_run(args, dag=None):
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
+ ti.refresh_from_db()
ti.init_run_context(raw=args.raw)
hostname = get_hostname()
diff --git a/tests/cli/commands/test_task_command.py b/tests/cli/commands/test_task_command.py
index 0a4b991667749..ed301b2e8e092 100644
--- a/tests/cli/commands/test_task_command.py
+++ b/tests/cli/commands/test_task_command.py
@@ -31,11 +31,12 @@
from airflow.cli.commands import task_command
from airflow.configuration import conf
from airflow.exceptions import AirflowException
-from airflow.models import DagBag, TaskInstance
-from airflow.settings import Session
+from airflow.models import DagBag, DagRun, TaskInstance
from airflow.utils import timezone
from airflow.utils.cli import get_dag
+from airflow.utils.session import create_session
from airflow.utils.state import State
+from airflow.utils.types import DagRunType
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_pools, clear_db_runs
@@ -46,11 +47,11 @@
def reset(dag_id):
- session = Session()
- tis = session.query(TaskInstance).filter_by(dag_id=dag_id)
- tis.delete()
- session.commit()
- session.close()
+ with create_session() as session:
+ tis = session.query(TaskInstance).filter_by(dag_id=dag_id)
+ tis.delete()
+ runs = session.query(DagRun).filter_by(dag_id=dag_id)
+ runs.delete()
class TestCliTasks(unittest.TestCase):
@@ -256,8 +257,10 @@ class TestLogsfromTaskRunCommand(unittest.TestCase):
def setUp(self) -> None:
self.dag_id = "test_logging_dag"
self.task_id = "test_task"
+ self.dag_path = os.path.join(ROOT_FOLDER, "dags", "test_logging_in_dag.py")
reset(self.dag_id)
- self.execution_date_str = timezone.make_aware(datetime(2017, 1, 1)).isoformat()
+ self.execution_date = timezone.make_aware(datetime(2017, 1, 1))
+ self.execution_date_str = self.execution_date.isoformat()
self.log_dir = conf.get('logging', 'base_log_folder')
self.log_filename = f"{self.dag_id}/{self.task_id}/{self.execution_date_str}/1.log"
self.ti_log_file_path = os.path.join(self.log_dir, self.log_filename)
@@ -295,7 +298,7 @@ def test_logging_with_run_task(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
- with conf_vars({('core', 'dags_folder'): os.path.join(ROOT_FOLDER, f"tests/dags/{self.dag_id}")}):
+ with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args([
'tasks', 'run', self.dag_id, self.task_id, '--local', self.execution_date_str]))
@@ -322,7 +325,7 @@ def test_logging_with_run_task(self):
def test_logging_with_run_task_subprocess(self):
# We are not using self.assertLogs as we want to verify what actually is stored in the Log file
# as that is what gets displayed
- with conf_vars({('core', 'dags_folder'): os.path.join(ROOT_FOLDER, f"tests/dags/{self.dag_id}")}):
+ with conf_vars({('core', 'dags_folder'): self.dag_path}):
task_command.task_run(self.parser.parse_args([
'tasks', 'run', self.dag_id, self.task_id, '--local', self.execution_date_str]))
@@ -343,6 +346,43 @@ def test_logging_with_run_task_subprocess(self):
self.assertIn(f"INFO - Marking task as SUCCESS.dag_id={self.dag_id}, "
f"task_id={self.task_id}, execution_date=20170101T000000", logs)
+ def test_log_file_template_with_run_task(self):
+ """Verify that the taskinstance has the right context for log_filename_template"""
+
+ with mock.patch.object(task_command, "_run_task_by_selected_method"):
+ with conf_vars({('core', 'dags_folder'): self.dag_path}):
+ # increment the try_number of the task to be run
+ dag = DagBag().get_dag(self.dag_id)
+ task = dag.get_task(self.task_id)
+ with create_session() as session:
+ dag.create_dagrun(
+ execution_date=self.execution_date,
+ start_date=timezone.utcnow(),
+ state=State.RUNNING,
+ run_type=DagRunType.MANUAL,
+ session=session,
+ )
+ ti = TaskInstance(task, self.execution_date)
+ ti.refresh_from_db(session=session, lock_for_update=True)
+ ti.try_number = 1 # not running, so starts at 0
+ session.merge(ti)
+
+ log_file_path = os.path.join(os.path.dirname(self.ti_log_file_path), "2.log")
+
+ try:
+ task_command.task_run(
+ self.parser.parse_args(
+ ['tasks', 'run', self.dag_id, self.task_id, '--local', self.execution_date_str]
+ )
+ )
+
+ assert os.path.exists(log_file_path)
+ finally:
+ try:
+ os.remove(log_file_path)
+ except OSError:
+ pass
+
class TestCliTaskBackfill(unittest.TestCase):
@classmethod
|
python-telegram-bot__python-telegram-bot-377 | Execfile does not exist in py3k
<!--
Thanks for reporting issues of python-telegram-bot!
To make it easier for us to help you please enter detailed information below.
Please note, we only support the latest version of python-telegram-bot and
master branch. Please make sure to upgrade & recreate the issue on the latest
version prior to opening an issue.
-->
### Steps to reproduce
1. Use python 3
2. Try to install from git:
`$ pip install -e git+https://github.com/python-telegram-bot/python-telegram-bot.git@555e36ee8036a179f157f60dcb0c3fcf958146f4#egg=telegram`
### Expected behaviour
The library should be installed.
### Actual behaviour
NameError due to `execfile` not being a thing in python 3.
See here for alternatives: https://stackoverflow.com/a/437857
I would fix it myself, but I am unable to actually find the execfile call anywhere .-.
### Configuration
**Operating System:**
Windows 10 Education
**Version of Python, python-telegram-bot & dependencies:**
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]
### Logs
``````
$ pip install -e git+https://github.com/python-telegram-bot/python-telegram-bot.git@555e36ee8036a179f157f60dcb0c3fcf958146f4#egg=telegram
Obtaining telegram from git+https://github.com/python-telegram-bot/python-telegram-bot.git@555e36ee8036a179f157f60dcb0c3fcf958146f4#egg=telegram
Skipping because already up-to-date.
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Development\telegram\VocaBot2\src\telegram\setup.py", line 20, in <module>
execfile(os.path.join('telegram', 'version.py'))
NameError: name 'execfile' is not defined
Command "python setup.py egg_info" failed with error code 1```
``````
| [
{
"content": "#!/usr/bin/env python\n\"\"\"The setup and build script for the python-telegram-bot library.\"\"\"\n\nimport codecs\nimport os\nfrom setuptools import setup, find_packages\n\n\ndef requirements():\n \"\"\"Build the requirements list for this project\"\"\"\n requirements_list = []\n\n with... | [
{
"content": "#!/usr/bin/env python\n\"\"\"The setup and build script for the python-telegram-bot library.\"\"\"\n\nimport codecs\nimport os\nfrom setuptools import setup, find_packages\n\n\ndef requirements():\n \"\"\"Build the requirements list for this project\"\"\"\n requirements_list = []\n\n with... | diff --git a/setup.py b/setup.py
index 3b114c51d88..bd57d845bcd 100644
--- a/setup.py
+++ b/setup.py
@@ -16,6 +16,13 @@ def requirements():
return requirements_list
+
+def execfile(fn):
+ with open(fn) as f:
+ code = compile(f.read(), fn, 'exec')
+ exec(code)
+
+
with codecs.open('README.rst', 'r', 'utf-8') as fd:
execfile(os.path.join('telegram', 'version.py'))
|
jschneier__django-storages-1087 | SFTPStorage: keep trying to connect when timeout (in a loop)
I was implementing saving a file in SFTP and, when testing time out, it was never launched.
I have debugged and it goes into a loop trying to connect.
Specifically:
- https://github.com/jschneier/django-storages/blob/master/storages/backends/sftpstorage.py#L67
```
try:
self._ssh.connect(self._host, **self._params)
except paramiko.AuthenticationException as e:
```
the exception thrown is socket "timeout" (`from socket import timeout`)
I may not have done something correctly, but I have done this workaround (maybe it helps someone, or to illustrate the problem)
```
from socket import timeout
from storages.backends.sftpstorage import SFTPStorage
class SFTPStorageWithException(SFTPStorage):
@property
def sftp(self):
try:
return super().sftp
except timeout as exc:
log_message(f'Timeout connecting to SFTP: {exc}', 'error')
raise paramiko.AuthenticationException(exc)
```
thanks
| [
{
"content": "# SFTP storage backend for Django.\n# Author: Brent Tubbs <brent.tubbs@gmail.com>\n# License: MIT\n#\n# Modeled on the FTP storage by Rafal Jonca <jonca.rafal@gmail.com>\n\nimport getpass\nimport io\nimport os\nimport posixpath\nimport stat\nfrom datetime import datetime\nfrom urllib.parse import ... | [
{
"content": "# SFTP storage backend for Django.\n# Author: Brent Tubbs <brent.tubbs@gmail.com>\n# License: MIT\n#\n# Modeled on the FTP storage by Rafal Jonca <jonca.rafal@gmail.com>\n\nimport getpass\nimport io\nimport os\nimport posixpath\nimport stat\nfrom datetime import datetime\nfrom urllib.parse import ... | diff --git a/storages/backends/sftpstorage.py b/storages/backends/sftpstorage.py
index 529daf278..643685c88 100644
--- a/storages/backends/sftpstorage.py
+++ b/storages/backends/sftpstorage.py
@@ -150,7 +150,7 @@ def exists(self, name):
try:
self.sftp.stat(self._remote_path(name))
return True
- except OSError:
+ except FileNotFoundError:
return False
def _isdir_attr(self, item):
diff --git a/tests/test_sftp.py b/tests/test_sftp.py
index 094c4447f..448358f29 100644
--- a/tests/test_sftp.py
+++ b/tests/test_sftp.py
@@ -1,5 +1,6 @@
import io
import os
+import socket
import stat
from datetime import datetime
from unittest.mock import MagicMock, patch
@@ -56,7 +57,7 @@ def test_mkdir(self, mock_sftp):
self.assertEqual(mock_sftp.mkdir.call_args[0], ('foo',))
@patch('storages.backends.sftpstorage.SFTPStorage.sftp', **{
- 'stat.side_effect': (IOError(), True)
+ 'stat.side_effect': (FileNotFoundError(), True)
})
def test_mkdir_parent(self, mock_sftp):
self.storage._mkdir('bar/foo')
@@ -69,7 +70,7 @@ def test_save(self, mock_sftp):
self.assertTrue(mock_sftp.open.return_value.write.called)
@patch('storages.backends.sftpstorage.SFTPStorage.sftp', **{
- 'stat.side_effect': (IOError(), True)
+ 'stat.side_effect': (FileNotFoundError(), True)
})
def test_save_in_subdir(self, mock_sftp):
self.storage._save('bar/foo', File(io.BytesIO(b'foo'), 'foo'))
@@ -86,11 +87,18 @@ def test_exists(self, mock_sftp):
self.assertTrue(self.storage.exists('foo'))
@patch('storages.backends.sftpstorage.SFTPStorage.sftp', **{
- 'stat.side_effect': IOError()
+ 'stat.side_effect': FileNotFoundError()
})
def test_not_exists(self, mock_sftp):
self.assertFalse(self.storage.exists('foo'))
+ @patch('storages.backends.sftpstorage.SFTPStorage.sftp', **{
+ 'stat.side_effect': socket.timeout()
+ })
+ def test_not_exists_timeout(self, mock_sftp):
+ with self.assertRaises(socket.timeout):
+ self.storage.exists('foo')
+
@patch('storages.backends.sftpstorage.SFTPStorage.sftp', **{
'listdir_attr.return_value':
[MagicMock(filename='foo', st_mode=stat.S_IFDIR),
|
vyperlang__vyper-3340 | Bug: compiler dislikes `x not in [a, b]` in 0.3.8, whereas it was fine in 0.3.7
### Version Information
* vyper Version (output of `vyper --version`): 0.3.8
* OS: osx
* Python Version (output of `python --version`): 3.10.4
### What's your issue about?
<img width="705" alt="image" src="https://user-images.githubusercontent.com/11488427/230437774-c3b68030-9319-4169-b344-dbb470002102.png">
| [
{
"content": "from typing import Dict\n\nfrom vyper.semantics.analysis.base import VarInfo\nfrom vyper.semantics.types import AddressT, BytesT, VyperType\nfrom vyper.semantics.types.shortcuts import BYTES32_T, UINT256_T\n\n\n# common properties for environment variables\nclass _EnvType(VyperType):\n def __eq... | [
{
"content": "from typing import Dict\n\nfrom vyper.semantics.analysis.base import VarInfo\nfrom vyper.semantics.types import AddressT, BytesT, VyperType\nfrom vyper.semantics.types.shortcuts import BYTES32_T, UINT256_T\n\n\n# common properties for environment variables\nclass _EnvType(VyperType):\n def __eq... | diff --git a/vyper/semantics/environment.py b/vyper/semantics/environment.py
index 0f915a2161..ad68f1103e 100644
--- a/vyper/semantics/environment.py
+++ b/vyper/semantics/environment.py
@@ -57,12 +57,7 @@ def get_constant_vars() -> Dict:
return result
-# Not sure this is necessary, but add an ad-hoc type for `self` for clarity
-class _SelfT(AddressT):
- pass
-
-
-MUTABLE_ENVIRONMENT_VARS: Dict[str, type] = {"self": _SelfT}
+MUTABLE_ENVIRONMENT_VARS: Dict[str, type] = {"self": AddressT}
def get_mutable_vars() -> Dict:
|
ansible__ansible-modules-extras-1291 | pam_limits - documentation is not updated
`limit_type` choices are `hard`, `soft` in the [documentation](http://docs.ansible.com/ansible/pam_limits_module.html) but in the [code](https://github.com/ansible/ansible-modules-extras/blob/devel/system/pam_limits.py#L95) `-` is supported.
pam_limits - documentation is not updated
`limit_type` choices are `hard`, `soft` in the [documentation](http://docs.ansible.com/ansible/pam_limits_module.html) but in the [code](https://github.com/ansible/ansible-modules-extras/blob/devel/system/pam_limits.py#L95) `-` is supported.
| [
{
"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2014, Sebastien Rohaut <sebastien.rohaut@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible 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 Softw... | [
{
"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2014, Sebastien Rohaut <sebastien.rohaut@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible 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 Softw... | diff --git a/system/pam_limits.py b/system/pam_limits.py
index eb04021c3e0..4003f76d3f8 100644
--- a/system/pam_limits.py
+++ b/system/pam_limits.py
@@ -40,7 +40,7 @@
description:
- Limit type, see C(man limits) for an explanation
required: true
- choices: [ "hard", "soft" ]
+ choices: [ "hard", "soft", "-" ]
limit_item:
description:
- The limit to be set
|
microsoft__botbuilder-python-2050 | botbuidler support for regex== 2022 and above
Description:
I'm currently working on building a chatbot using Azure Bot Builder SDK in conjunction with OpenAI. In my project, I'm relying on the OpenAIEmbedding class from the langchain package, which utilizes Tiktoken. However, I've run into an issue due to dependency conflicts with Tiktoken. Specifically, Tiktoken requires regex version 2022 or higher, while the Bot Builder package supports only up to regex version 2019.
Feature Request:
I kindly request adding support for Tiktoken's regex version 2022 or higher in the OpenAIEmbedding class within the langchain package. This update would resolve the dependency conflicts and enable smoother integration of OpenAI into projects using Azure Bot Builder SDK.
Additional Information:
Current Behavior: Currently, the OpenAIEmbedding class in langchain relies on Tiktoken, which necessitates a regex version that is not compatible with the Bot Builder SDK's regex version support.
Desired Behavior: The botbuilder classes should be updated to support Tiktoken's dependency on regex version 2022 or higher t
Impact of the Feature:
This feature would benefit developers working on chatbot projects that use Azure Bot Builder SDK and OpenAI. It would eliminate dependency conflicts, allowing for a seamless integration experience.
| [
{
"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport os\nfrom setuptools import setup\n\nREQUIRES = [\n \"regex<=2019.08.19\",\n \"emoji==1.7.0\",\n \"recognizers-text-date-time>=1.0.2a1\",\n \"recognizers-text-number-with-unit>=1.0.2... | [
{
"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport os\nfrom setuptools import setup\n\nREQUIRES = [\n \"regex>=2022.1.18\",\n \"emoji==1.7.0\",\n \"recognizers-text-date-time>=1.0.2a1\",\n \"recognizers-text-number-with-unit>=1.0.2a... | diff --git a/libraries/botbuilder-dialogs/setup.py b/libraries/botbuilder-dialogs/setup.py
index 6e97715a5..574f8bbe7 100644
--- a/libraries/botbuilder-dialogs/setup.py
+++ b/libraries/botbuilder-dialogs/setup.py
@@ -5,7 +5,7 @@
from setuptools import setup
REQUIRES = [
- "regex<=2019.08.19",
+ "regex>=2022.1.18",
"emoji==1.7.0",
"recognizers-text-date-time>=1.0.2a1",
"recognizers-text-number-with-unit>=1.0.2a1",
|
coala__coala-4980 | Compatibility.py: Add comment explaining JSONDecodeError is missing in Python 3.4
difficulty/newcomer
Opened via [gitter](https://gitter.im/coala/coala/?at=59098da68fcce56b205cd7e0) by @jayvdb
| [
{
"content": "import json\ntry:\n JSONDecodeError = json.decoder.JSONDecodeError\nexcept AttributeError: # pragma Python 3.5,3.6: no cover\n JSONDecodeError = ValueError\n",
"path": "coalib/misc/Compatibility.py"
}
] | [
{
"content": "import json\ntry:\n # JSONDecodeError class is available since Python 3.5.x.\n JSONDecodeError = json.decoder.JSONDecodeError\nexcept AttributeError: # pragma Python 3.5,3.6: no cover\n JSONDecodeError = ValueError\n",
"path": "coalib/misc/Compatibility.py"
}
] | diff --git a/coalib/misc/Compatibility.py b/coalib/misc/Compatibility.py
index f81e818544..f0e63d63b3 100644
--- a/coalib/misc/Compatibility.py
+++ b/coalib/misc/Compatibility.py
@@ -1,5 +1,6 @@
import json
try:
+ # JSONDecodeError class is available since Python 3.5.x.
JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError: # pragma Python 3.5,3.6: no cover
JSONDecodeError = ValueError
|
open-telemetry__opentelemetry-python-2962 | Fix dead link
There is a dead link in the CHANGELOG, [here](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md?plain=1#L13).
| [
{
"content": "#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nfrom configparser import ConfigParser\nfrom datetime import datetime\nfrom inspect import cleandoc\nfrom itertools import chain\nfrom os.path import basename\nfrom pathlib i... | [
{
"content": "#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nfrom configparser import ConfigParser\nfrom datetime import datetime\nfrom inspect import cleandoc\nfrom itertools import chain\nfrom os.path import basename\nfrom pathlib i... | diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea4f873b37d..6d3b1d2fedb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v1.13.0-0.34b0...HEAD)
+## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v1.13.0...HEAD)
- Update explicit histogram bucket boundaries
([#2947](https://github.com/open-telemetry/opentelemetry-python/pull/2947))
diff --git a/scripts/eachdist.py b/scripts/eachdist.py
index c02a75b256d..0c0620e95ac 100755
--- a/scripts/eachdist.py
+++ b/scripts/eachdist.py
@@ -675,7 +675,7 @@ def release_args(args):
update_dependencies(targets, version, packages)
update_version_files(targets, version, packages)
- update_changelogs("-".join(updated_versions))
+ update_changelogs(updated_versions[0])
def test_args(args):
|
open-mmlab__mmcv-1834 | Support None in DictAction
Some times there are needs to override some key in the config to be `None`, e.g., the load_from is assigned to some string and you want to override it through `--cfg-options load_from=None`, it will pass a string of None rather than the real `None` value to the config and make checkpoint loader load checkpoint from a path named `'None'`
| [
{
"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport ast\nimport copy\nimport os\nimport os.path as osp\nimport platform\nimport shutil\nimport sys\nimport tempfile\nimport types\nimport uuid\nimport warnings\nfrom argparse import Action, ArgumentParser\nfrom collections import abc\nfrom import... | [
{
"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport ast\nimport copy\nimport os\nimport os.path as osp\nimport platform\nimport shutil\nimport sys\nimport tempfile\nimport types\nimport uuid\nimport warnings\nfrom argparse import Action, ArgumentParser\nfrom collections import abc\nfrom import... | diff --git a/mmcv/utils/config.py b/mmcv/utils/config.py
index 4f96372ae4..473bd1e165 100644
--- a/mmcv/utils/config.py
+++ b/mmcv/utils/config.py
@@ -638,6 +638,8 @@ def _parse_int_float_bool(val):
pass
if val.lower() in ['true', 'false']:
return True if val.lower() == 'true' else False
+ if val == 'None':
+ return None
return val
@staticmethod
diff --git a/tests/test_utils/test_config.py b/tests/test_utils/test_config.py
index 6f9f95726c..368016e572 100644
--- a/tests/test_utils/test_config.py
+++ b/tests/test_utils/test_config.py
@@ -470,9 +470,18 @@ def test_dict_action():
with pytest.raises(AssertionError):
parser.parse_args(['--options', 'item2.a=[(a,b), [1,2], false'])
# Normal values
- args = parser.parse_args(
- ['--options', 'item2.a=1', 'item2.b=0.1', 'item2.c=x', 'item3=false'])
- out_dict = {'item2.a': 1, 'item2.b': 0.1, 'item2.c': 'x', 'item3': False}
+ args = parser.parse_args([
+ '--options', 'item2.a=1', 'item2.b=0.1', 'item2.c=x', 'item3=false',
+ 'item4=none', 'item5=None'
+ ])
+ out_dict = {
+ 'item2.a': 1,
+ 'item2.b': 0.1,
+ 'item2.c': 'x',
+ 'item3': False,
+ 'item4': 'none',
+ 'item5': None,
+ }
assert args.options == out_dict
cfg_file = osp.join(data_path, 'config/a.py')
cfg = Config.fromfile(cfg_file)
|
django-helpdesk__django-helpdesk-645 | systems_settings url should only be available to staff users
currently, the template starts to render before it fails if the user is not logged in.
| [
{
"content": "\"\"\"\ndjango-helpdesk - A Django powered ticket tracker for small enterprise.\n\n(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.\n\nurls.py - Mapping of URL's to our various views. Note we always used NAMED\n views for simplicity in linking later on.\n\"\"\"\n\nf... | [
{
"content": "\"\"\"\ndjango-helpdesk - A Django powered ticket tracker for small enterprise.\n\n(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.\n\nurls.py - Mapping of URL's to our various views. Note we always used NAMED\n views for simplicity in linking later on.\n\"\"\"\n\nf... | diff --git a/helpdesk/urls.py b/helpdesk/urls.py
index 969d8dd1d..02d1ff1d0 100644
--- a/helpdesk/urls.py
+++ b/helpdesk/urls.py
@@ -222,6 +222,6 @@ def get_context_data(self, **kwargs):
name='help_context'),
url(r'^system_settings/$',
- DirectTemplateView.as_view(template_name='helpdesk/system_settings.html'),
+ login_required(DirectTemplateView.as_view(template_name='helpdesk/system_settings.html')),
name='system_settings'),
]
|
pre-commit__pre-commit-67 | TypeError while instantiating LoggingHandler (2.6)
I assume this is new-style vs old-style classes being grumpy?
```
>>> from pre_commit.logging_handler import LoggingHandler
>>> LoggingHandler(True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../py_env/lib/python2.6/site-packages/pre_commit/logging_handler.py", line 19, in __init__
super(LoggingHandler, self).__init__()
TypeError: super() argument 1 must be type, not classobj
```
| [
{
"content": "\nfrom __future__ import print_function\n\nimport logging\n\nfrom pre_commit import color\n\n\nLOG_LEVEL_COLORS = {\n 'DEBUG': '',\n 'INFO': '',\n 'WARNING': color.YELLOW,\n 'ERROR': color.RED,\n}\n\n\nclass LoggingHandler(logging.Handler):\n def __init__(self, use_color):\n ... | [
{
"content": "\nfrom __future__ import print_function\n\nimport logging\n\nfrom pre_commit import color\n\n\nLOG_LEVEL_COLORS = {\n 'DEBUG': '',\n 'INFO': '',\n 'WARNING': color.YELLOW,\n 'ERROR': color.RED,\n}\n\n\nclass LoggingHandler(logging.Handler):\n def __init__(self, use_color):\n ... | diff --git a/pre_commit/logging_handler.py b/pre_commit/logging_handler.py
index 11736d1b5..70b61e730 100644
--- a/pre_commit/logging_handler.py
+++ b/pre_commit/logging_handler.py
@@ -16,7 +16,7 @@
class LoggingHandler(logging.Handler):
def __init__(self, use_color):
- super(LoggingHandler, self).__init__()
+ logging.Handler.__init__(self)
self.use_color = use_color
def emit(self, record):
diff --git a/tests/logging_handler_test.py b/tests/logging_handler_test.py
new file mode 100644
index 000000000..d2fed4189
--- /dev/null
+++ b/tests/logging_handler_test.py
@@ -0,0 +1,38 @@
+import __builtin__
+import mock
+import pytest
+
+from pre_commit import color
+from pre_commit.logging_handler import LoggingHandler
+
+
+@pytest.yield_fixture
+def print_mock():
+ with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
+ yield print_mock
+
+
+class FakeLogRecord(object):
+ def __init__(self, message, levelname, levelno):
+ self.message = message
+ self.levelname = levelname
+ self.levelno = levelno
+
+ def getMessage(self):
+ return self.message
+
+
+def test_logging_handler_color(print_mock):
+ handler = LoggingHandler(True)
+ handler.emit(FakeLogRecord('hi', 'WARNING', 30))
+ print_mock.assert_called_once_with(
+ color.YELLOW + '[WARNING]' + color.NORMAL + ' hi',
+ )
+
+
+def test_logging_handler_no_color(print_mock):
+ handler = LoggingHandler(False)
+ handler.emit(FakeLogRecord('hi', 'WARNING', 30))
+ print_mock.assert_called_once_with(
+ '[WARNING] hi',
+ )
|
opendatacube__datacube-core-747 | Dataset `__eq__` fails when other object is not a Dataset
### Expected behaviour
```python
ds, *_ = dc.find_datasets(..)
assert (ds == "33") is False
```
### Actual behaviour
Error is raised inside `__eq__` operator.
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-a8ddf445deb8> in <module>
1 ds, *_ = dc.find_datasets(product=product, limit=10)
2
----> 3 assert (ds == "33") is False
~/wk/datacube-core/datacube/model/__init__.py in __eq__(self, other)
286
287 def __eq__(self, other) -> bool:
--> 288 return self.id == other.id
289
290 def __hash__(self):
AttributeError: 'str' object has no attribute 'id'
```
| [
{
"content": "# coding=utf-8\n\"\"\"\nCore classes used across modules.\n\"\"\"\nimport logging\nimport math\nimport warnings\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom pathlib import Path\nfrom uuid import UUID\n\nfrom affine import Affine\nfrom typing import Optional, List, Mapp... | [
{
"content": "# coding=utf-8\n\"\"\"\nCore classes used across modules.\n\"\"\"\nimport logging\nimport math\nimport warnings\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom pathlib import Path\nfrom uuid import UUID\n\nfrom affine import Affine\nfrom typing import Optional, List, Mapp... | diff --git a/datacube/model/__init__.py b/datacube/model/__init__.py
index a9c93b2971..ef7c588308 100644
--- a/datacube/model/__init__.py
+++ b/datacube/model/__init__.py
@@ -285,7 +285,9 @@ def xytuple(obj):
return None
def __eq__(self, other) -> bool:
- return self.id == other.id
+ if isinstance(other, Dataset):
+ return self.id == other.id
+ return False
def __hash__(self):
return hash(self.id)
diff --git a/tests/test_model.py b/tests/test_model.py
index 4406f28844..521eb8c1c9 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -45,6 +45,14 @@ def test_gridspec_upperleft():
assert cells[(30, 15)].extent.boundingbox == tile_bbox
+def test_dataset_basics():
+ ds = mk_sample_dataset([dict(name='a')])
+ assert ds == ds
+ assert ds != "33"
+ assert (ds == "33") is False
+ assert str(ds) == repr(ds)
+
+
def test_dataset_measurement_paths():
format = 'GeoTiff'
|
joke2k__faker-318 | Access to the Generator.random
It would be nice if one could gain access to the Generator.random variable so that one could save/set the state. I realize I can pass in the seed, but one currently has no way of gathering what the seed/state is if using the automatically generated seed. I don't want to use a fixed seed, but I do want to log/print the seed used _if_ the tests fail.
That is, I'd like to be able to do something like: `faker.generator.getstate()` (which gets the random state w/o exposing random) or `faker.generator.random.getstate()` (which gives access to the random variable)
For now, the workaround appears to be to create a Faker object with your own Generator.
| [
{
"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport random\n\n\n_re_token = re.compile(r'\\{\\{(\\s?)(\\w+)(\\s?)\\}\\}')\nrandom = random.Random()\n\n\nclass Generator(object):\n\n __config = {}\n\n def __init__(self, **config):\n self.providers = []\n ... | [
{
"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport random\n\n\n_re_token = re.compile(r'\\{\\{(\\s?)(\\w+)(\\s?)\\}\\}')\nrandom = random.Random()\n\n\nclass Generator(object):\n\n __config = {}\n\n def __init__(self, **config):\n self.providers = []\n ... | diff --git a/README.rst b/README.rst
index 4dc04a86fb..0941dbdaa7 100644
--- a/README.rst
+++ b/README.rst
@@ -263,13 +263,26 @@ How to use with factory-boy
title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=4))
author_name = factory.LazyAttribute(lambda x: faker.name())
+Accessing the `random` instance
+-------------------------------
+
+The ``.random`` property on the generator returns the instance of ``random.Random``
+used to generate the values:
+
+__ code:: python
+
+ from faker import Faker
+ fake = Faker()
+ fake.random
+ fake.random.getstate()
+
Seeding the Generator
---------------------
When using Faker for unit testing, you will often want to generate the same
-data set. The generator offers a ``seed()`` method, which seeds the random
-number generator. Calling the same script twice with the same seed produces the
-same results.
+data set. For convenience, the generator also provide a ``seed()`` method, which
+seeds the random number generator. Calling the same script twice with the same
+seed produces the same results.
.. code:: python
@@ -280,8 +293,20 @@ same results.
print fake.name()
> Margaret Boehm
+The code above is equivalent to the following:
+
+.. code:: python
+
+ from faker import Faker
+ fake = Faker()
+ faker.random.seed(4321)
+
+ print fake.name()
+ > Margaret Boehm
+
Tests
-----
+
Installing dependencies:
.. code:: bash
diff --git a/docs/index.rst b/docs/index.rst
index 601d474d0d..7e96203cac 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -264,13 +264,26 @@ How to use with factory-boy
title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=4))
author_name = factory.LazyAttribute(lambda x: faker.name())
+Accessing the `random` instance
+-------------------------------
+
+The ``.random`` property on the generator returns the instance of ``random.Random``
+used to generate the values:
+
+__ code:: python
+
+ from faker import Faker
+ fake = Faker()
+ fake.random
+ fake.random.getstate()
+
Seeding the Generator
---------------------
When using Faker for unit testing, you will often want to generate the same
-data set. The generator offers a ``seed()`` method, which seeds the random
-number generator. Calling the same script twice with the same seed produces the
-same results.
+data set. For convenience, the generator also provide a ``seed()`` method, which
+seeds the random number generator. Calling the same script twice with the same
+seed produces the same results.
.. code:: python
@@ -281,6 +294,17 @@ same results.
print fake.name()
> Margaret Boehm
+The code above is equivalent to the following:
+
+.. code:: python
+
+ from faker import Faker
+ fake = Faker()
+ faker.random.seed(4321)
+
+ print fake.name()
+ > Margaret Boehm
+
Tests
-----
diff --git a/faker/generator.py b/faker/generator.py
index 95dfac2a73..74034cb440 100644
--- a/faker/generator.py
+++ b/faker/generator.py
@@ -50,6 +50,10 @@ def get_providers(self):
"""Returns added providers."""
return self.providers
+ @property
+ def random(self):
+ return random
+
def seed(self, seed=None):
"""Calls random.seed"""
random.seed(seed)
diff --git a/faker/tests/__init__.py b/faker/tests/__init__.py
index 6502a4489d..5dc2252823 100644
--- a/faker/tests/__init__.py
+++ b/faker/tests/__init__.py
@@ -518,6 +518,12 @@ class GeneratorTestCase(unittest.TestCase):
def setUp(self):
self.generator = Generator()
+ @patch('random.getstate')
+ def test_get_random(self, mock_system_random):
+ random_instance = self.generator.random
+ random_instance.getstate()
+ self.assertFalse(mock_system_random.called)
+
@patch('random.seed')
def test_random_seed_doesnt_seed_system_random(self, mock_system_random):
self.generator.seed(0)
|
scikit-image__scikit-image-1430 | measure.label is documented under morphology.label
In the [measure API reference](http://scikit-image.org/docs/stable/api/skimage.measure.html) label is not documented, but it is [documented under morphology module](http://scikit-image.org/docs/stable/api/skimage.morphology.html#label) (which is depreciated).
| [
{
"content": "from ._find_contours import find_contours\nfrom ._marching_cubes import (marching_cubes, mesh_surface_area,\n correct_mesh_orientation)\nfrom ._regionprops import regionprops, perimeter\nfrom ._structural_similarity import structural_similarity\nfrom ._polygon import a... | [
{
"content": "from ._find_contours import find_contours\nfrom ._marching_cubes import (marching_cubes, mesh_surface_area,\n correct_mesh_orientation)\nfrom ._regionprops import regionprops, perimeter\nfrom ._structural_similarity import structural_similarity\nfrom ._polygon import a... | diff --git a/skimage/measure/__init__.py b/skimage/measure/__init__.py
index e2a4a51aef4..9731d6da6fc 100755
--- a/skimage/measure/__init__.py
+++ b/skimage/measure/__init__.py
@@ -9,7 +9,7 @@
from .profile import profile_line
from .fit import LineModel, CircleModel, EllipseModel, ransac
from .block import block_reduce
-from ._ccomp import label
+from ._label import label
__all__ = ['find_contours',
|
opendatacube__datacube-core-652 | `unary_union` does not detect failures
In this function:
https://github.com/opendatacube/datacube-core/blob/0ab135ef9986bee0ea476ced76fad7b9c2f47328/datacube/utils/geometry/_base.py#L692-L695
https://github.com/opendatacube/datacube-core/blob/0ab135ef9986bee0ea476ced76fad7b9c2f47328/datacube/utils/geometry/_base.py#L711-L712
`ogr.UnionCascaded()` can return `None` on failure, this `None` is then passed on to `Geometry` constructor (`._geom` property), but `Geometry` class assumes that `_geom` is not `None`. So there is no clean way to check if union succeeded in the first place(without accessing private members), probably `unary_union` should just return `None` on failure to mimic behaviour of the underlying function.
| [
{
"content": "import functools\nimport math\nfrom collections import namedtuple, OrderedDict\nfrom typing import Tuple, Callable\n\nimport cachetools\nimport numpy\nfrom affine import Affine\nfrom osgeo import ogr, osr\n\nfrom .tools import roi_normalise, roi_shape\n\nCoordinate = namedtuple('Coordinate', ('val... | [
{
"content": "import functools\nimport math\nfrom collections import namedtuple, OrderedDict\nfrom typing import Tuple, Callable\n\nimport cachetools\nimport numpy\nfrom affine import Affine\nfrom osgeo import ogr, osr\n\nfrom .tools import roi_normalise, roi_shape\n\nCoordinate = namedtuple('Coordinate', ('val... | diff --git a/datacube/utils/geometry/_base.py b/datacube/utils/geometry/_base.py
index 79611d46cc..b9ec36a6e3 100644
--- a/datacube/utils/geometry/_base.py
+++ b/datacube/utils/geometry/_base.py
@@ -303,6 +303,8 @@ def _get_coordinates(geom):
def _make_geom_from_ogr(geom, crs):
+ if geom is None:
+ return None
result = Geometry.__new__(Geometry)
result._geom = geom # pylint: disable=protected-access
result.crs = crs
diff --git a/tests/test_geometry.py b/tests/test_geometry.py
index 5571f43401..6995b6ffc0 100644
--- a/tests/test_geometry.py
+++ b/tests/test_geometry.py
@@ -199,6 +199,8 @@ def test_unary_union():
assert union4.type == 'Polygon'
assert union4.area == 2.5 * box1.area
+ assert geometry.unary_union([]) is None
+
with pytest.raises(ValueError):
pt = geometry.point(6, 7, epsg4326)
geometry.unary_union([pt, pt])
|
frappe__frappe-15915 | no_copy option not available in customize form field
<!--
Welcome to the Frappe Framework issue tracker! Before creating an issue, please heed the following:
1. This tracker should only be used to report bugs and request features / enhancements to Frappe
- For questions and general support, use https://stackoverflow.com/questions/tagged/frappe
- For documentation issues, refer to https://frappeframework.com/docs/user/en or the developer cheetsheet https://github.com/frappe/frappe/wiki/Developer-Cheatsheet
2. Use the search function before creating a new issue. Duplicates will be closed and directed to
the original discussion.
3. When making a bug report, make sure you provide all required information. The easier it is for
maintainers to reproduce, the faster it'll be fixed.
4. If you think you know what the reason for the bug is, share it with us. Maybe put in a PR 😉
-->
## Description of the issue
## Context information (for bug reports)
**Output of `bench version`**
```
(paste here)
```
## Steps to reproduce the issue
1.
2.
3.
### Observed result
no copy is a field property in doctype, but in customize form, the no copy option is not available for the field.
### Expected result
make no copy as available property of the field in customize form
### Stacktrace / full error message
```
(paste here)
```
## Additional information
OS version / distribution, `Frappe` install method, etc.
| [
{
"content": "# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See LICENSE\n\n\"\"\"\n\tCustomize Form is a Single DocType used to mask the Property Setter\n\tThus providing a better UI from user perspective\n\"\"\"\nimport json\nimport frappe\nimport frappe.translate\nfrom f... | [
{
"content": "# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See LICENSE\n\n\"\"\"\n\tCustomize Form is a Single DocType used to mask the Property Setter\n\tThus providing a better UI from user perspective\n\"\"\"\nimport json\nimport frappe\nimport frappe.translate\nfrom f... | diff --git a/frappe/custom/doctype/customize_form/customize_form.py b/frappe/custom/doctype/customize_form/customize_form.py
index 92a540447fd1..f1b6ab40edb1 100644
--- a/frappe/custom/doctype/customize_form/customize_form.py
+++ b/frappe/custom/doctype/customize_form/customize_form.py
@@ -540,6 +540,7 @@ def reset_customization(doctype):
'in_global_search': 'Check',
'in_preview': 'Check',
'bold': 'Check',
+ 'no_copy': 'Check',
'hidden': 'Check',
'collapsible': 'Check',
'collapsible_depends_on': 'Data',
diff --git a/frappe/custom/doctype/customize_form/test_customize_form.py b/frappe/custom/doctype/customize_form/test_customize_form.py
index 0fe39e0008ec..37198c5ba6a5 100644
--- a/frappe/custom/doctype/customize_form/test_customize_form.py
+++ b/frappe/custom/doctype/customize_form/test_customize_form.py
@@ -97,13 +97,18 @@ def test_save_customization_custom_field_property(self):
custom_field = d.get("fields", {"fieldname": "test_custom_field"})[0]
custom_field.reqd = 1
+ custom_field.no_copy = 1
d.run_method("save_customization")
self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 1)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "no_copy"), 1)
custom_field = d.get("fields", {"is_custom_field": True})[0]
custom_field.reqd = 0
+ custom_field.no_copy = 0
d.run_method("save_customization")
self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 0)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "no_copy"), 0)
+
def test_save_customization_new_field(self):
d = self.get_customize_form("Event")
diff --git a/frappe/custom/doctype/customize_form_field/customize_form_field.json b/frappe/custom/doctype/customize_form_field/customize_form_field.json
index 4351e76609dd..5906cd3bcfaf 100644
--- a/frappe/custom/doctype/customize_form_field/customize_form_field.json
+++ b/frappe/custom/doctype/customize_form_field/customize_form_field.json
@@ -20,6 +20,7 @@
"in_global_search",
"in_preview",
"bold",
+ "no_copy",
"allow_in_quick_entry",
"translatable",
"column_break_7",
@@ -437,13 +438,19 @@
"fieldname": "show_dashboard",
"fieldtype": "Check",
"label": "Show Dashboard"
+ },
+ {
+ "default": "0",
+ "fieldname": "no_copy",
+ "fieldtype": "Check",
+ "label": "No Copy"
}
],
"idx": 1,
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2022-01-27 21:45:22.349776",
+ "modified": "2022-02-08 19:38:16.111199",
"modified_by": "Administrator",
"module": "Custom",
"name": "Customize Form Field",
@@ -453,4 +460,4 @@
"sort_field": "modified",
"sort_order": "ASC",
"states": []
-}
\ No newline at end of file
+}
|
dask__distributed-367 | OverflowError when sending large sparse arrays
I don't yet have a small reproducible example, but I can make this happen every time I try to collect many large sparse arrays. I do have a notebook that will produce it though, and can make that available. The traceback:
```
Traceback (most recent call last):
File "/home/jcrist/miniconda/envs/dask_learn/lib/python2.7/site-packages/distributed/core.py", line 266, in write
frames = protocol.dumps(msg)
File "/home/jcrist/miniconda/envs/dask_learn/lib/python2.7/site-packages/distributed/protocol.py", line 81, in dumps
frames = dumps_msgpack(small)
File "/home/jcrist/miniconda/envs/dask_learn/lib/python2.7/site-packages/distributed/protocol.py", line 155, in dumps_msgpack
fmt, payload = maybe_compress(payload)
File "/home/jcrist/miniconda/envs/dask_learn/lib/python2.7/site-packages/distributed/protocol.py", line 137, in maybe_compress
compressed = compress(payload)
OverflowError: size does not fit in an int
```
A few notes:
- Each array is roughly `675000 x 745`, and ~1% dense. The total bytes for indices + indptr + data is ~40MB each.
- I can get each array individually, so it's not a problem with a chunk being too large
- The error appears only when I'm collecting enough at once (for my size, 39 and and lower works fine).
- At 41 arrays I get the above error, 40 arrays gives me a different (but probably related) error:
```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-55-7b87709b6c67> in <module>()
----> 1 res = t.compute()
/home/jcrist/dask/dask/base.pyc in compute(self, **kwargs)
84 Extra keywords to forward to the scheduler ``get`` function.
85 """
---> 86 return compute(self, **kwargs)[0]
87
88 @classmethod
/home/jcrist/dask/dask/base.pyc in compute(*args, **kwargs)
177 dsk = merge(var.dask for var in variables)
178 keys = [var._keys() for var in variables]
--> 179 results = get(dsk, keys, **kwargs)
180
181 results_iter = iter(results)
/home/jcrist/miniconda/envs/dask_learn/lib/python2.7/site-packages/distributed/executor.pyc in get(self, dsk, keys, **kwargs)
1008
1009 if status == 'error':
-> 1010 raise result
1011 else:
1012 return result
ValueError: corrupt input at byte 2
```
| [
{
"content": "\"\"\"\nThe distributed message protocol consists of the following parts:\n\n1. The length of the header, stored as a uint32\n2. The header, stored as msgpack.\n If there are no fields in the header then we skip it entirely.\n3. The payload, stored as possibly compressed msgpack\n4. A senti... | [
{
"content": "\"\"\"\nThe distributed message protocol consists of the following parts:\n\n1. The length of the header, stored as a uint32\n2. The header, stored as msgpack.\n If there are no fields in the header then we skip it entirely.\n3. The payload, stored as possibly compressed msgpack\n4. A senti... | diff --git a/distributed/protocol.py b/distributed/protocol.py
index ca67ddbdd4f..21d1584f968 100644
--- a/distributed/protocol.py
+++ b/distributed/protocol.py
@@ -123,6 +123,8 @@ def maybe_compress(payload, compression=default_compression, min_size=1e4,
return None, payload
if len(payload) < min_size:
return None, payload
+ if len(payload) > 2**31:
+ return None, payload
min_size = int(min_size)
sample_size = int(sample_size)
|
piskvorky__gensim-2869 | Investigate and fix Keras problem under Python 3.8
One of our unit tests fails on Travis under Py3.8.
```
=================================== FAILURES ===================================
_____________ TestKerasWord2VecWrapper.testEmbeddingLayerCosineSim _____________
self = <gensim.test.test_keras_integration.TestKerasWord2VecWrapper testMethod=testEmbeddingLayerCosineSim>
def testEmbeddingLayerCosineSim(self):
"""
Test Keras 'Embedding' layer returned by 'get_embedding_layer' function for a simple word similarity task.
"""
keras_w2v_model = self.model_cos_sim
keras_w2v_model_wv = keras_w2v_model.wv
embedding_layer = keras_w2v_model_wv.get_keras_embedding()
input_a = Input(shape=(1,), dtype='int32', name='input_a')
input_b = Input(shape=(1,), dtype='int32', name='input_b')
embedding_a = embedding_layer(input_a)
embedding_b = embedding_layer(input_b)
similarity = dot([embedding_a, embedding_b], axes=2, normalize=True)
> model = Model(input=[input_a, input_b], output=similarity)
embedding_a = <tf.Tensor 'embedding_4/Identity:0' shape=(None, 1, 100) dtype=float32>
embedding_b = <tf.Tensor 'embedding_4_1/Identity:0' shape=(None, 1, 100) dtype=float32>
embedding_layer = <tensorflow.python.keras.layers.embeddings.Embedding object at 0x7f603df0d130>
input_a = <tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>
input_b = <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>
keras_w2v_model = <gensim.models.word2vec.Word2Vec object at 0x7f603df0d760>
keras_w2v_model_wv = <gensim.models.keyedvectors.Word2VecKeyedVectors object at 0x7f603df0d250>
self = <gensim.test.test_keras_integration.TestKerasWord2VecWrapper testMethod=testEmbeddingLayerCosineSim>
similarity = <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>
gensim/test/test_keras_integration.py:62:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:167: in __init__
super(Model, self).__init__(*args, **kwargs)
__class__ = <class 'tensorflow.python.keras.engine.training.Model'>
args = ()
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/keras/engine/network.py:176: in __init__
self._init_subclassed_network(**kwargs)
args = ()
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py:456: in _method_wrapper
result = method(self, *args, **kwargs)
args = ()
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
method = <function Network._init_subclassed_network at 0x7f60465f6d30>
previous_value = True
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/keras/engine/network.py:367: in _init_subclassed_network
self._base_init(name=name, **kwargs)
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
name = None
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py:456: in _method_wrapper
result = method(self, *args, **kwargs)
args = ()
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'name': None, 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
method = <function Network._base_init at 0x7f60465f6a60>
previous_value = False
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
.tox/py38-linux/lib/python3.8/site-packages/tensorflow/python/keras/engine/network.py:202: in _base_init
generic_utils.validate_kwargs(kwargs, {'trainable', 'dtype', 'dynamic',
__class__ = <class 'tensorflow.python.keras.engine.network.Network'>
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
name = None
self = <tensorflow.python.keras.engine.training.Model object at 0x7f603df18ac0>
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
allowed_kwargs = {'autocast', 'dtype', 'dynamic', 'trainable'}
error_message = 'Keyword argument not understood:'
def validate_kwargs(kwargs,
allowed_kwargs,
error_message='Keyword argument not understood:'):
"""Checks that all keyword arguments are in the set of allowed keys."""
for kwarg in kwargs:
if kwarg not in allowed_kwargs:
> raise TypeError(error_message, kwarg)
E TypeError: ('Keyword argument not understood:', 'input')
allowed_kwargs = {'autocast', 'dtype', 'dynamic', 'trainable'}
error_message = 'Keyword argument not understood:'
kwarg = 'input'
kwargs = {'input': [<tf.Tensor 'input_a_3:0' shape=(None, 1) dtype=int32>, <tf.Tensor 'input_b_3:0' shape=(None, 1) dtype=int32>], 'output': <tf.Tensor 'dot_3/Identity:0' shape=(None, 1, 1) dtype=float32>}
```
| [
{
"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2014 Radim Rehurek <radimrehurek@seznam.cz>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nRun with::\n\n python ./setup.py install\n\"\"\"\n\nimport distutils.cmd\nimport distutils.log\ni... | [
{
"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2014 Radim Rehurek <radimrehurek@seznam.cz>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nRun with::\n\n python ./setup.py install\n\"\"\"\n\nimport distutils.cmd\nimport distutils.log\ni... | diff --git a/gensim/test/test_keras_integration.py b/gensim/test/test_keras_integration.py
index bad0bb8b95..cc7af1892d 100644
--- a/gensim/test/test_keras_integration.py
+++ b/gensim/test/test_keras_integration.py
@@ -59,7 +59,7 @@ def testEmbeddingLayerCosineSim(self):
embedding_b = embedding_layer(input_b)
similarity = dot([embedding_a, embedding_b], axes=2, normalize=True)
- model = Model(input=[input_a, input_b], output=similarity)
+ model = Model(inputs=[input_a, input_b], outputs=similarity)
model.compile(optimizer='sgd', loss='mse')
word_a = 'graph'
diff --git a/setup.py b/setup.py
index b8545ab61d..38b7319f96 100644
--- a/setup.py
+++ b/setup.py
@@ -314,7 +314,7 @@ def run(self):
# See https://github.com/RaRe-Technologies/gensim/pull/2814#issuecomment-621477948
linux_testenv += [
'tensorflow',
- 'keras==2.3.1',
+ 'keras',
]
NUMPY_STR = 'numpy >= 1.11.3'
|
pallets__click-2544 | zsh completion requires pressing tab twice
```
❯ black --<TAB>
# Nothing will happen
❯ black --<TAB>
unsorted
--code Format the code passed in as a string.
...
# work after second time
```
Expected:
```
❯ black --<TAB>
unsorted
--code Format the code passed in as a string.
...
# work after first time
```
<details><summary>Original investigation</summary>
```zsh
❯ _BLACK_COMPLETE=zsh_source black
#compdef black
_black_completion() {
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[black] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) _BLACK_COMPLETE=zsh_complete black)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
}
compdef _black_completion black;
```
that is equivalent to
```zsh
_black() {
_black_completion() {
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[black] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) _BLACK_COMPLETE=zsh_complete black)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
}
compdef _black_completion black;
}
compdef _black black # because first line comment
```
So, in the first time, `compdef _black black` tell zsh the completion function is `_black()`, but `_black()` not return any completion items, only define a new function named `_black_completion` and `compdef _black_completion black`. So when the second time, it work.
The fix method is remove the nested function definition:
```zsh
❯ _BLACK_COMPLETE=zsh_source black
#compdef black
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[black] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) _BLACK_COMPLETE=zsh_complete black)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
```
</details>
| [
{
"content": "import os\nimport re\nimport typing as t\nfrom gettext import gettext as _\n\nfrom .core import Argument\nfrom .core import BaseCommand\nfrom .core import Context\nfrom .core import MultiCommand\nfrom .core import Option\nfrom .core import Parameter\nfrom .core import ParameterSource\nfrom .parser... | [
{
"content": "import os\nimport re\nimport typing as t\nfrom gettext import gettext as _\n\nfrom .core import Argument\nfrom .core import BaseCommand\nfrom .core import Context\nfrom .core import MultiCommand\nfrom .core import Option\nfrom .core import Parameter\nfrom .core import ParameterSource\nfrom .parser... | diff --git a/CHANGES.rst b/CHANGES.rst
index 76c234f6b..674e44901 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -17,6 +17,7 @@ Unreleased
- Improve responsiveness of ``click.clear()``. :issue:`2284`
- Improve command name detection when using Shiv or PEX. :issue:`2332`
- Avoid showing empty lines if command help text is empty. :issue:`2368`
+- ZSH completion script works when loaded from ``fpath``. :issue:`2344`.
Version 8.1.3
diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py
index bb3e48ec3..731be65c6 100644
--- a/src/click/shell_completion.py
+++ b/src/click/shell_completion.py
@@ -157,7 +157,13 @@ def __getattr__(self, name: str) -> t.Any:
fi
}
-compdef %(complete_func)s %(prog_name)s;
+if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
+ # autoload from fpath, call function directly
+ %(complete_func)s "$@"
+else
+ # eval/source/. command, register function for later
+ compdef %(complete_func)s %(prog_name)s
+fi
"""
_SOURCE_FISH = """\
|
dotkom__onlineweb4-2553 | Cant delete mails through REST API endpoints
The endpoint to remove mails are fucked :)
| [
{
"content": "from django.contrib.auth.models import Group\nfrom rest_framework import mixins, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom apps.authentication.models import ... | [
{
"content": "from django.contrib.auth.models import Group\nfrom rest_framework import mixins, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom apps.authentication.models import ... | diff --git a/apps/authentication/api/views.py b/apps/authentication/api/views.py
index fc27a3be1..59aab50a3 100644
--- a/apps/authentication/api/views.py
+++ b/apps/authentication/api/views.py
@@ -105,6 +105,7 @@ def destroy(self, request, *args, **kwargs):
},
status=status.HTTP_400_BAD_REQUEST,
)
+ super().destroy(request, *args, **kwargs)
class PositionViewSet(MultiSerializerMixin, viewsets.ModelViewSet):
|
pypa__pipenv-930 | Pipfile is not terminated by a newline
The Pipfile created by pipenv doesn't contain a trailing newline
##### Describe you environment
1. Mac OS Sierra (10.12.6)
1. Python version: I use pyenv, and I've tried this on 2.7.13 and 3.6.3. I doubt this is related to the Python version, but if you can't reproduce let me know and I'll investigate further.
1. pipenv version 8.2.7
##### Expected result
That the Pipfile would contain a trailing newline
##### Actual result
```
hobbes:pipenv-bug cdunklau$ pyenv version
3.6.3 (set by /Users/cdunklau/Development/pipenv-bug/.python-version)
hobbes:pipenv-bug cdunklau$ pyenv which pipenv
/Users/cdunklau/.pyenv/versions/3.6.3/bin/pipenv
hobbes:pipenv-bug cdunklau$ pipenv install --python 3.6.3
Creating a virtualenv for this project…
Using /Users/cdunklau/.pyenv/versions/3.6.3/bin/python3.6m to create virtualenv…
⠋Running virtualenv with interpreter /Users/cdunklau/.pyenv/versions/3.6.3/bin/python3.6m
Using base prefix '/Users/cdunklau/.pyenv/versions/3.6.3'
New python executable in /Users/cdunklau/.local/share/virtualenvs/pipenv-bug-1HVkXapj/bin/python3.6m
Also creating executable in /Users/cdunklau/.local/share/virtualenvs/pipenv-bug-1HVkXapj/bin/python
Installing setuptools, pip, wheel...done.
Virtualenv location: /Users/cdunklau/.local/share/virtualenvs/pipenv-bug-1HVkXapj
Creating a Pipfile for this project…
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (625834)!
Installing dependencies from Pipfile.lock (625834)…
🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00
To activate this project's virtualenv, run the following:
$ pipenv shell
hobbes:pipenv-bug cdunklau$ cat Pipfile
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
[dev-packages]
[requires]
python_version = "3.6"hobbes:pipenv-bug cdunklau$
hobbes:pipenv-bug cdunklau$ hexdump -C Pipfile
00000000 5b 5b 73 6f 75 72 63 65 5d 5d 0a 0a 75 72 6c 20 |[[source]]..url |
00000010 3d 20 22 68 74 74 70 73 3a 2f 2f 70 79 70 69 2e |= "https://pypi.|
00000020 70 79 74 68 6f 6e 2e 6f 72 67 2f 73 69 6d 70 6c |python.org/simpl|
00000030 65 22 0a 76 65 72 69 66 79 5f 73 73 6c 20 3d 20 |e".verify_ssl = |
00000040 74 72 75 65 0a 6e 61 6d 65 20 3d 20 22 70 79 70 |true.name = "pyp|
00000050 69 22 0a 0a 0a 5b 70 61 63 6b 61 67 65 73 5d 0a |i"...[packages].|
00000060 0a 0a 0a 5b 64 65 76 2d 70 61 63 6b 61 67 65 73 |...[dev-packages|
00000070 5d 0a 0a 0a 0a 5b 72 65 71 75 69 72 65 73 5d 0a |]....[requires].|
00000080 0a 70 79 74 68 6f 6e 5f 76 65 72 73 69 6f 6e 20 |.python_version |
00000090 3d 20 22 33 2e 36 22 |= "3.6"|
00000097
hobbes:pipenv-bug cdunklau$
```
##### Steps to replicate
```
pipenv install
cat Pipfile
```
| [
{
"content": "# -*- coding: utf-8 -*-\nimport os\nimport hashlib\nimport tempfile\nimport sys\nimport shutil\nimport logging\n\nimport click\nimport crayons\nimport delegator\nimport pip\nimport parse\nimport requirements\nimport fuzzywuzzy.process\nimport requests\nimport six\n\nlogging.basicConfig(level=loggi... | [
{
"content": "# -*- coding: utf-8 -*-\nimport os\nimport hashlib\nimport tempfile\nimport sys\nimport shutil\nimport logging\n\nimport click\nimport crayons\nimport delegator\nimport pip\nimport parse\nimport requirements\nimport fuzzywuzzy.process\nimport requests\nimport six\n\nlogging.basicConfig(level=loggi... | diff --git a/pipenv/utils.py b/pipenv/utils.py
index bb118b7cc1..bf99cdd578 100644
--- a/pipenv/utils.py
+++ b/pipenv/utils.py
@@ -290,7 +290,9 @@ def cleanup_toml(tml):
# Insert a newline after the heading.
if after:
new_toml.append('')
-
+
+ # adding new line at the end of the TOML file
+ new_toml.append('')
toml = '\n'.join(new_toml)
return toml
diff --git a/tests/test_utils.py b/tests/test_utils.py
index b094a34658..4922d2949b 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -186,3 +186,21 @@ def test_download_file(self):
pipenv.utils.download_file(url, output)
assert os.path.exists(output)
os.remove(output)
+
+ def test_new_line_end_of_toml_file(this):
+ # toml file that needs clean up
+ toml = """
+[dev-packages]
+
+"flake8" = ">=3.3.0,<4"
+pytest = "*"
+mock = "*"
+sphinx = "<=1.5.5"
+"-e ." = "*"
+twine = "*"
+"sphinx-click" = "*"
+"pytest-xdist" = "*"
+ """
+ new_toml = pipenv.utils.cleanup_toml(toml)
+ # testing if the end of the generated file contains a newline
+ assert new_toml[-1] == '\n'
|
benoitc__gunicorn-1806 | I get error in this package AttributeError: 'NoneType' object has no attribute 'add_extra_file'
hi every one ..
when i try to deploy keras model into google cloud i get this error ...
```py
File "/home/falahgs07/keras/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/home/falahgs07/keras/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 148, in load_wsgi
self.reloader.add_extra_file(exc_val.filename)
AttributeError: 'NoneType' object has no attribute 'add_extra_file'
```
| [
{
"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nfrom datetime import datetime\nimport os\nfrom random import randint\nimport signal\nfrom ssl import SSLError\nimport sys\nimport time\nimport traceback\n\nfrom guni... | [
{
"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nfrom datetime import datetime\nimport os\nfrom random import randint\nimport signal\nfrom ssl import SSLError\nimport sys\nimport time\nimport traceback\n\nfrom guni... | diff --git a/docs/source/news.rst b/docs/source/news.rst
index 3d90aead2..8f61b9c87 100644
--- a/docs/source/news.rst
+++ b/docs/source/news.rst
@@ -2,6 +2,13 @@
Changelog
=========
+19.x / not released
+===================
+
+- fix: prevent raising :exc:`AttributeError` when ``--reload`` is not passed
+ in case of a :exc:`SyntaxError` raised from the WSGI application.
+ (:issue:`1805`, :pr:`1806`)
+
19.8.1 / 2018/04/30
===================
diff --git a/gunicorn/workers/base.py b/gunicorn/workers/base.py
index ce40796f5..881efa0f0 100644
--- a/gunicorn/workers/base.py
+++ b/gunicorn/workers/base.py
@@ -137,7 +137,7 @@ def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
- if self.cfg.reload == 'off':
+ if not self.cfg.reload:
raise
self.log.exception(e)
|
frappe__frappe-16129 | no_copy option not available in customize form field
<!--
Welcome to the Frappe Framework issue tracker! Before creating an issue, please heed the following:
1. This tracker should only be used to report bugs and request features / enhancements to Frappe
- For questions and general support, use https://stackoverflow.com/questions/tagged/frappe
- For documentation issues, refer to https://frappeframework.com/docs/user/en or the developer cheetsheet https://github.com/frappe/frappe/wiki/Developer-Cheatsheet
2. Use the search function before creating a new issue. Duplicates will be closed and directed to
the original discussion.
3. When making a bug report, make sure you provide all required information. The easier it is for
maintainers to reproduce, the faster it'll be fixed.
4. If you think you know what the reason for the bug is, share it with us. Maybe put in a PR 😉
-->
## Description of the issue
## Context information (for bug reports)
**Output of `bench version`**
```
(paste here)
```
## Steps to reproduce the issue
1.
2.
3.
### Observed result
no copy is a field property in doctype, but in customize form, the no copy option is not available for the field.
### Expected result
make no copy as available property of the field in customize form
### Stacktrace / full error message
```
(paste here)
```
## Additional information
OS version / distribution, `Frappe` install method, etc.
no_copy option not available in customize form field
<!--
Welcome to the Frappe Framework issue tracker! Before creating an issue, please heed the following:
1. This tracker should only be used to report bugs and request features / enhancements to Frappe
- For questions and general support, use https://stackoverflow.com/questions/tagged/frappe
- For documentation issues, refer to https://frappeframework.com/docs/user/en or the developer cheetsheet https://github.com/frappe/frappe/wiki/Developer-Cheatsheet
2. Use the search function before creating a new issue. Duplicates will be closed and directed to
the original discussion.
3. When making a bug report, make sure you provide all required information. The easier it is for
maintainers to reproduce, the faster it'll be fixed.
4. If you think you know what the reason for the bug is, share it with us. Maybe put in a PR 😉
-->
## Description of the issue
## Context information (for bug reports)
**Output of `bench version`**
```
(paste here)
```
## Steps to reproduce the issue
1.
2.
3.
### Observed result
no copy is a field property in doctype, but in customize form, the no copy option is not available for the field.
### Expected result
make no copy as available property of the field in customize form
### Stacktrace / full error message
```
(paste here)
```
## Additional information
OS version / distribution, `Frappe` install method, etc.
| [
{
"content": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\n\"\"\"\n\tCustomize Form is a Single DocType used to mask the Property Setter\n\tThus providing a better UI from user perspective\n\"\"\"\nimport json\ni... | [
{
"content": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\n\"\"\"\n\tCustomize Form is a Single DocType used to mask the Property Setter\n\tThus providing a better UI from user perspective\n\"\"\"\nimport json\ni... | diff --git a/frappe/custom/doctype/customize_form/customize_form.py b/frappe/custom/doctype/customize_form/customize_form.py
index 53626a75217b..faa8e74c2feb 100644
--- a/frappe/custom/doctype/customize_form/customize_form.py
+++ b/frappe/custom/doctype/customize_form/customize_form.py
@@ -533,6 +533,7 @@ def reset_customization(doctype):
'in_global_search': 'Check',
'in_preview': 'Check',
'bold': 'Check',
+ 'no_copy': 'Check',
'hidden': 'Check',
'collapsible': 'Check',
'collapsible_depends_on': 'Data',
diff --git a/frappe/custom/doctype/customize_form/test_customize_form.py b/frappe/custom/doctype/customize_form/test_customize_form.py
index 7d87fd0f4c4f..1aa33e7ce90a 100644
--- a/frappe/custom/doctype/customize_form/test_customize_form.py
+++ b/frappe/custom/doctype/customize_form/test_customize_form.py
@@ -98,13 +98,17 @@ def test_save_customization_custom_field_property(self):
custom_field = d.get("fields", {"fieldname": "test_custom_field"})[0]
custom_field.reqd = 1
+ custom_field.no_copy = 1
d.run_method("save_customization")
- self.assertEquals(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 1)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 1)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "no_copy"), 1)
custom_field = d.get("fields", {"is_custom_field": True})[0]
custom_field.reqd = 0
+ custom_field.no_copy = 0
d.run_method("save_customization")
- self.assertEquals(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 0)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "reqd"), 0)
+ self.assertEqual(frappe.db.get_value("Custom Field", "Event-test_custom_field", "no_copy"), 0)
def test_save_customization_new_field(self):
d = self.get_customize_form("Event")
diff --git a/frappe/custom/doctype/customize_form_field/customize_form_field.json b/frappe/custom/doctype/customize_form_field/customize_form_field.json
index 0a456b102605..9b2986d9e620 100644
--- a/frappe/custom/doctype/customize_form_field/customize_form_field.json
+++ b/frappe/custom/doctype/customize_form_field/customize_form_field.json
@@ -19,6 +19,7 @@
"in_global_search",
"in_preview",
"bold",
+ "no_copy",
"allow_in_quick_entry",
"translatable",
"column_break_7",
@@ -422,13 +423,19 @@
"fieldname": "non_negative",
"fieldtype": "Check",
"label": "Non Negative"
+ },
+ {
+ "default": "0",
+ "fieldname": "no_copy",
+ "fieldtype": "Check",
+ "label": "No Copy"
}
],
"idx": 1,
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-07-10 21:57:24.479749",
+ "modified": "2022-02-08 19:38:16.111199",
"modified_by": "Administrator",
"module": "Custom",
"name": "Customize Form Field",
@@ -436,4 +443,4 @@
"permissions": [],
"sort_field": "modified",
"sort_order": "ASC"
-}
\ No newline at end of file
+}
|
carltongibson__django-filter-568 | Import of rest_framework backend can fail
In the DRF docs, they give an example which looks like:
```
import django_filters
# ...
class ProductFilter(django_filters.rest_framework.FilterSet):
# ...
```
This does not work, however, with the way the `django_filters/__init__.py` is set up. Using this example, I get:
`AttributeError: 'module' object has no attribute 'rest_framework'`
I have found a fix for it, by adding the following to `django_filters/__init__.py`:
`from . import rest_framework`
| [
{
"content": "# flake8: noqa\nfrom __future__ import absolute_import\nfrom .constants import STRICTNESS\nfrom .filterset import FilterSet\nfrom .filters import *\n\n__version__ = '1.0.0'\n\n\ndef parse_version(version):\n '''\n '0.1.2-dev' -> (0, 1, 2, 'dev')\n '0.1.2' -> (0, 1, 2)\n '''\n v = ve... | [
{
"content": "# flake8: noqa\nfrom __future__ import absolute_import\nfrom .constants import STRICTNESS\nfrom .filterset import FilterSet\nfrom .filters import *\n\n# We make the `rest_framework` module available without an additional import.\n# If DRF is not installed we simply set None.\ntry:\n from . im... | diff --git a/django_filters/__init__.py b/django_filters/__init__.py
index 6f2400721..b9f928131 100644
--- a/django_filters/__init__.py
+++ b/django_filters/__init__.py
@@ -4,6 +4,13 @@
from .filterset import FilterSet
from .filters import *
+# We make the `rest_framework` module available without an additional import.
+# If DRF is not installed we simply set None.
+try:
+ from . import rest_framework
+except ImportError:
+ rest_framework = None
+
__version__ = '1.0.0'
|
ivy-llc__ivy-13273 | unravel_index
| [
{
"content": "# local\nimport ivy\nfrom ivy.functional.frontends.jax.func_wrapper import (\n to_ivy_arrays_and_back,\n)\n\n\n@to_ivy_arrays_and_back\ndef diagonal(a, offset=0, axis1=0, axis2=1):\n return ivy.diagonal(a, offset=offset, axis1=axis1, axis2=axis2)\n\n\n@to_ivy_arrays_and_back\ndef diag(v, k=0... | [
{
"content": "# local\nimport ivy\nfrom ivy.functional.frontends.jax.func_wrapper import (\n to_ivy_arrays_and_back,\n)\n\n\n@to_ivy_arrays_and_back\ndef diagonal(a, offset=0, axis1=0, axis2=1):\n return ivy.diagonal(a, offset=offset, axis1=axis1, axis2=axis2)\n\n\n@to_ivy_arrays_and_back\ndef diag(v, k=0... | diff --git a/ivy/functional/frontends/jax/numpy/indexing.py b/ivy/functional/frontends/jax/numpy/indexing.py
index 10df7c6e7d956..0594d21259f97 100644
--- a/ivy/functional/frontends/jax/numpy/indexing.py
+++ b/ivy/functional/frontends/jax/numpy/indexing.py
@@ -44,3 +44,10 @@ def triu_indices_from(arr, k=0):
def tril_indices_from(arr, k=0):
return ivy.tril_indices(arr.shape[-2], arr.shape[-1], k)
+
+
+# unravel_index
+@to_ivy_arrays_and_back
+def unravel_index(indices, shape):
+ ret = [x.astype("int64") for x in ivy.unravel_index(indices, shape)]
+ return tuple(ret)
diff --git a/ivy_tests/test_ivy/test_frontends/test_jax/test_jax_numpy_indexing.py b/ivy_tests/test_ivy/test_frontends/test_jax/test_jax_numpy_indexing.py
index d3a6a9025b487..9817ca2a0589e 100644
--- a/ivy_tests/test_ivy/test_frontends/test_jax/test_jax_numpy_indexing.py
+++ b/ivy_tests/test_ivy/test_frontends/test_jax/test_jax_numpy_indexing.py
@@ -293,3 +293,48 @@ def test_jax_numpy_tril_indices_from(
arr=x[0],
k=k,
)
+
+
+# unravel_index
+@st.composite
+def max_value_as_shape_prod(draw):
+ shape = draw(
+ helpers.get_shape(
+ min_num_dims=1,
+ max_num_dims=5,
+ min_dim_size=1,
+ max_dim_size=5,
+ )
+ )
+ dtype_and_x = draw(
+ helpers.dtype_values_axis(
+ available_dtypes=["int32", "int64"],
+ min_value=0,
+ max_value=np.prod(shape) - 1,
+ )
+ )
+ return dtype_and_x, shape
+@handle_frontend_test(
+ fn_tree="jax.numpy.unravel_index",
+ dtype_x_shape=max_value_as_shape_prod(),
+ test_with_out=st.just(False),
+)
+def test_jax_numpy_unravel_index(
+ *,
+ dtype_x_shape,
+ test_flags,
+ frontend,
+ fn_tree,
+ on_device,
+):
+ dtype_and_x, shape = dtype_x_shape
+ input_dtype, x = dtype_and_x[0], dtype_and_x[1]
+ helpers.test_frontend_function(
+ input_dtypes=input_dtype,
+ test_flags=test_flags,
+ frontend=frontend,
+ fn_tree=fn_tree,
+ on_device=on_device,
+ indices=x[0],
+ shape=shape,
+ )
|
deeppavlov__DeepPavlov-76 | What is "'Chainer' object has no attribute 'infer'
2018-03-04 14:09:23,638 (util.py:64 WorkerThread2) ERROR - TeleBot: "AttributeError occurred, args=("'Chainer' object has no attribute 'infer'",)
Traceback (most recent call last):
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/util.py", line 58, in run
task(*args, **kwargs)
File "/Users/developer/Project/DeepPavlov/telegram_utils/telegram_ui.py", line 48, in handle_inference
pred = model.infer(context)
AttributeError: 'Chainer' object has no attribute 'infer'
"
2018-03-04 14:09:23.638 ERROR in 'TeleBot'['util'] at line 64: AttributeError occurred, args=("'Chainer' object has no attribute 'infer'",)
Traceback (most recent call last):
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/util.py", line 58, in run
task(*args, **kwargs)
File "/Users/developer/Project/DeepPavlov/telegram_utils/telegram_ui.py", line 48, in handle_inference
pred = model.infer(context)
AttributeError: 'Chainer' object has no attribute 'infer'
Traceback (most recent call last):
File "deep.py", line 60, in <module>
main()
File "deep.py", line 56, in main
interact_model_by_telegram(pipeline_config_path, token)
File "/Users/developer/Project/DeepPavlov/telegram_utils/telegram_ui.py", line 58, in interact_model_by_telegram
init_bot_for_model(token, model)
File "/Users/developer/Project/DeepPavlov/telegram_utils/telegram_ui.py", line 52, in init_bot_for_model
bot.polling()
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/__init__.py", line 264, in polling
self.__threaded_polling(none_stop, interval, timeout)
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/__init__.py", line 288, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/util.py", line 107, in raise_exceptions
six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/six.py", line 693, in reraise
raise value
File "/Users/developer/DeepPavlov/lib/python3.6/site-packages/telebot/util.py", line 58, in run
task(*args, **kwargs)
File "/Users/developer/Project/DeepPavlov/telegram_utils/telegram_ui.py", line 48, in handle_inference
pred = model.infer(context)
AttributeError: 'Chainer' object has no attribute 'infer'
| [
{
"content": "\"\"\"\nCopyright 2017 Neural Networks and Deep Learning lab, MIPT\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUn... | [
{
"content": "\"\"\"\nCopyright 2017 Neural Networks and Deep Learning lab, MIPT\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUn... | diff --git a/telegram_utils/telegram_ui.py b/telegram_utils/telegram_ui.py
index 3841847438..1606180af6 100644
--- a/telegram_utils/telegram_ui.py
+++ b/telegram_utils/telegram_ui.py
@@ -45,7 +45,7 @@ def handle_inference(message):
chat_id = message.chat.id
context = message.text
- pred = model.infer(context)
+ pred = model(context)
reply_message = str(pred)
bot.send_message(chat_id, reply_message)
|
microsoft__botbuilder-python-2057 | 4.14.6 CloudAdapter fails to send Typing Activity in Teams
## Version
botbuilder-core 4.14.6
botbuilder-integration-aiohttp 4.14.6
botbuilder-schema 4.14.6
## Describe the bug
I am unable to send typing indicators with the `ShowTypingMiddleware` middleware, `turn_context.send_activity`, and
`turn_context.send_activities`.
## To Reproduce
Create a bot
```
cfg = DefaultConfig()
adapter = CloudAdapter(ConfigurationBotFrameworkAuthentication(cfg))
bot = Bot()
```
define on_message_activity
[From documentation](https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-send-messages?view=azure-bot-service-4.0&tabs=python)
```
async def on_message_activity(self, turn_context: TurnContext): # pylint: disable=unused-argument
if turn_context.activity.text == "wait":
return await turn_context.send_activities([
Activity(
type=ActivityTypes.typing
),
Activity(
type="delay",
value=3000
),
Activity(
type=ActivityTypes.message,
text="Finished Typing"
)
])
else:
return await turn_context.send_activity(
f"You said {turn_context.activity.text}. Say 'wait' to watch me type."
)
```
Publish in azure, set up MS Teams channel.
send 'wait' via Microsoft Teams
stacktrace:
```
Traceback (most recent call last):
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/bot_adapter.py", line 174, in run_pipeline
return await self._middleware.receive_activity_with_status(
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/middleware_set.py", line 69, in receive_activity_with_status
return await self.receive_activity_internal(context, callback)
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/middleware_set.py", line 79, in receive_activity_internal
return await callback(context)
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/activity_handler.py", line 70, in on_turn
await self.on_message_activity(turn_context)
File "/home/josh/ctrlstack/babelfish/askbot/microsoft-teams/src/bot.py", line 78, in on_message_activity
return await turn_context.send_activities([
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/turn_context.py", line 225, in send_activities
return await self._emit(self._on_send_activities, output, logic())
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/turn_context.py", line 303, in _emit
return await logic
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/turn_context.py", line 220, in logic
responses = await self.adapter.send_activities(self, output)
File "path-to-virtual-env/lib/python3.10/site-packages/botbuilder/core/cloud_adapter_base.py", line 103, in send_activities
response = response or ResourceResponse(activity.id or "")
```
## Expected behavior
the typing indicator for 3 seconds.
| [
{
"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nfrom abc import ABC\nfrom asyncio import sleep\nfrom copy import Error\nfrom http import HTTPStatus\nfrom typing import Awaitable, Callable, List, Union\nfrom uuid import uuid4\n\nfrom botbuilder.core... | [
{
"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nfrom abc import ABC\nfrom asyncio import sleep\nfrom copy import Error\nfrom http import HTTPStatus\nfrom typing import Awaitable, Callable, List, Union\nfrom uuid import uuid4\n\nfrom botbuilder.core... | diff --git a/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py b/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
index c5eda9589..7e996c90c 100644
--- a/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
+++ b/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
@@ -100,7 +100,7 @@ async def send_activities(
)
)
- response = response or ResourceResponse(activity.id or "")
+ response = response or ResourceResponse(id=activity.id or "")
responses.append(response)
diff --git a/libraries/botbuilder-core/tests/simple_adapter.py b/libraries/botbuilder-core/tests/simple_adapter.py
index ae68dc323..2ba3f31b8 100644
--- a/libraries/botbuilder-core/tests/simple_adapter.py
+++ b/libraries/botbuilder-core/tests/simple_adapter.py
@@ -75,7 +75,7 @@ async def update_activity(self, context: TurnContext, activity: Activity):
if self._call_on_update is not None:
self._call_on_update(activity)
- return ResourceResponse(activity.id)
+ return ResourceResponse(id=activity.id)
async def process_request(self, activity, handler):
context = TurnContext(self, activity)
diff --git a/libraries/botbuilder-core/tests/teams/simple_adapter_with_create_conversation.py b/libraries/botbuilder-core/tests/teams/simple_adapter_with_create_conversation.py
index d1801d978..cacfbd5ed 100644
--- a/libraries/botbuilder-core/tests/teams/simple_adapter_with_create_conversation.py
+++ b/libraries/botbuilder-core/tests/teams/simple_adapter_with_create_conversation.py
@@ -76,7 +76,7 @@ async def update_activity(self, context: TurnContext, activity: Activity):
if self._call_on_update is not None:
self._call_on_update(activity)
- return ResourceResponse(activity.id)
+ return ResourceResponse(id=activity.id)
async def process_request(self, activity, handler):
context = TurnContext(self, activity)
|
sunpy__sunpy-1365 | JSOC download skips first file in Results object
| [
{
"content": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import\n\nimport os\nimport time\nimport urlparse\nimport warnings\n\nimport requests\nimport numpy as np\nimport astropy.units as u\nimport astropy.time\nimport astropy.table\n\nfrom sunpy import config\nfrom sunpy.time impo... | [
{
"content": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import\n\nimport os\nimport time\nimport urlparse\nimport warnings\n\nimport requests\nimport numpy as np\nimport astropy.units as u\nimport astropy.time\nimport astropy.table\n\nfrom sunpy import config\nfrom sunpy.time impo... | diff --git a/sunpy/net/jsoc/jsoc.py b/sunpy/net/jsoc/jsoc.py
index 494e2f3e311..0c39fbf6414 100644
--- a/sunpy/net/jsoc/jsoc.py
+++ b/sunpy/net/jsoc/jsoc.py
@@ -423,8 +423,8 @@ def get_request(self, requestIDs, path=None, overwrite=False, progress=True,
else:
#Make Results think it has finished.
results.require([])
+ results.poke()
- results.poke()
return results
def _process_time(self, time):
diff --git a/sunpy/net/jsoc/tests/test_jsoc.py b/sunpy/net/jsoc/tests/test_jsoc.py
index af1bcb721b0..8cdb4405ab1 100644
--- a/sunpy/net/jsoc/tests/test_jsoc.py
+++ b/sunpy/net/jsoc/tests/test_jsoc.py
@@ -212,7 +212,6 @@ def test_get_request():
assert isinstance(aa, Results)
@pytest.mark.online
-@pytest.mark.xfail
def test_results_filenames():
responses = client.query(attrs.Time('2014/1/1T1:00:36', '2014/1/1T01:01:38'),
attrs.Series('hmi.M_45s'), attrs.Notify('jsoc@cadair.com'))
|
open-telemetry__opentelemetry-python-contrib-1515 | Add readthedocs documentation for remoulade instrumentation
Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
| [
{
"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/instrumentation/remoulade/remoulade.rst b/docs/instrumentation/remoulade/remoulade.rst
new file mode 100644
index 0000000000..bc5a7da42c
--- /dev/null
+++ b/docs/instrumentation/remoulade/remoulade.rst
@@ -0,0 +1,7 @@
+.. include:: ../../../instrumentation/opentelemetry-instrumentation-remoulade/README.rst
+
+
+.. automodule:: opentelemetry.instrumentation.remoulade
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py b/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py
index c9e53d92df..87a26585fc 100644
--- a/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py
+++ b/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py
@@ -16,13 +16,13 @@
Usage
-----
-* Start broker backend
+Start broker backend
::
docker run -p 5672:5672 rabbitmq
-* Run instrumented actor
+Run instrumented actor
.. code-block:: python
|
frappe__frappe-23585 | Route History shouldn‘t be editable
Editing or adding a new Route History:


… shouldn’t be possible, not even for the Administrator.
| [
{
"content": "# Copyright (c) 2022, Frappe Technologies and contributors\n# License: MIT. See LICENSE\n\nimport frappe\nfrom frappe.deferred_insert import deferred_insert as _deferred_insert\nfrom frappe.model.document import Document\n\n\nclass RouteHistory(Document):\n\t# begin: auto-generated types\n\t# This... | [
{
"content": "# Copyright (c) 2022, Frappe Technologies and contributors\n# License: MIT. See LICENSE\n\nimport frappe\nfrom frappe.deferred_insert import deferred_insert as _deferred_insert\nfrom frappe.model.document import Document\n\n\nclass RouteHistory(Document):\n\t# begin: auto-generated types\n\t# This... | diff --git a/frappe/desk/doctype/route_history/route_history.json b/frappe/desk/doctype/route_history/route_history.json
index a5d73fc360d2..0b96277431da 100644
--- a/frappe/desk/doctype/route_history/route_history.json
+++ b/frappe/desk/doctype/route_history/route_history.json
@@ -1,5 +1,6 @@
{
"actions": [],
+ "allow_copy": 1,
"creation": "2018-10-05 11:26:04.601113",
"doctype": "DocType",
"editable_grid": 1,
@@ -13,7 +14,9 @@
"fieldname": "route",
"fieldtype": "Data",
"in_list_view": 1,
- "label": "Route"
+ "label": "Route",
+ "no_copy": 1,
+ "read_only": 1
},
{
"fieldname": "user",
@@ -21,30 +24,29 @@
"in_list_view": 1,
"in_standard_filter": 1,
"label": "User",
- "options": "User"
+ "no_copy": 1,
+ "options": "User",
+ "read_only": 1
}
],
+ "in_create": 1,
"links": [],
- "modified": "2022-06-13 05:48:56.967244",
+ "modified": "2023-12-04 04:41:32.448331",
"modified_by": "Administrator",
"module": "Desk",
"name": "Route History",
"owner": "Administrator",
"permissions": [
{
- "create": 1,
- "delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
- "share": 1,
- "write": 1
+ "share": 1
}
],
- "quick_entry": 1,
"sort_field": "modified",
"sort_order": "DESC",
"states": [],
diff --git a/frappe/desk/doctype/route_history/route_history.py b/frappe/desk/doctype/route_history/route_history.py
index 9aba975c3a87..5c0c37d4a731 100644
--- a/frappe/desk/doctype/route_history/route_history.py
+++ b/frappe/desk/doctype/route_history/route_history.py
@@ -18,6 +18,7 @@ class RouteHistory(Document):
route: DF.Data | None
user: DF.Link | None
# end: auto-generated types
+
@staticmethod
def clear_old_logs(days=30):
from frappe.query_builder import Interval
|
akvo__akvo-rsr-2158 | Improve IATI export
## Test plan
Before starting with testing, make sure to perform two one-time actions:
- The `iati_export` cron job is running (done on Test and UAT)
- See running cron jobs by running: `manage.py crontab show`;
- The `perform_iati_checks` management command has been run (done on Test and UAT).
---
GIVEN the 'My IATI' section in MyRSR
WHEN connected to multiple organisations (or as superuser)
THEN an organisation selection screen should be shown
WHEN connected to one organisation
THEN this organisation should be automatically selected
GIVEN the 'My IATI' section in MyRSR
WHEN an organisation has been selected
THEN the overview of all IATI exports should be shown
AND for each export the status, number of projects, created by, created at and IATI version should be shown
AND the latest IATI export should be shown in a green row
AND a pending or in progress IATI export should be shown in a yellow row
AND a cancelled or export without an IATI file should be shown in a red row
GIVEN the 'My IATI' section in MyRSR
WHEN an organisation has been selected
THEN it should be possible to select whether the latest IATI file is shown on the organisation page
GIVEN that is has been set that the latest IATI file is shown on the organisation page
THEN it should be shown on the organisation page as well
ELSE the IATI file should not be shown
GIVEN that the 'Add new IATI export' button is clicked
THEN the user should be redirected to the project selection overview
GIVEN the project selection overview
WHEN looking at the projects overview
THEN all projects where the selected organisation is reporting organisation should be shown
GIVEN the project selection overview
WHEN applying a filter
THEN the project selection should change
AND the indication of the number of projects selected should indicate the number of selected projects
GIVEN the project selection overview
WHEN projects are selected AND the 'create new IATI export' button is clicked
THEN the user should be redirected to the IATI exports overview
AND the top IATI export should be the new IATI export (with 'Pending' status)
GIVEN the IATI export overview
WHEN an export is pending or in progress
THEN the overview should be refreshed every 10 seconds
AND when an export is in progress, the number of processed projects should be shown
## Issue description
Currently, an IATI export with more than 70 projects will give a DB timeout. However, we need to be able to export an IATI file with any amount of projects. Similar to the IATI import, we can use a cron job for this.
- [x] Move IATI export to a cron job implementation
- [x] Update the 'My IATI' tab in MyRSR
| [
{
"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\nimport re... | [
{
"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\nimport re... | diff --git a/akvo/rsr/feeds.py b/akvo/rsr/feeds.py
index bc7e5802c2..4d95fde643 100644
--- a/akvo/rsr/feeds.py
+++ b/akvo/rsr/feeds.py
@@ -227,7 +227,7 @@ def description(self, obj):
def items(self, obj):
# Limited to 25 items to prevent gateway timeouts.
- return obj.published_projects().all_updates()[:25]
+ return obj.all_updates()[:25]
def item_title(self, item):
return _(
diff --git a/akvo/rsr/static/scripts-src/my-iati.js b/akvo/rsr/static/scripts-src/my-iati.js
index b2ddeecb0b..c70e835948 100644
--- a/akvo/rsr/static/scripts-src/my-iati.js
+++ b/akvo/rsr/static/scripts-src/my-iati.js
@@ -327,7 +327,7 @@ function loadComponents() {
onclickAll;
if (this.props.projects.length > 0) {
- // In case there are projets, show a table overview of the projects.
+ // In case there are projects, show a table overview of the projects.
checked = this.props.projects.length === this.props.selectedProjects.length;
onclickAll = checked ? this.props.deselectAll : this.props.selectAll;
projects = this.sortedProjects().map(function(project) {
@@ -384,7 +384,10 @@ function loadComponents() {
selectedProjects: [],
lastExport: null,
publishedFilter: false,
- exporting: false
+ exporting: false,
+ noErrorsChecked: false,
+ previousChecked: false,
+ publishedChecked: false
};
},
@@ -427,6 +430,7 @@ function loadComponents() {
if (projectIndex > -1) {
newSelection.splice(projectIndex, 1);
+ this.checkUnchecked();
} else {
newSelection.push(projectId);
}
@@ -451,6 +455,27 @@ function loadComponents() {
apiCall('POST', url, data, true, exportAdded);
},
+ checkUnchecked: function() {
+ // A check whether the filters should be unchecked (after deselecting a project,
+ // for instance).
+ var selection = this.state.selectedProjects,
+ allProjects = this.state.allProjects.results,
+ lastProjects = this.state.lastExport[0].projects;
+
+ for (var i = 0; i < allProjects.length; i++) {
+ var project = allProjects[i];
+ if (project.checks_errors.length === 0 && selection.indexOf(project.id) < 0) {
+ this.setState({noErrorsChecked: false});
+ }
+ if (lastProjects.indexOf(project.id) > -1 && selection.indexOf(project.id) < 0) {
+ this.setState({previousChecked: false});
+ }
+ if (project.publishing_status === 'published' && selection.indexOf(project.id) < 0) {
+ this.setState({publishedChecked: false});
+ }
+ }
+ },
+
selectNoErrors: function(select) {
var newSelection = this.state.selectedProjects;
@@ -467,14 +492,6 @@ function loadComponents() {
this.setState({selectedProjects: newSelection});
},
- selectNoErrorsProjects: function() {
- this.selectNoErrors(true);
- },
-
- deselectNoErrorsProjects: function() {
- this.selectNoErrors(false);
- },
-
checkNoErrors: function() {
var noErrorsCount = 0;
@@ -488,15 +505,14 @@ function loadComponents() {
return noErrorsCount;
},
- allNoErrorsSelected: function() {
- for (var i = 0; i < this.state.allProjects.results.length; i++) {
- var project = this.state.allProjects.results[i];
-
- if (project.checks_errors.length === 0 && this.state.selectedProjects.indexOf(project.id) < 0) {
- return false;
- }
+ clickNoErrorsProjects: function() {
+ var previousState = this.state.noErrorsChecked;
+ this.setState({noErrorsChecked: !previousState});
+ if (previousState) {
+ this.selectNoErrors(false);
+ } else {
+ this.selectNoErrors(true);
}
- return true;
},
renderNoErrorsButton: function() {
@@ -504,34 +520,77 @@ function loadComponents() {
return (
React.DOM.span(null )
);
- } else if (this.allNoErrorsSelected()) {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm"},
- React.DOM.input( {type:"checkbox", checked:true, onClick:this.deselectNoErrorsProjects} ), " ", cap(i18n.without_errors)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:true} ), " ", cap(i18n.without_errors)
- )
- );
+ } else {
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
+ }
+
+ return (
+ React.DOM.button( {className:buttonClass, onClick:this.clickNoErrorsProjects} ,
+ React.DOM.input( {type:"checkbox", checked:this.state.noErrorsChecked} ), " ", cap(i18n.without_errors)
+ )
+ );
+ }
+ },
+
+ selectPublished: function(select) {
+ var newSelection = this.state.selectedProjects;
+
+ for (var i = 0; i < this.state.allProjects.results.length; i++) {
+ var project = this.state.allProjects.results[i],
+ newSelectionIndex = newSelection.indexOf(project.id);
+ if (select && newSelectionIndex < 0 && project.publishing_status === 'published') {
+ newSelection.push(project.id);
+ } else if (!select && newSelectionIndex > -1 && project.publishing_status === 'published') {
+ newSelection.splice(newSelectionIndex, 1);
+ }
+ }
+
+ this.setState({selectedProjects: newSelection});
+ },
+
+ checkPublished: function() {
+ var noErrorsCount = 0;
+
+ for (var i = 0; i < this.state.allProjects.results.length; i++) {
+ var project = this.state.allProjects.results[i];
+ if (project.publishing_status === 'published') {
+ return true;
}
+ }
+
+ return false;
+ },
+
+ clickPublishedProjects: function() {
+ var previousState = this.state.publishedChecked;
+ this.setState({publishedChecked: !previousState});
+ if (previousState) {
+ this.selectPublished(false);
} else {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm"},
- React.DOM.input( {type:"checkbox", checked:false, onClick:this.selectNoErrorsProjects} ), " ", cap(i18n.without_errors)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:false} ), " ", cap(i18n.without_errors)
- )
- );
+ this.selectPublished(true);
+ }
+ },
+
+ renderPublishedButton: function() {
+ if (this.state.allProjects === null || this.state.allProjects.results.length === 0 || !this.checkPublished()) {
+ return (
+ React.DOM.span(null )
+ );
+ } else {
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
}
+
+ return (
+ React.DOM.button( {className:buttonClass, onClick:this.clickPublishedProjects},
+ React.DOM.input( {type:"checkbox", checked:this.state.publishedChecked} ), " ", cap(i18n.published)
+ )
+ );
}
},
@@ -552,14 +611,6 @@ function loadComponents() {
this.setState({selectedProjects: newSelection});
},
- selectPreviousProjects: function() {
- this.selectPrevious(true);
- },
-
- deselectPreviousProjects: function() {
- this.selectPrevious(false);
- },
-
checkPrevious: function() {
var lastProjects = this.state.lastExport[0].projects,
countLastProjects = 0;
@@ -574,40 +625,34 @@ function loadComponents() {
return countLastProjects === lastProjects.length;
},
+ clickPreviousProjects: function() {
+ var previousState = this.state.previousChecked;
+ this.setState({previousChecked: !previousState});
+ if (previousState) {
+ this.selectPrevious(false);
+ } else {
+ this.selectPrevious(true);
+ }
+ },
+
renderSelectPreviousButton: function() {
if (this.state.initializing || this.state.allProjects.results.length === 0 ||
this.state.lastExport.length === 0 || this.state.lastExport[0].projects.length === 0) {
return (
React.DOM.span(null )
);
- } else if (this.checkPrevious()) {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:this.deselectPreviousProjects},
- React.DOM.input( {type:"checkbox", checked:true, onClick:this.deselectPreviousProjects} ), " ", cap(i18n.included_export)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:true} ), " ", cap(i18n.included_export)
- )
- );
- }
} else {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:this.selectPreviousProjects},
- React.DOM.input( {type:"checkbox", checked:false, onClick:this.selectPreviousProjects} ), " ", cap(i18n.included_export)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:false} ), " ", cap(i18n.included_export)
- )
- );
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
}
+
+ return (
+ React.DOM.button( {className:buttonClass, onClick:this.clickPreviousProjects},
+ React.DOM.input( {type:"checkbox", checked:this.state.previousChecked} ), " ", cap(i18n.included_export)
+ )
+ );
}
},
@@ -639,42 +684,6 @@ function loadComponents() {
this.selectAll(false);
},
- renderSelectAllButton: function() {
- if (this.state.allProjects === null || this.state.allProjects.results.length === 0) {
- return (
- React.DOM.span(null )
- );
- } else if (this.state.allProjects.results.length === this.state.selectedProjects.length) {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:this.deselectAllProjects},
- React.DOM.input( {type:"checkbox", checked:true, onClick:this.deselectAllProjects} ), " ", cap(i18n.all)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:true} ), " ", cap(i18n.all)
- )
- );
- }
- } else {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:this.selectAllProjects},
- React.DOM.input( {type:"checkbox", checked:false, onClick:this.selectAllProjects} ), " ", cap(i18n.all)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:false} ), " ", cap(i18n.all)
- )
- );
- }
- }
- },
-
selectProjects: function(select, key, value) {
var newSelection = this.state.selectedProjects;
@@ -711,89 +720,14 @@ function loadComponents() {
return any ? false : count === countSelected;
},
- renderFilter: function(projectKey, projectValue, name) {
- var allProjects = this.checkProjects(projectKey, projectValue, false),
- thisFilter = this;
-
- var selectProjects = function() {
- thisFilter.selectProjects(true, projectKey, projectValue);
- };
-
- var deselectProjects = function() {
- thisFilter.selectProjects(false, projectKey, projectValue);
- };
-
- if (allProjects) {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:deselectProjects},
- React.DOM.input( {type:"checkbox", checked:true, onClick:deselectProjects} ), " ", cap(name)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:true} ), " ", cap(name)
- )
- );
- }
- } else {
- if (!this.state.exporting) {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm", onClick:selectProjects},
- React.DOM.input( {type:"checkbox", checked:false, onClick:selectProjects} ), " ", cap(name)
- )
- );
- } else {
- return (
- React.DOM.button( {className:"btn btn-default btn-sm disabled"},
- React.DOM.input( {type:"checkbox", checked:false} ), " ", cap(name)
- )
- );
- }
- }
- },
-
renderFilters: function() {
- var renderFilter = function(filter) {
- var anyProjects = thisApp.checkProjects(filter[0], filter[1], true);
-
- if (anyProjects) {
- return thisApp.renderFilter(filter[0], filter[1], filter[2]);
- } else {
- return (
- React.DOM.span(null )
- );
- }
- };
-
- var thisApp = this,
- statusFilters = [
- ['status', 'H', i18n.needs_funding],
- ['status', 'A', i18n.active],
- ['status', 'C', i18n.completed],
- ['status', 'L', i18n.cancelled],
- ['status', 'R', i18n.archived]
- ],
- globalFilters = [
- ['publishing_status', 'published', i18n.published],
- ['is_public', true, i18n.public]
- ];
-
- var renderedStatusFilters = statusFilters.map(renderFilter);
- var renderedGlobalFilters = globalFilters.map(renderFilter);
-
return (
React.DOM.div( {className:"row iatiFilters"},
React.DOM.div( {className:"col-sm-8 filterGroup"},
- React.DOM.h3(null, cap(i18n.project_selection)),
- React.DOM.p(null, cap(i18n.global_selection)),
- this.renderSelectAllButton(),
+ React.DOM.h5(null, cap(i18n.project_selection)),
this.renderNoErrorsButton(),
this.renderSelectPreviousButton(),
- renderedGlobalFilters,
- React.DOM.p(null, cap(i18n.project_status)),
- renderedStatusFilters
+ this.renderPublishedButton()
),
React.DOM.div( {className:"col-sm-4 newIatiExport text-center"},
React.DOM.p(null, this.state.selectedProjects.length, " ", i18n.projects_selected),
diff --git a/akvo/rsr/static/scripts-src/my-iati.jsx b/akvo/rsr/static/scripts-src/my-iati.jsx
index 7d7c3daa05..c7d0a522bb 100644
--- a/akvo/rsr/static/scripts-src/my-iati.jsx
+++ b/akvo/rsr/static/scripts-src/my-iati.jsx
@@ -327,7 +327,7 @@ function loadComponents() {
onclickAll;
if (this.props.projects.length > 0) {
- // In case there are projets, show a table overview of the projects.
+ // In case there are projects, show a table overview of the projects.
checked = this.props.projects.length === this.props.selectedProjects.length;
onclickAll = checked ? this.props.deselectAll : this.props.selectAll;
projects = this.sortedProjects().map(function(project) {
@@ -384,7 +384,10 @@ function loadComponents() {
selectedProjects: [],
lastExport: null,
publishedFilter: false,
- exporting: false
+ exporting: false,
+ noErrorsChecked: false,
+ previousChecked: false,
+ publishedChecked: false
};
},
@@ -427,6 +430,7 @@ function loadComponents() {
if (projectIndex > -1) {
newSelection.splice(projectIndex, 1);
+ this.checkUnchecked();
} else {
newSelection.push(projectId);
}
@@ -451,6 +455,27 @@ function loadComponents() {
apiCall('POST', url, data, true, exportAdded);
},
+ checkUnchecked: function() {
+ // A check whether the filters should be unchecked (after deselecting a project,
+ // for instance).
+ var selection = this.state.selectedProjects,
+ allProjects = this.state.allProjects.results,
+ lastProjects = this.state.lastExport[0].projects;
+
+ for (var i = 0; i < allProjects.length; i++) {
+ var project = allProjects[i];
+ if (project.checks_errors.length === 0 && selection.indexOf(project.id) < 0) {
+ this.setState({noErrorsChecked: false});
+ }
+ if (lastProjects.indexOf(project.id) > -1 && selection.indexOf(project.id) < 0) {
+ this.setState({previousChecked: false});
+ }
+ if (project.publishing_status === 'published' && selection.indexOf(project.id) < 0) {
+ this.setState({publishedChecked: false});
+ }
+ }
+ },
+
selectNoErrors: function(select) {
var newSelection = this.state.selectedProjects;
@@ -467,14 +492,6 @@ function loadComponents() {
this.setState({selectedProjects: newSelection});
},
- selectNoErrorsProjects: function() {
- this.selectNoErrors(true);
- },
-
- deselectNoErrorsProjects: function() {
- this.selectNoErrors(false);
- },
-
checkNoErrors: function() {
var noErrorsCount = 0;
@@ -488,15 +505,14 @@ function loadComponents() {
return noErrorsCount;
},
- allNoErrorsSelected: function() {
- for (var i = 0; i < this.state.allProjects.results.length; i++) {
- var project = this.state.allProjects.results[i];
-
- if (project.checks_errors.length === 0 && this.state.selectedProjects.indexOf(project.id) < 0) {
- return false;
- }
+ clickNoErrorsProjects: function() {
+ var previousState = this.state.noErrorsChecked;
+ this.setState({noErrorsChecked: !previousState});
+ if (previousState) {
+ this.selectNoErrors(false);
+ } else {
+ this.selectNoErrors(true);
}
- return true;
},
renderNoErrorsButton: function() {
@@ -504,34 +520,77 @@ function loadComponents() {
return (
<span />
);
- } else if (this.allNoErrorsSelected()) {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm">
- <input type="checkbox" checked={true} onClick={this.deselectNoErrorsProjects} /> {cap(i18n.without_errors)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={true} /> {cap(i18n.without_errors)}
- </button>
- );
+ } else {
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
+ }
+
+ return (
+ <button className={buttonClass} onClick={this.clickNoErrorsProjects}>
+ <input type="checkbox" checked={this.state.noErrorsChecked} /> {cap(i18n.without_errors)}
+ </button>
+ );
+ }
+ },
+
+ selectPublished: function(select) {
+ var newSelection = this.state.selectedProjects;
+
+ for (var i = 0; i < this.state.allProjects.results.length; i++) {
+ var project = this.state.allProjects.results[i],
+ newSelectionIndex = newSelection.indexOf(project.id);
+ if (select && newSelectionIndex < 0 && project.publishing_status === 'published') {
+ newSelection.push(project.id);
+ } else if (!select && newSelectionIndex > -1 && project.publishing_status === 'published') {
+ newSelection.splice(newSelectionIndex, 1);
+ }
+ }
+
+ this.setState({selectedProjects: newSelection});
+ },
+
+ checkPublished: function() {
+ var noErrorsCount = 0;
+
+ for (var i = 0; i < this.state.allProjects.results.length; i++) {
+ var project = this.state.allProjects.results[i];
+ if (project.publishing_status === 'published') {
+ return true;
}
+ }
+
+ return false;
+ },
+
+ clickPublishedProjects: function() {
+ var previousState = this.state.publishedChecked;
+ this.setState({publishedChecked: !previousState});
+ if (previousState) {
+ this.selectPublished(false);
} else {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm">
- <input type="checkbox" checked={false} onClick={this.selectNoErrorsProjects} /> {cap(i18n.without_errors)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={false} /> {cap(i18n.without_errors)}
- </button>
- );
+ this.selectPublished(true);
+ }
+ },
+
+ renderPublishedButton: function() {
+ if (this.state.allProjects === null || this.state.allProjects.results.length === 0 || !this.checkPublished()) {
+ return (
+ <span />
+ );
+ } else {
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
}
+
+ return (
+ <button className={buttonClass} onClick={this.clickPublishedProjects}>
+ <input type="checkbox" checked={this.state.publishedChecked} /> {cap(i18n.published)}
+ </button>
+ );
}
},
@@ -552,14 +611,6 @@ function loadComponents() {
this.setState({selectedProjects: newSelection});
},
- selectPreviousProjects: function() {
- this.selectPrevious(true);
- },
-
- deselectPreviousProjects: function() {
- this.selectPrevious(false);
- },
-
checkPrevious: function() {
var lastProjects = this.state.lastExport[0].projects,
countLastProjects = 0;
@@ -574,40 +625,34 @@ function loadComponents() {
return countLastProjects === lastProjects.length;
},
+ clickPreviousProjects: function() {
+ var previousState = this.state.previousChecked;
+ this.setState({previousChecked: !previousState});
+ if (previousState) {
+ this.selectPrevious(false);
+ } else {
+ this.selectPrevious(true);
+ }
+ },
+
renderSelectPreviousButton: function() {
if (this.state.initializing || this.state.allProjects.results.length === 0 ||
this.state.lastExport.length === 0 || this.state.lastExport[0].projects.length === 0) {
return (
<span />
);
- } else if (this.checkPrevious()) {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={this.deselectPreviousProjects}>
- <input type="checkbox" checked={true} onClick={this.deselectPreviousProjects} /> {cap(i18n.included_export)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={true} /> {cap(i18n.included_export)}
- </button>
- );
- }
} else {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={this.selectPreviousProjects}>
- <input type="checkbox" checked={false} onClick={this.selectPreviousProjects} /> {cap(i18n.included_export)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={false} /> {cap(i18n.included_export)}
- </button>
- );
+ var buttonClass = "btn btn-default btn-sm";
+
+ if (this.state.exporting) {
+ buttonClass += " disabled";
}
+
+ return (
+ <button className={buttonClass} onClick={this.clickPreviousProjects}>
+ <input type="checkbox" checked={this.state.previousChecked} /> {cap(i18n.included_export)}
+ </button>
+ );
}
},
@@ -639,42 +684,6 @@ function loadComponents() {
this.selectAll(false);
},
- renderSelectAllButton: function() {
- if (this.state.allProjects === null || this.state.allProjects.results.length === 0) {
- return (
- <span />
- );
- } else if (this.state.allProjects.results.length === this.state.selectedProjects.length) {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={this.deselectAllProjects}>
- <input type="checkbox" checked={true} onClick={this.deselectAllProjects} /> {cap(i18n.all)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={true} /> {cap(i18n.all)}
- </button>
- );
- }
- } else {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={this.selectAllProjects}>
- <input type="checkbox" checked={false} onClick={this.selectAllProjects} /> {cap(i18n.all)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={false} /> {cap(i18n.all)}
- </button>
- );
- }
- }
- },
-
selectProjects: function(select, key, value) {
var newSelection = this.state.selectedProjects;
@@ -711,89 +720,14 @@ function loadComponents() {
return any ? false : count === countSelected;
},
- renderFilter: function(projectKey, projectValue, name) {
- var allProjects = this.checkProjects(projectKey, projectValue, false),
- thisFilter = this;
-
- var selectProjects = function() {
- thisFilter.selectProjects(true, projectKey, projectValue);
- };
-
- var deselectProjects = function() {
- thisFilter.selectProjects(false, projectKey, projectValue);
- };
-
- if (allProjects) {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={deselectProjects}>
- <input type="checkbox" checked={true} onClick={deselectProjects} /> {cap(name)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={true} /> {cap(name)}
- </button>
- );
- }
- } else {
- if (!this.state.exporting) {
- return (
- <button className="btn btn-default btn-sm" onClick={selectProjects}>
- <input type="checkbox" checked={false} onClick={selectProjects} /> {cap(name)}
- </button>
- );
- } else {
- return (
- <button className="btn btn-default btn-sm disabled">
- <input type="checkbox" checked={false} /> {cap(name)}
- </button>
- );
- }
- }
- },
-
renderFilters: function() {
- var renderFilter = function(filter) {
- var anyProjects = thisApp.checkProjects(filter[0], filter[1], true);
-
- if (anyProjects) {
- return thisApp.renderFilter(filter[0], filter[1], filter[2]);
- } else {
- return (
- <span />
- );
- }
- };
-
- var thisApp = this,
- statusFilters = [
- ['status', 'H', i18n.needs_funding],
- ['status', 'A', i18n.active],
- ['status', 'C', i18n.completed],
- ['status', 'L', i18n.cancelled],
- ['status', 'R', i18n.archived]
- ],
- globalFilters = [
- ['publishing_status', 'published', i18n.published],
- ['is_public', true, i18n.public]
- ];
-
- var renderedStatusFilters = statusFilters.map(renderFilter);
- var renderedGlobalFilters = globalFilters.map(renderFilter);
-
return (
<div className="row iatiFilters">
<div className="col-sm-8 filterGroup">
- <h3>{cap(i18n.project_selection)}</h3>
- <p>{cap(i18n.global_selection)}</p>
- {this.renderSelectAllButton()}
+ <h5>{cap(i18n.project_selection)}</h5>
{this.renderNoErrorsButton()}
{this.renderSelectPreviousButton()}
- {renderedGlobalFilters}
- <p>{cap(i18n.project_status)}</p>
- {renderedStatusFilters}
+ {this.renderPublishedButton()}
</div>
<div className="col-sm-4 newIatiExport text-center">
<p>{this.state.selectedProjects.length} {i18n.projects_selected}</p>
diff --git a/akvo/rsr/static/styles-src/main.css b/akvo/rsr/static/styles-src/main.css
index dfe212d80c..1c20bb0574 100755
--- a/akvo/rsr/static/styles-src/main.css
+++ b/akvo/rsr/static/styles-src/main.css
@@ -3992,8 +3992,6 @@ div.iatiFilters {
div.iatiFilters h3 {
margin-top: 0;
display: block; }
- div.iatiFilters .newIatiExport p {
- margin-top: 10%; }
div.iatiFilters .newIatiExport .btn {
display: inline-block;
margin-left: auto;
diff --git a/akvo/rsr/static/styles-src/main.scss b/akvo/rsr/static/styles-src/main.scss
index a2a95f3e0b..81e1115e33 100755
--- a/akvo/rsr/static/styles-src/main.scss
+++ b/akvo/rsr/static/styles-src/main.scss
@@ -4690,9 +4690,6 @@ div.iatiFilters {
display: block;
}
.newIatiExport {
- p {
- margin-top: 10%;
- }
.btn {
display: inline-block;
margin-left: auto;
|
kubeflow__pipelines-5054 | TypeErro occurs in gcp/automl/create_dataset_for_tables component
### What steps did you take:
[A clear and concise description of what the bug is.]
[gcp/automl/create_dataset_for_tables component](https://github.com/kubeflow/pipelines/tree/master/components/gcp/automl/create_dataset_for_tables)'s `create_time` output is declared as a string:
https://github.com/kubeflow/pipelines/blob/ecb14f40bb819c0678589b6458892ece5369fa71/components/gcp/automl/create_dataset_for_tables/component.yaml#L15
however, `google.protobuf.timestamp_pb2.Timestamp` is returned in actual fact:
https://github.com/kubeflow/pipelines/blob/ecb14f40bb819c0678589b6458892ece5369fa71/components/gcp/automl/create_dataset_for_tables/component.py#L54
FYI: The `dataset` object is an instance of `google.cloud.automl_v1beta1.types.Dataset` class and its [document](https://googleapis.dev/python/automl/0.4.0/gapic/v1beta1/types.html#google.cloud.automl_v1beta1.types.Dataset.create_time) says:
> **create_time**
> Output only. Timestamp when this dataset was created.
### What happened:
`TypeError` occurs

### What did you expect to happen:
Work.
### Environment:
<!-- Please fill in those that seem relevant. -->
How did you deploy Kubeflow Pipelines (KFP)? AI Platform Pipelines
<!-- If you are not sure, here's [an introduction of all options](https://www.kubeflow.org/docs/pipelines/installation/overview/). -->
KFP version: 1.0.4 <!-- If you are not sure, build commit shows on bottom of KFP UI left sidenav. -->
KFP SDK version: 1.3.0 <!-- Please attach the output of this shell command: $pip list | grep kfp -->
### Anything else you would like to add:
[Miscellaneous information that will assist in solving the issue.]
/kind bug
<!-- Please include labels by uncommenting them to help us better triage issues, choose from the following -->
<!--
// /area frontend
// /area backend
// /area sdk
// /area testing
// /area engprod
-->
| [
{
"content": "# Copyright 2019 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 applicab... | [
{
"content": "# Copyright 2019 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 applicab... | diff --git a/components/gcp/automl/create_dataset_for_tables/component.py b/components/gcp/automl/create_dataset_for_tables/component.py
index 9239e780b15..968a8ad55d0 100644
--- a/components/gcp/automl/create_dataset_for_tables/component.py
+++ b/components/gcp/automl/create_dataset_for_tables/component.py
@@ -51,7 +51,7 @@ def automl_create_dataset_for_tables(
region=gcp_region,
dataset_id=dataset_id,
)
- return (dataset.name, dataset.create_time, dataset_id, dataset_url)
+ return (dataset.name, str(dataset.create_time), dataset_id, dataset_url)
if __name__ == '__main__':
diff --git a/components/gcp/automl/create_dataset_for_tables/component.yaml b/components/gcp/automl/create_dataset_for_tables/component.yaml
index 74257db9fdd..1a79fc40bdd 100644
--- a/components/gcp/automl/create_dataset_for_tables/component.yaml
+++ b/components/gcp/automl/create_dataset_for_tables/component.yaml
@@ -65,7 +65,7 @@ implementation:
region=gcp_region,
dataset_id=dataset_id,
)
- return (dataset.name, dataset.create_time, dataset_id, dataset_url)
+ return (dataset.name, str(dataset.create_time), dataset_id, dataset_url)
import json
def _serialize_str(str_value: str) -> str:
|
streamlink__streamlink-4628 | plugins.twitcasting: Writes JSON into video files when it shouldn't
### Checklist
- [X] This is a plugin issue and not a different kind of issue
- [X] [I have read the contribution guidelines](https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink)
- [X] [I have checked the list of open and recently closed plugin issues](https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22)
- [X] [I have checked the commit log of the master branch](https://github.com/streamlink/streamlink/commits/master)
### Streamlink version
Latest build from the master branch
### Description
https://github.com/streamlink/streamlink/pull/4608 introduced a bug of JSON being written to the output file.
- When running streamlink on a channel that is live but only for members, using `-o out.mp4` flag to output to a file, it creates a video file containing just a single JSON line in it:
```
$ cat out.mp4
{"type":"status","code":403,"text":"Access Forbidden"}
```
The expected behavior is that it doesn't create the file in such situation, like it used to behave before https://github.com/streamlink/streamlink/pull/4608 fixes were made.
- It also adds `{"type":"status","code":504,"text":"End of Live"}` at the end of video files when the stream ends:
```
$ xxd -s -128 -c 16 out.ts
24b5bee9: 5c75 7cc6 7e38 e099 55d9 6257 59d8 eb6e \u|.~8..U.bWY..n
24b5bef9: b7aa 49bb ef3a dd18 7767 8c77 7dc6 6ade ..I..:..wg.w}.j.
24b5bf09: 6d54 2175 2acf 0926 400f 0449 2bc6 a816 mT!u*..&@..I+...
24b5bf19: 3523 72e9 db4d 6c5a 5aba ec75 3c0a ad72 5#r..MlZZ..u<..r
24b5bf29: 2258 0b2f ebc2 b50a 7ed3 bbbd 8d30 c77b "X./....~....0.{
24b5bf39: 2274 7970 6522 3a22 7374 6174 7573 222c "type":"status",
24b5bf49: 2263 6f64 6522 3a35 3034 2c22 7465 7874 "code":504,"text
24b5bf59: 223a 2245 6e64 206f 6620 4c69 7665 227d ":"End of Live"}
```

- Perhaps it shouldn't be writing any `response['type'] == 'status'` to the file?
- While at it, maybe there is something else that it's writing to a video file that it shouldn't? As mentioned in https://github.com/streamlink/streamlink/issues/4604#issuecomment-1166177130, Twitcasting also sends `{"type":"event","code":100,"text":""}` sometimes. Would that get written into the video file too? Is that something that should be written into it?
### Debug log
```text
[cli][debug] OS: Linux-5.10.0-14-amd64-x86_64-with-glibc2.31
[cli][debug] Python: 3.9.2
[cli][debug] Streamlink: 4.1.0+37.g2c564dbe
[cli][debug] Dependencies:
[cli][debug] isodate: 0.6.0
[cli][debug] lxml: 4.7.1
[cli][debug] pycountry: 20.7.3
[cli][debug] pycryptodome: 3.10.1
[cli][debug] PySocks: 1.7.1
[cli][debug] requests: 2.28.0
[cli][debug] websocket-client: 1.2.3
[cli][debug] Arguments:
[cli][debug] url=https://twitcasting.tv/[REDACTED]
[cli][debug] stream=['best']
[cli][debug] --config=['../config']
[cli][debug] --loglevel=debug
[cli][debug] --output=[REDACTED]
[cli][debug] --retry-streams=1.0
[cli][debug] --retry-max=300
[cli][info] Found matching plugin twitcasting for URL https://twitcasting.tv/[REDACTED]
[plugins.twitcasting][debug] Live stream info: {'movie': {'id': [REDACTED], 'live': True}, 'fmp4': {'host': '202-218-171-197.twitcasting.tv', 'proto': 'wss', 'source': False, 'mobilesource': False}}
[plugins.twitcasting][debug] Real stream url: wss://202-218-171-197.twitcasting.tv/ws.app/stream/[REDACTED]/fmp4/bd/1/1500?mode=base
[cli][info] Available streams: base (worst, best)
[cli][info] Opening stream: base (stream)
[cli][info] Writing output to
[REDACTED]
[cli][debug] Checking file output
[plugin.api.websocket][debug] Connecting to: wss://202-218-171-197.twitcasting.tv/ws.app/stream/[REDACTED]/fmp4/bd/1/1500?mode=base
[cli][debug] Pre-buffering 8192 bytes
[plugin.api.websocket][debug] Connected: wss://202-218-171-197.twitcasting.tv/ws.app/stream/[REDACTED]/fmp4/bd/1/1500?mode=base
[cli][debug] Writing stream to output
[plugin.api.websocket][error] Connection to remote host was lost.
[plugin.api.websocket][debug] Closed: wss://202-218-171-197.twitcasting.tv/ws.app/stream/[REDACTED]/fmp4/bd/1/1500?mode=base
[cli][info] Stream ended
[cli][info] Closing currently open stream...
```
| [
{
"content": "\"\"\"\n$description Global live broadcasting and live broadcast archiving social platform.\n$url twitcasting.tv\n$type live\n\"\"\"\n\nimport hashlib\nimport logging\nimport re\n\nfrom streamlink.buffers import RingBuffer\nfrom streamlink.plugin import Plugin, PluginArgument, PluginArguments, Plu... | [
{
"content": "\"\"\"\n$description Global live broadcasting and live broadcast archiving social platform.\n$url twitcasting.tv\n$type live\n\"\"\"\n\nimport hashlib\nimport logging\nimport re\n\nfrom streamlink.buffers import RingBuffer\nfrom streamlink.plugin import Plugin, PluginArgument, PluginArguments, Plu... | diff --git a/src/streamlink/plugins/twitcasting.py b/src/streamlink/plugins/twitcasting.py
index e2f8fb097e9..206845d4062 100644
--- a/src/streamlink/plugins/twitcasting.py
+++ b/src/streamlink/plugins/twitcasting.py
@@ -104,7 +104,7 @@ def on_close(self, *args, **kwargs):
def on_data(self, wsapp, data, data_type, cont):
if data_type == self.OPCODE_TEXT:
- data = bytes(data, "utf-8")
+ return
try:
self.buffer.write(data)
|
huggingface__diffusers-6012 | logging.remove_handler() has a faulty assertion, doesn't allow registered handlers to be removed
### Describe the bug
in `utils/logging.py` there the function remove_handler seems to have a faulty assertion in it.
```py
def add_handler(handler: logging.Handler) -> None:
"""adds a handler to the HuggingFace Diffusers' root logger."""
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler)
def remove_handler(handler: logging.Handler) -> None:
"""removes given handler from the HuggingFace Diffusers' root logger."""
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers # <<< THIS ONE
_get_library_root_logger().removeHandler(handler)
```
That line seems to have a `not` that shouldn't be there. (the `not in` to be precise)
Normally I'd just do a PR to remove it, but as I'm not that familiar with the codebase, nor Python in general, and don't yet have a solid grasp of what these things actually do (I'm just playing around trying to familiarize myself), I decided to make an issue instead so people who actually know the codebase can do it.
### Reproduction
```py
from diffusers import logging
from logging import Handler
class TestHandler(Handler):
def __init__(self):
super().__init__()
def emit(self):
pass
handler = TestHandler()
logging.add_handler(handler)
logging.remove_handler(handler)
```
### Logs
```shell
Traceback (most recent call last):
File ".\test.py", line 14, in <module>
logging.remove_handler(handler)
File "C:\Users\XXX\XXX\venv\lib\site-packages\diffusers\utils\logging.py", line 221, in remove_handler
assert handler is not None and handler not in _get_library_root_logger().handlers
AssertionError
```
### System Info
- `diffusers` version: 0.3.0
- Platform: Windows-10-10.0.19041-SP0
- Python version: 3.8.9
- PyTorch version (GPU?): 1.12.1+cpu (False)
- Huggingface_hub version: 0.9.1
- Transformers version: 4.21.3
- Using GPU in script?: no
- Using distributed or parallel set-up in script?: Don't understand the question, but seems irrelevant.
| [
{
"content": "# coding=utf-8\n# Copyright 2023 Optuna, Hugging Face\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# Un... | [
{
"content": "# coding=utf-8\n# Copyright 2023 Optuna, Hugging Face\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# Un... | diff --git a/src/diffusers/utils/logging.py b/src/diffusers/utils/logging.py
index 6050f314c008..7945db333cab 100644
--- a/src/diffusers/utils/logging.py
+++ b/src/diffusers/utils/logging.py
@@ -213,7 +213,7 @@ def remove_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
- assert handler is not None and handler not in _get_library_root_logger().handlers
+ assert handler is not None and handler in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(handler)
|
e2nIEE__pandapower-2106 | [bug] Pandapower interferes with matplotlib savefig
### Bug report checklis
- [X] Searched the [issues page](https://github.com/e2nIEE/pandapower/issues) for similar reports
- [X] Read the relevant sections of the [documentation](https://pandapower.readthedocs.io/en/latest/about.html)
- [X] Browse the [tutorials](https://github.com/e2nIEE/pandapower/tree/develop/tutorials) and [tests](https://github.com/e2nIEE/pandapower/tree/develop/pandapower/test) for usefull code snippets and examples of use
- [X] Reproduced the issue after updating with `pip install --upgrade pandapower` (or `git pull`)
- [X] Tried basic troubleshooting (if a bug/error) like restarting the interpreter and checking the pythonpath
### Reproducible Example
```python
import matplotlib.pyplot as plt
import pandapower
fig, ax = plt.subplots()
ax.scatter(range(5), range(5))
fig.savefig('test.svg')
```
### Issue Description and Traceback
When pandapower is imported, matplotlib `savefig()` may run into a bug where the `GraphicsContextBase._capstyle` is set to a `str` instead of a `CapStyle` instance. Calling the proper `set_capstyle()` method solves this issue. Also, somehow, this issue does not arise when calling `fig.savefig('test.png')`. It only arises when the figure save type is SVG.
The following code works fine. Notice that I have commented out `import pandapower`:
```python
import matplotlib.pyplot as plt
# import pandapower
fig, ax = plt.subplots()
ax.scatter(range(5), range(5))
fig.savefig('test.svg')
```
However, if I uncomment the `import pandapower` line, then I will get an error:
```python
import matplotlib.pyplot as plt
import pandapower
fig, ax = plt.subplots()
ax.scatter(range(5), range(5))
fig.savefig('test.svg')
```
Error:
```
Traceback (most recent call last):
File "/home/user/testenv/test.py", line 6, in <module>
fig.savefig('test.svg')
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/figure.py", line 3378, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backend_bases.py", line 2366, in print_figure
result = print_method(
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backend_bases.py", line 2232, in <lambda>
print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py", line 1369, in print_svg
self.figure.draw(renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/artist.py", line 95, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/figure.py", line 3175, in draw
mimage._draw_list_compositing_images(
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/image.py", line 131, in _draw_list_compositing_images
a.draw(renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 3064, in draw
mimage._draw_list_compositing_images(
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/image.py", line 131, in _draw_list_compositing_images
a.draw(renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/collections.py", line 972, in draw
super().draw(renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/collections.py", line 405, in draw
renderer.draw_markers(
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py", line 717, in draw_markers
style = self._get_style_dict(gc, rgbFace)
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py", line 609, in _get_style_dict
if gc.get_capstyle() != 'butt':
File "/home/user/miniconda3/envs/testenv/lib/python3.10/site-packages/matplotlib/backend_bases.py", line 820, in get_capstyle
return self._capstyle.name
AttributeError: 'str' object has no attribute 'name'
```
### Expected Behavior
I would expect the following 2 code blocks to produce identical (or at least similar) results:
```python
import matplotlib.pyplot as plt
# import pandapower
fig, ax = plt.subplots()
ax.scatter(range(5), range(5))
fig.savefig('test.svg')
```
and
```python
import matplotlib.pyplot as plt
import pandapower
fig, ax = plt.subplots()
ax.scatter(range(5), range(5))
fig.savefig('test.svg')
```
The 1st code block works fine, whereas the 2nd code block throws an `AttributeError`.
### Installed Versions
OS: Ubuntu 22.04 LTS
Python 3.10
Matplotlib 3.7.2
Pandapower 2.13.1
### Label
- [X] Relevant labels are selected
| [
{
"content": "from pandapower.plotting.collections import *\nfrom pandapower.plotting.colormaps import *\nfrom pandapower.plotting.generic_geodata import *\nfrom pandapower.plotting.powerflow_results import *\nfrom pandapower.plotting.simple_plot import *\nfrom pandapower.plotting.plotly import *\nfrom pandapow... | [
{
"content": "from pandapower.plotting.collections import *\nfrom pandapower.plotting.colormaps import *\nfrom pandapower.plotting.generic_geodata import *\nfrom pandapower.plotting.powerflow_results import *\nfrom pandapower.plotting.simple_plot import *\nfrom pandapower.plotting.plotly import *\nfrom pandapow... | diff --git a/pandapower/plotting/__init__.py b/pandapower/plotting/__init__.py
index 8b71f2bea..11a5090a4 100644
--- a/pandapower/plotting/__init__.py
+++ b/pandapower/plotting/__init__.py
@@ -16,7 +16,7 @@
class GC(GraphicsContextBase):
def __init__(self):
super().__init__()
- self._capstyle = 'round'
+ self.set_capstyle('round')
def custom_new_gc(self):
return GC()
|
gammapy__gammapy-3099 | Error in executing `FluxPoints.to_sed_type()`
**Gammapy version**
Present dev
**Bug description**
Calling `FluxPoints.to_sed_type()` returns an error
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-225-40a5362800d4> in <module>
----> 1 flux_points_fermi = FluxPoints(fgl_src.flux_points.table).to_sed_type("dnde", model=fgl_src.sky_model().spectral_model)
2 fpds_fermi = FluxPointsDataset(
3 data=flux_points_fermi, models=fgl_src.sky_model()
4 )
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in to_sed_type(self, sed_type, method, model, pwl_approx)
380 else:
381 raise ValueError(f"Invalid method: {method}")
--> 382 table = self._flux_to_dnde(e_ref, table, model, pwl_approx)
383
384 elif self.sed_type == "dnde" and sed_type == "e2dnde":
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in _flux_to_dnde(self, e_ref, table, model, pwl_approx)
277
278 flux = table["flux"].quantity
--> 279 dnde = self._dnde_from_flux(flux, model, e_ref, e_min, e_max, pwl_approx)
280
281 # Add to result table
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in _dnde_from_flux(flux, model, e_ref, e_min, e_max, pwl_approx)
436 )
437 else:
--> 438 flux_model = model.integral(e_min, e_max, intervals=True)
439
440 return dnde_model * (flux / flux_model)
~/Gammapy-dev/gammapy/gammapy/modeling/models/spectral.py in integral(self, emin, emax, **kwargs)
167 return self.evaluate_integral(emin, emax, **kwargs)
168 else:
--> 169 return integrate_spectrum(self, emin, emax, **kwargs)
170
171 def integral_error(self, emin, emax):
TypeError: integrate_spectrum() got an unexpected keyword argument 'intervals'
```
**To Reproduce**
```
from gammapy.catalog import CATALOG_REGISTRY
catalog_4fgl = CATALOG_REGISTRY.get_cls("4fgl")()
fgl_src = catalog_4fgl["FGES J1553.8-5325"]
flux_points_fermi = FluxPoints(fgl_src.flux_points.table).to_sed_type("dnde",
model=fgl_src.sky_model().spectral_model)
```
Error in executing `FluxPoints.to_sed_type()`
**Gammapy version**
Present dev
**Bug description**
Calling `FluxPoints.to_sed_type()` returns an error
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-225-40a5362800d4> in <module>
----> 1 flux_points_fermi = FluxPoints(fgl_src.flux_points.table).to_sed_type("dnde", model=fgl_src.sky_model().spectral_model)
2 fpds_fermi = FluxPointsDataset(
3 data=flux_points_fermi, models=fgl_src.sky_model()
4 )
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in to_sed_type(self, sed_type, method, model, pwl_approx)
380 else:
381 raise ValueError(f"Invalid method: {method}")
--> 382 table = self._flux_to_dnde(e_ref, table, model, pwl_approx)
383
384 elif self.sed_type == "dnde" and sed_type == "e2dnde":
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in _flux_to_dnde(self, e_ref, table, model, pwl_approx)
277
278 flux = table["flux"].quantity
--> 279 dnde = self._dnde_from_flux(flux, model, e_ref, e_min, e_max, pwl_approx)
280
281 # Add to result table
~/Gammapy-dev/gammapy/gammapy/estimators/flux_point.py in _dnde_from_flux(flux, model, e_ref, e_min, e_max, pwl_approx)
436 )
437 else:
--> 438 flux_model = model.integral(e_min, e_max, intervals=True)
439
440 return dnde_model * (flux / flux_model)
~/Gammapy-dev/gammapy/gammapy/modeling/models/spectral.py in integral(self, emin, emax, **kwargs)
167 return self.evaluate_integral(emin, emax, **kwargs)
168 else:
--> 169 return integrate_spectrum(self, emin, emax, **kwargs)
170
171 def integral_error(self, emin, emax):
TypeError: integrate_spectrum() got an unexpected keyword argument 'intervals'
```
**To Reproduce**
```
from gammapy.catalog import CATALOG_REGISTRY
catalog_4fgl = CATALOG_REGISTRY.get_cls("4fgl")()
fgl_src = catalog_4fgl["FGES J1553.8-5325"]
flux_points_fermi = FluxPoints(fgl_src.flux_points.table).to_sed_type("dnde",
model=fgl_src.sky_model().spectral_model)
```
| [
{
"content": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.io.registry import IORegistryError\nfrom astropy.table import Table, vstack\nfrom gammapy.datasets import Datasets\nfrom gammapy.modeling.models import ... | [
{
"content": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.io.registry import IORegistryError\nfrom astropy.table import Table, vstack\nfrom gammapy.datasets import Datasets\nfrom gammapy.modeling.models import ... | diff --git a/gammapy/estimators/flux_point.py b/gammapy/estimators/flux_point.py
index 62d1e45e36..685957d4bc 100644
--- a/gammapy/estimators/flux_point.py
+++ b/gammapy/estimators/flux_point.py
@@ -435,7 +435,7 @@ def _dnde_from_flux(flux, model, e_ref, e_min, e_max, pwl_approx):
amplitude=dnde_model,
)
else:
- flux_model = model.integral(e_min, e_max, intervals=True)
+ flux_model = model.integral(e_min, e_max)
return dnde_model * (flux / flux_model)
diff --git a/gammapy/estimators/tests/test_flux_point.py b/gammapy/estimators/tests/test_flux_point.py
index fed6f5d3d2..1441ee7774 100644
--- a/gammapy/estimators/tests/test_flux_point.py
+++ b/gammapy/estimators/tests/test_flux_point.py
@@ -139,6 +139,16 @@ def test_compute_flux_points_dnde_exp(method):
assert_quantity_allclose(actual, desired, rtol=1e-8)
+@requires_data()
+def test_fermi_to_dnde():
+ from gammapy.catalog import CATALOG_REGISTRY
+ catalog_4fgl = CATALOG_REGISTRY.get_cls("4fgl")()
+ src = catalog_4fgl["FGES J1553.8-5325"]
+ fp_dnde = src.flux_points.to_sed_type("dnde", model=src.spectral_model())
+
+ assert_allclose(fp_dnde.table["dnde"].quantity[1], 4.567393e-10 * u.Unit("cm-2 s-1 MeV-1"), rtol=1e-5)
+
+
@pytest.fixture(params=FLUX_POINTS_FILES, scope="session")
def flux_points(request):
path = "$GAMMAPY_DATA/tests/spectrum/flux_points/" + request.param
diff --git a/gammapy/modeling/models/tests/test_cube.py b/gammapy/modeling/models/tests/test_cube.py
index a51b125e29..f7571911ae 100644
--- a/gammapy/modeling/models/tests/test_cube.py
+++ b/gammapy/modeling/models/tests/test_cube.py
@@ -23,7 +23,7 @@
SkyModel,
create_fermi_isotropic_diffuse_model,
)
-from gammapy.utils.testing import requires_data, mpl_plot_check
+from gammapy.utils.testing import requires_data, mpl_plot_check, requires_dependency
from gammapy.modeling import Parameter
from astropy.coordinates.angle_utilities import angular_separation
@@ -612,6 +612,7 @@ def test_energy_dependent_model(geom_true):
assert_allclose(model.data.sum(), 1.678314e-14, rtol=1e-3)
+@requires_dependency("matplotlib")
def test_plot_grid(geom_true):
spatial_model = MyCustomGaussianModel(frame="galactic")
with mpl_plot_check():
diff --git a/gammapy/modeling/models/tests/test_spatial.py b/gammapy/modeling/models/tests/test_spatial.py
index 86e4d2acba..489d3c3d08 100644
--- a/gammapy/modeling/models/tests/test_spatial.py
+++ b/gammapy/modeling/models/tests/test_spatial.py
@@ -235,6 +235,7 @@ def test_sky_diffuse_constant():
assert isinstance(model.to_region(), EllipseSkyRegion)
+@requires_dependency("matplotlib")
@requires_data()
def test_sky_diffuse_map():
filename = "$GAMMAPY_DATA/catalogs/fermi/Extended_archive_v18/Templates/RXJ1713_2016_250GeV.fits"
@@ -242,18 +243,23 @@ def test_sky_diffuse_map():
lon = [258.5, 0] * u.deg
lat = -39.8 * u.deg
val = model(lon, lat)
+
assert val.unit == "sr-1"
desired = [3269.178107, 0]
assert_allclose(val.value, desired)
+
res = model.evaluate_geom(model.map.geom)
assert_allclose(np.sum(res.value), 32816514.42078349)
radius = model.evaluation_radius
+
assert radius.unit == "deg"
assert_allclose(radius.value, 0.64, rtol=1.0e-2)
assert model.frame == "fk5"
assert isinstance(model.to_region(), PolygonSkyRegion)
+
with pytest.raises(TypeError):
model.plot_interative()
+
with pytest.raises(TypeError):
model.plot_grid()
@@ -266,13 +272,17 @@ def test_sky_diffuse_map_3d():
lat = -39.8 * u.deg
energy = 1 * u.GeV
val = model(lon, lat, energy)
+
with pytest.raises(ValueError):
model(lon, lat)
assert model.map.unit == "cm-2 s-1 MeV-1 sr-1"
+
val = model(lon, lat, energy)
assert val.unit == "cm-2 s-1 MeV-1 sr-1"
+
res = model.evaluate_geom(model.map.geom)
assert_allclose(np.sum(res.value), 0.11803847221522712)
+
with pytest.raises(TypeError):
model.plot()
|
xorbitsai__inference-386 | QUESTION: Upper bound for the max_token argument
I noticed that there is an upper bound of 2048 tokens placed on the max_token argument in [xinference/core/restful_api.py](https://github.com/xorbitsai/inference/blob/67a06b40ef4ec36448e504fd23526043719211bc/xinference/core/restful_api.py#L39-L41)
https://github.com/xorbitsai/inference/blob/67a06b40ef4ec36448e504fd23526043719211bc/xinference/core/restful_api.py#L39-L41
Why is this necessary? I feel like it would be reasonable to generate a 4000 token long essay with a model with matching context length, especially when we now have models like [InternLM](https://github.com/xorbitsai/inference/blob/67a06b40ef4ec36448e504fd23526043719211bc/xinference/model/llm/llm_family.json#L965-L1007) with 8k context length and [ChatGLM2-32k](https://github.com/xorbitsai/inference/blob/67a06b40ef4ec36448e504fd23526043719211bc/xinference/model/llm/llm_family.json#L450-L483) with 32k context length.
| [
{
"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/core/restful_api.py b/xinference/core/restful_api.py
index e2231d53f1..61908cc603 100644
--- a/xinference/core/restful_api.py
+++ b/xinference/core/restful_api.py
@@ -37,7 +37,7 @@
logger = logging.getLogger(__name__)
max_tokens_field = Field(
- default=128, ge=1, le=2048, description="The maximum number of tokens to generate."
+ default=128, ge=1, le=32768, description="The maximum number of tokens to generate."
)
temperature_field = Field(
|
Textualize__rich-211 | [BUG] Deprecation warning due to invalid escape sequences
**Describe the bug**
Deprecation warnings are raised due to invalid escape sequences. This can be fixed by using raw strings or escaping the literals. pyupgrade also helps in automatic conversion : https://github.com/asottile/pyupgrade/
**To Reproduce**
```
./tests/test_markup.py:26: DeprecationWarning: invalid escape sequence \[
assert escape("foo[bar]") == "foo\[bar]"
./tests/test_markup.py:30: DeprecationWarning: invalid escape sequence \[
result = list(_parse("[foo]hello[/foo][bar]world[/]\[escaped]"))
./rich/markup.py:50: DeprecationWarning: invalid escape sequence \[
return markup.replace("[", "\[")
```
**Platform**
What platform (Win/Linux/Mac) are you running on? What terminal software are you using. Which version of Rich?
| [
{
"content": "import re\nfrom typing import Iterable, List, NamedTuple, Optional, Tuple, Union\n\nfrom .errors import MarkupError\nfrom .style import Style\nfrom .text import Span, Text\nfrom ._emoji_replace import _emoji_replace\n\n\nRE_TAGS = re.compile(\n r\"\"\"\n(\\\\\\[)|\n\\[([a-z#\\/].*?)\\]\n\"\"\",... | [
{
"content": "import re\nfrom typing import Iterable, List, NamedTuple, Optional, Tuple, Union\n\nfrom .errors import MarkupError\nfrom .style import Style\nfrom .text import Span, Text\nfrom ._emoji_replace import _emoji_replace\n\n\nRE_TAGS = re.compile(\n r\"\"\"\n(\\\\\\[)|\n\\[([a-z#\\/].*?)\\]\n\"\"\",... | diff --git a/rich/markup.py b/rich/markup.py
index fb6f45c61..9af1cd9dd 100644
--- a/rich/markup.py
+++ b/rich/markup.py
@@ -47,7 +47,7 @@ def escape(markup: str) -> str:
Returns:
str: Markup with square brackets escaped.
"""
- return markup.replace("[", "\[")
+ return markup.replace("[", r"\[")
def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:
diff --git a/tests/test_markup.py b/tests/test_markup.py
index e345eaecc..8e254e9a3 100644
--- a/tests/test_markup.py
+++ b/tests/test_markup.py
@@ -23,11 +23,11 @@ def test_re_match():
def test_escape():
- assert escape("foo[bar]") == "foo\[bar]"
+ assert escape("foo[bar]") == r"foo\[bar]"
def test_parse():
- result = list(_parse("[foo]hello[/foo][bar]world[/]\[escaped]"))
+ result = list(_parse(r"[foo]hello[/foo][bar]world[/]\[escaped]"))
expected = [
(0, None, Tag(name="foo", parameters=None)),
(10, "hello", None),
|
pytorch__ignite-2852 | [CI] Doc test is failing
We have somehow doctest ci job failing right now. The failure happens with the following code snippet from our docs:
- https://pytorch.org/ignite/generated/ignite.contrib.metrics.PrecisionRecallCurve.html
```
**********************************************************************
File "../../ignite/contrib/metrics/precision_recall_curve.py", line ?, in default
Failed example:
y_pred = torch.tensor([0.0474, 0.5987, 0.7109, 0.9997])
y_true = torch.tensor([0, 0, 1, 1])
prec_recall_curve = PrecisionRecallCurve()
prec_recall_curve.attach(default_evaluator, 'prec_recall_curve')
state = default_evaluator.run([[y_pred, y_true]])
print("Precision", [round(i, 4) for i in state.metrics['prec_recall_curve'][0].tolist()])
print("Recall", [round(i, 4) for i in state.metrics['prec_recall_curve'][1].tolist()])
print("Thresholds", [round(i, 4) for i in state.metrics['prec_recall_curve'][2].tolist()])
Expected:
Precision [1.0, 1.0, 1.0]
Recall [1.0, 0.5, 0.0]
Thresholds [0.7109, 0.9997]
Got:
Precision [0.5, 0.6667, 1.0, 1.0, 1.0]
Recall [1.0, 1.0, 1.0, 0.5, 0.0]
Thresholds [0.0474, 0.5987, 0.7109, 0.9997]
```
- https://github.com/pytorch/ignite/actions/runs/4099985910/jobs/7074343114
### How to help with this issue
You need to do some detective work:
- Reproduce the issue locally
- Try to figure out which result is correct: "Expected" or "Got"
- Try to figure out why it started to happen: maybe sklearn version updated ? Previously, for example Jan 18, doctest was passing: https://github.com/pytorch/ignite/actions/runs/3894024421/jobs/6647420435
- Report here your findings and propose a way to solve the issue
| [
{
"content": "from typing import Any, Callable, cast, Tuple, Union\n\nimport torch\n\nimport ignite.distributed as idist\nfrom ignite.exceptions import NotComputableError\nfrom ignite.metrics import EpochMetric\n\n\ndef precision_recall_curve_compute_fn(y_preds: torch.Tensor, y_targets: torch.Tensor) -> Tuple[A... | [
{
"content": "from typing import Any, Callable, cast, Tuple, Union\n\nimport torch\n\nimport ignite.distributed as idist\nfrom ignite.exceptions import NotComputableError\nfrom ignite.metrics import EpochMetric\n\n\ndef precision_recall_curve_compute_fn(y_preds: torch.Tensor, y_targets: torch.Tensor) -> Tuple[A... | diff --git a/ignite/contrib/metrics/precision_recall_curve.py b/ignite/contrib/metrics/precision_recall_curve.py
index 3126c27ea2ba..d45a31fe5032 100644
--- a/ignite/contrib/metrics/precision_recall_curve.py
+++ b/ignite/contrib/metrics/precision_recall_curve.py
@@ -65,9 +65,9 @@ def sigmoid_output_transform(output):
.. testoutput::
- Precision [1.0, 1.0, 1.0]
- Recall [1.0, 0.5, 0.0]
- Thresholds [0.7109, 0.9997]
+ Precision [0.5, 0.6667, 1.0, 1.0, 1.0]
+ Recall [1.0, 1.0, 1.0, 0.5, 0.0]
+ Thresholds [0.0474, 0.5987, 0.7109, 0.9997]
"""
|
python-pillow__Pillow-1686 | Repeated looping over image stack shows last frame in place of first frame
When looping through the frames in an animation or TIFF stack with `ImageSequence.Iterator`, the frame pointer is not reset for the first frame. Consequently, if the loop is run through a second time the final frame is shown again instead of the first frame.
### Demo
Code
``` python
from PIL import Image, ImageSequence
import os
# Make a test image
os.system((
"convert -depth 8 -size 1x1 xc:'rgb(100,100,100)' xc:'rgb(121,121,121)'"
" xc:'rgb(142,142,142)' xc:'rgb(163,163,163)' image.tif"
))
# Open the image
im = Image.open('image.tif')
# Run through the image
print('First run')
for frame in ImageSequence.Iterator(im):
print(list(frame.getdata()))
# Run through the image again
print('Second run')
for frame in ImageSequence.Iterator(im):
print(list(frame.getdata()))
```
Output
```
First run
[100]
[121]
[142]
[163]
Second run
[163]
[121]
[142]
[163]
```
| [
{
"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# sequence support classes\n#\n# history:\n# 1997-02-20 fl Created\n#\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n\n\nclass Iterato... | [
{
"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# sequence support classes\n#\n# history:\n# 1997-02-20 fl Created\n#\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n\n\nclass Iterato... | diff --git a/PIL/ImageSequence.py b/PIL/ImageSequence.py
index 256bcbedb35..a979b8865a3 100644
--- a/PIL/ImageSequence.py
+++ b/PIL/ImageSequence.py
@@ -35,8 +35,7 @@ def __init__(self, im):
def __getitem__(self, ix):
try:
- if ix:
- self.im.seek(ix)
+ self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # end of sequence
diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py
index 9e18192ee14..5429c2845b0 100644
--- a/Tests/test_imagesequence.py
+++ b/Tests/test_imagesequence.py
@@ -44,6 +44,17 @@ def test_libtiff(self):
self._test_multipage_tiff()
TiffImagePlugin.READ_LIBTIFF = False
+ def test_consecutive(self):
+ im = Image.open('Tests/images/multipage.tiff')
+ firstFrame = None
+ for frame in ImageSequence.Iterator(im):
+ if firstFrame == None:
+ firstFrame = frame.copy()
+ pass
+ for frame in ImageSequence.Iterator(im):
+ self.assert_image_equal(frame, firstFrame)
+ break
+
if __name__ == '__main__':
unittest.main()
|
OpenMined__PySyft-2278 | Splitting up serde broke serialization for multipointers
**Describe the bug**
```
@staticmethod
def simplify(tensor: "MultiPointerTensor") -> tuple:
"""
This function takes the attributes of a MultiPointerTensor and saves them in a tuple
Args:
tensor (MultiPointerTensor): a MultiPointerTensor
Returns:
tuple: a tuple holding the unique attributes of the additive shared tensor
Examples:
data = simplify(tensor)
"""
chain = None
if hasattr(tensor, "child"):
> chain = sy.serde.simplify(tensor.child)
E AttributeError: module 'syft.serde' has no attribute 'simplify'
```
| [
{
"content": "import torch\nfrom typing import List\nfrom typing import Union\n\nimport syft as sy\nfrom syft.frameworks.torch.tensors.interpreters.abstract import AbstractTensor\nfrom syft.frameworks.torch.tensors.interpreters import AdditiveSharingTensor\nfrom syft.workers import BaseWorker\nfrom syft.framewo... | [
{
"content": "import torch\nfrom typing import List\nfrom typing import Union\n\nimport syft as sy\nfrom syft.frameworks.torch.tensors.interpreters.abstract import AbstractTensor\nfrom syft.frameworks.torch.tensors.interpreters import AdditiveSharingTensor\nfrom syft.workers import BaseWorker\nfrom syft.framewo... | diff --git a/Makefile b/Makefile
index 7c24dc74d6e..d13f7ae12ec 100644
--- a/Makefile
+++ b/Makefile
@@ -27,7 +27,7 @@ test: venv
(. venv/bin/activate; \
python setup.py install; \
venv/bin/coverage run setup.py test;\
- venv/bin/coverage report -m --fail-under 100;\
+ venv/bin/coverage report -m --fail-under 95;\
)
.PHONY: docs
diff --git a/syft/frameworks/torch/tensors/interpreters/multi_pointer.py b/syft/frameworks/torch/tensors/interpreters/multi_pointer.py
index 986b10c23ed..f3fc7627bc8 100644
--- a/syft/frameworks/torch/tensors/interpreters/multi_pointer.py
+++ b/syft/frameworks/torch/tensors/interpreters/multi_pointer.py
@@ -204,7 +204,7 @@ def simplify(tensor: "MultiPointerTensor") -> tuple:
chain = None
if hasattr(tensor, "child"):
- chain = sy.serde.simplify(tensor.child)
+ chain = sy.serde._simplify(tensor.child)
return (tensor.id, chain)
@staticmethod
diff --git a/test/torch/tensors/test_multi_pointer.py b/test/torch/tensors/test_multi_pointer.py
index 86fbdff16f6..d27581afff1 100644
--- a/test/torch/tensors/test_multi_pointer.py
+++ b/test/torch/tensors/test_multi_pointer.py
@@ -39,3 +39,15 @@ def test_dim(workers):
a = th.tensor([1, 2, 3, 4, 5]).send(bob, alice)
assert a.dim() == 1
+
+
+def test_simplify(workers):
+ bob = workers["bob"]
+ alice = workers["alice"]
+
+ a = th.tensor([1, 2, 3, 4, 5]).send(bob, alice)
+ ser = sy.serde.serialize(a)
+ detail = sy.serde.deserialize(ser).child
+ assert isinstance(detail, sy.MultiPointerTensor)
+ for key in a.child.child:
+ assert key in detail.child
|
learningequality__kolibri-1464 | hide not-recent learners on 'coach - recent activity' tab
See similar issue for channels: https://github.com/learningequality/kolibri/pull/1406
Now we need to do the same thing for when you drill deeper and reach the learners list. For example here, we're showing all learners regardless of whether or not they've had recent activity:

| [
{
"content": "from dateutil.parser import parse\n\nfrom django.db.models import Case, Count, F, IntegerField, Sum, Value as V, When\nfrom django.db.models.functions import Coalesce\nfrom kolibri.auth.models import FacilityUser\nfrom kolibri.content.models import ContentNode\nfrom kolibri.logger.models import Co... | [
{
"content": "from dateutil.parser import parse\n\nfrom django.db.models import Case, Count, F, IntegerField, Sum, Value as V, When\nfrom django.db.models.functions import Coalesce\nfrom kolibri.auth.models import FacilityUser\nfrom kolibri.content.models import ContentNode\nfrom kolibri.logger.models import Co... | diff --git a/kolibri/plugins/coach/assets/src/reportConstants.js b/kolibri/plugins/coach/assets/src/reportConstants.js
index 0cb82afeefe..69f55344c94 100644
--- a/kolibri/plugins/coach/assets/src/reportConstants.js
+++ b/kolibri/plugins/coach/assets/src/reportConstants.js
@@ -24,6 +24,7 @@ const TableColumns = {
EXERCISE: 'exercise_progress',
CONTENT: 'content_progress',
DATE: 'date',
+ GROUP: 'group',
};
const SortOrders = {
@@ -32,10 +33,13 @@ const SortOrders = {
NONE: 'none',
};
+const RECENCY_THRESHOLD_IN_DAYS = 7;
+
module.exports = {
ContentScopes,
UserScopes,
ViewBy,
TableColumns,
SortOrders,
+ RECENCY_THRESHOLD_IN_DAYS,
};
diff --git a/kolibri/plugins/coach/assets/src/state/actions/reports.js b/kolibri/plugins/coach/assets/src/state/actions/reports.js
index 814df65407a..ff2d9dc0fac 100644
--- a/kolibri/plugins/coach/assets/src/state/actions/reports.js
+++ b/kolibri/plugins/coach/assets/src/state/actions/reports.js
@@ -11,13 +11,11 @@ const { now } = require('kolibri.utils.serverClock');
const RecentReportResourceConstructor = require('../../apiResources/recentReport');
const UserReportResourceConstructor = require('../../apiResources/userReport');
-const UserSummaryResourceConstructor = require('../../apiResources/userSummary');
const ContentSummaryResourceConstructor = require('../../apiResources/contentSummary');
const ContentReportResourceConstructor = require('../../apiResources/contentReport');
const RecentReportResource = new RecentReportResourceConstructor(coreApp);
const UserReportResource = new UserReportResourceConstructor(coreApp);
-const UserSummaryResource = new UserSummaryResourceConstructor(coreApp);
const ContentSummaryResource = new ContentSummaryResourceConstructor(coreApp);
const ContentReportResource = new ContentReportResourceConstructor(coreApp);
@@ -26,6 +24,7 @@ const ChannelResource = coreApp.resources.ChannelResource;
const ContentNodeResource = coreApp.resources.ContentNodeResource;
const FacilityUserResource = coreApp.resources.FacilityUserResource;
const SummaryLogResource = coreApp.resources.ContentSummaryLogResource;
+const LearnerGroupResource = coreApp.resources.LearnerGroupResource;
/**
* Helper function for _showChannelList
@@ -34,11 +33,11 @@ const SummaryLogResource = coreApp.resources.ContentSummaryLogResource;
* @returns {Promise} that resolves channel with lastActive value in object:
* { 'channelId': dateOfLastActivity }
*/
-function channelLastActivePromise(channel, classId) {
+function channelLastActivePromise(channel, userScope, userScopeId) {
const summaryPayload = {
channel_id: channel.id,
- collection_kind: ReportConstants.UserScopes.CLASSROOM,
- collection_id: classId,
+ collection_kind: userScope,
+ collection_id: userScopeId,
};
// workaround for conditionalPromise.then() misbehaving
@@ -58,8 +57,10 @@ function channelLastActivePromise(channel, classId) {
);
}
-function getAllChannelsLastActivePromise(channels, classId) {
- const promises = channels.map((channel) => channelLastActivePromise(channel, classId));
+function getAllChannelsLastActivePromise(channels, userScope, userScopeId) {
+ const promises = channels.map(
+ (channel) => channelLastActivePromise(channel, userScope, userScopeId)
+ );
return Promise.all(promises);
}
@@ -77,7 +78,7 @@ function _channelReportState(data) {
}));
}
-function _showChannelList(store, classId, showRecentOnly = false) {
+function _showChannelList(store, classId, userId = null, showRecentOnly = false) {
// don't handle super users
if (coreGetters.isSuperuser(store.state)) {
store.dispatch('SET_PAGE_STATE', {});
@@ -86,19 +87,29 @@ function _showChannelList(store, classId, showRecentOnly = false) {
return Promise.resolve();
}
+ const scope = userId ? ReportConstants.UserScopes.USER : ReportConstants.UserScopes.CLASSROOM;
+ const scopeId = userId || classId;
+
const promises = [
- getAllChannelsLastActivePromise(store.state.core.channels.list, classId),
+ getAllChannelsLastActivePromise(store.state.core.channels.list, scope, scopeId),
setClassState(store, classId),
];
return Promise.all(promises).then(
([allChannelLastActive]) => {
- store.dispatch('SET_RECENT_ONLY', showRecentOnly);
const reportProps = {
- userScope: ReportConstants.UserScopes.CLASSROOM,
- userScopeId: classId,
+ userScope: scope,
+ userScopeId: scopeId,
viewBy: ReportConstants.ViewBy.CHANNEL,
+ showRecentOnly,
};
+ const defaultSortCol = showRecentOnly ?
+ ReportConstants.TableColumns.DATE : ReportConstants.TableColumns.NAME;
+ store.dispatch(
+ 'SET_REPORT_SORTING',
+ defaultSortCol,
+ ReportConstants.SortOrders.DESCENDING
+ );
store.dispatch('SET_REPORT_PROPERTIES', reportProps);
store.dispatch('SET_REPORT_TABLE_DATA', _channelReportState(allChannelLastActive));
store.dispatch('CORE_SET_PAGE_LOADING', false);
@@ -147,12 +158,28 @@ function _recentReportState(data) {
}));
}
-function _learnerReportState(data) {
- if (!data) { return []; }
- return data.map(row => ({
- id: row.pk.toString(), // see https://github.com/learningequality/kolibri/issues/1255
+function _getGroupName(userId, groupData) {
+ const group = groupData.find(g => g.user_ids.includes(userId));
+ return group ? group.name : undefined;
+}
+
+function _rootLearnerReportState(userData, groupData) {
+ return userData.map(row => ({
+ id: row.id,
fullName: row.full_name,
+ username: row.username,
+ groupName: _getGroupName(row.id, groupData),
+ }));
+}
+
+function _learnerReportState(userReportData, groupData) {
+ if (!userReportData) { return []; }
+ return userReportData.map(row => ({
+ id: row.pk,
+ fullName: row.full_name,
+ username: row.username,
lastActive: row.last_active,
+ groupName: _getGroupName(row.pk, groupData),
progress: row.progress.map(progressData => ({
kind: progressData.kind,
timeSpent: progressData.time_spent,
@@ -183,13 +210,6 @@ function _contentSummaryState(data) {
};
}
-function _userSummaryState(data) {
- if (!data) {
- return {};
- }
- return data;
-}
-
function _setContentReport(store, reportPayload) {
const reportPromise = ContentReportResource.getCollection(reportPayload).fetch();
reportPromise.then(report => {
@@ -198,12 +218,14 @@ function _setContentReport(store, reportPayload) {
return reportPromise;
}
-function _setLearnerReport(store, reportPayload) {
- const reportPromise = UserReportResource.getCollection(reportPayload).fetch();
- reportPromise.then(report => {
- store.dispatch('SET_REPORT_TABLE_DATA', _learnerReportState(report));
+function _setLearnerReport(store, reportPayload, classId) {
+ const promises = [
+ UserReportResource.getCollection(reportPayload).fetch(),
+ LearnerGroupResource.getCollection({ parent: classId }).fetch(),
+ ];
+ return Promise.all(promises).then(([usersReport, learnerGroups]) => {
+ store.dispatch('SET_REPORT_TABLE_DATA', _learnerReportState(usersReport, learnerGroups));
});
- return reportPromise;
}
function _setContentSummary(store, contentScopeId, reportPayload) {
@@ -214,24 +236,17 @@ function _setContentSummary(store, contentScopeId, reportPayload) {
return contentPromise;
}
-function _setUserSummary(store, userScopeId, reportPayload) {
- const userPromise = UserSummaryResource.getModel(userScopeId, reportPayload).fetch();
- userPromise.then(userSummary => {
- store.dispatch('SET_REPORT_USER_SUMMARY', _userSummaryState(userSummary));
- });
- return userPromise;
-}
-
function _showContentList(store, options) {
const reportPayload = {
channel_id: options.channelId,
content_node_id: options.contentScopeId,
collection_kind: options.userScope,
- collection_id: options.classId,
+ collection_id: options.userScopeId,
};
const promises = [
_setContentSummary(store, options.contentScopeId, reportPayload),
_setContentReport(store, reportPayload),
+ setClassState(store, options.classId),
];
Promise.all(promises).then(
() => {
@@ -243,6 +258,11 @@ function _showContentList(store, options) {
userScopeId: options.userScopeId,
viewBy: ReportConstants.ViewBy.CONTENT,
};
+ store.dispatch(
+ 'SET_REPORT_SORTING',
+ ReportConstants.TableColumns.NAME,
+ ReportConstants.SortOrders.DESCENDING
+ );
store.dispatch('SET_REPORT_PROPERTIES', reportProps);
store.dispatch('CORE_SET_PAGE_LOADING', false);
},
@@ -259,7 +279,8 @@ function _showLearnerList(store, options) {
};
const promises = [
_setContentSummary(store, options.contentScopeId, reportPayload),
- _setLearnerReport(store, reportPayload),
+ _setLearnerReport(store, reportPayload, options.classId),
+ setClassState(store, options.classId),
];
Promise.all(promises).then(
() => {
@@ -270,7 +291,13 @@ function _showLearnerList(store, options) {
userScope: options.userScope,
userScopeId: options.userScopeId,
viewBy: ReportConstants.ViewBy.LEARNER,
+ showRecentOnly: options.showRecentOnly,
};
+ store.dispatch(
+ 'SET_REPORT_SORTING',
+ ReportConstants.TableColumns.NAME,
+ ReportConstants.SortOrders.DESCENDING
+ );
store.dispatch('SET_REPORT_PROPERTIES', reportProps);
store.dispatch('CORE_SET_PAGE_LOADING', false);
},
@@ -281,58 +308,48 @@ function _showLearnerList(store, options) {
// needs exercise, attemptlog. Pass answerstate into contentrender to display answer
function _showExerciseDetailView(store, classId, userId, channelId, contentId,
attemptLogIndex, interactionIndex) {
- Promise.all([
- ContentNodeResource.getCollection({ channel_id: channelId }, { content_id: contentId }).fetch(),
- AttemptLogResource.getCollection({ user: userId, content: contentId }).fetch(),
- SummaryLogResource.getCollection({ user_id: userId, content_id: contentId }).fetch(),
- FacilityUserResource.getModel(userId).fetch(),
- setClassState(store, classId),
- ]).then(
- ([exercises, attemptLogs, summaryLog, user]) => {
- // MAPPERS NEEDED
- // attemptLogState
- // attemptLogListState
- // interactionState
- // InteractionHistoryState
- // user?
-
- const exercise = exercises[0];
-
- // FIRST LOOP: Sort them by most recent
- attemptLogs.sort(
- (attemptLog1, attemptLog2) =>
- new Date(attemptLog2.end_timestamp) - new Date(attemptLog1.end_timestamp)
- );
-
- const exerciseQuestions = assessmentMetaDataState(exercise).assessmentIds;
- // SECOND LOOP: Add their question number
- if (exerciseQuestions && exerciseQuestions.length) {
- attemptLogs.forEach(
- attemptLog => {
- attemptLog.questionNumber = (exerciseQuestions.indexOf(attemptLog.item) + 1);
- }
+ ContentNodeResource.getModel(contentId, { channel_id: channelId }).fetch().then(
+ exercise => {
+ Promise.all([
+ AttemptLogResource.getCollection({ user: userId, content: exercise.content_id }).fetch(),
+ SummaryLogResource.getCollection(
+ { user_id: userId, content_id: exercise.content_id }
+ ).fetch(),
+ FacilityUserResource.getModel(userId).fetch(),
+ setClassState(store, classId),
+ ]).then(([attemptLogs, summaryLog, user]) => {
+ attemptLogs.sort(
+ (attemptLog1, attemptLog2) =>
+ new Date(attemptLog2.end_timestamp) - new Date(attemptLog1.end_timestamp)
);
- }
-
- const currentAttemptLog = attemptLogs[attemptLogIndex] || {};
-
- const currentInteractionHistory = currentAttemptLog.interaction_history || [];
-
- const pageState = {
- // because this is info returned from a collection
- user,
- exercise,
- attemptLogs,
- currentAttemptLog,
- interactionIndex,
- currentInteractionHistory,
- currentInteraction: currentInteractionHistory[interactionIndex],
- summaryLog: summaryLog[0],
- channelId,
- attemptLogIndex,
- };
- store.dispatch('SET_PAGE_STATE', pageState);
- store.dispatch('CORE_SET_PAGE_LOADING', false);
+ const exerciseQuestions = assessmentMetaDataState(exercise).assessmentIds;
+ // SECOND LOOP: Add their question number
+ if (exerciseQuestions && exerciseQuestions.length) {
+ attemptLogs.forEach(
+ attemptLog => {
+ attemptLog.questionNumber = (exerciseQuestions.indexOf(attemptLog.item) + 1);
+ }
+ );
+ }
+
+ const currentAttemptLog = attemptLogs[attemptLogIndex] || {};
+ const currentInteractionHistory = currentAttemptLog.interaction_history || [];
+ const pageState = {
+ // because this is info returned from a collection
+ user,
+ exercise,
+ attemptLogs,
+ currentAttemptLog,
+ interactionIndex,
+ currentInteractionHistory,
+ currentInteraction: currentInteractionHistory[interactionIndex],
+ summaryLog: summaryLog[0],
+ channelId,
+ attemptLogIndex,
+ };
+ store.dispatch('SET_PAGE_STATE', pageState);
+ store.dispatch('CORE_SET_PAGE_LOADING', false);
+ });
},
error => {
coreActions.handleApiError(store, error);
@@ -353,12 +370,7 @@ function showRecentChannels(store, classId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.RECENT_CHANNELS);
store.dispatch('CORE_SET_TITLE', 'Recent - All channels');
store.dispatch('CORE_SET_PAGE_LOADING', true);
- _showChannelList(store, classId, true /* showRecentOnly */);
- store.dispatch(
- 'SET_REPORT_SORTING',
- ReportConstants.TableColumns.DATE,
- ReportConstants.SortOrders.DESCENDING
- );
+ _showChannelList(store, classId, null, true);
}
@@ -370,17 +382,15 @@ function showRecentItemsForChannel(store, classId, channelId) {
Promise.all([channelPromise, setClassState(store, classId)]).then(
([channelData]) => {
- const sevenDaysAgo = now();
- // this is being set by default in the backend
- // backend date data might be unreliable, though
- sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
+ const threshold = now();
+ threshold.setDate(threshold.getDate() - ReportConstants.RECENCY_THRESHOLD_IN_DAYS);
const reportPayload = {
channel_id: channelId,
content_node_id: channelData.root_pk,
collection_kind: ReportConstants.UserScopes.CLASSROOM,
collection_id: classId,
- last_active_time: sevenDaysAgo,
+ last_active_time: threshold,
};
const recentReportsPromise = RecentReportResource.getCollection(reportPayload).fetch();
@@ -392,6 +402,7 @@ function showRecentItemsForChannel(store, classId, channelId) {
userScope: ReportConstants.UserScopes.CLASSROOM,
userScopeId: classId,
viewBy: ReportConstants.ViewBy.RECENT,
+ showRecentOnly: true,
};
store.dispatch('SET_REPORT_PROPERTIES', reportProps);
store.dispatch(
@@ -422,6 +433,7 @@ function showRecentLearnersForItem(store, classId, channelId, contentId) {
contentScopeId: contentId,
userScope: ReportConstants.UserScopes.CLASSROOM,
userScopeId: classId,
+ showRecentOnly: true,
});
}
@@ -441,7 +453,7 @@ function showTopicChannels(store, classId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.TOPIC_CHANNELS);
store.dispatch('CORE_SET_TITLE', 'Topics - All channels');
store.dispatch('CORE_SET_PAGE_LOADING', true);
- _showChannelList(store, classId);
+ _showChannelList(store, classId, null, false);
}
function showTopicChannelRoot(store, classId, channelId) {
@@ -460,6 +472,7 @@ function showTopicChannelRoot(store, classId, channelId) {
contentScopeId: channelData.root_pk,
userScope: ReportConstants.UserScopes.CLASSROOM,
userScopeId: classId,
+ showRecentOnly: false,
});
},
error => coreActions.handleError(store, error)
@@ -479,6 +492,7 @@ function showTopicItemList(store, classId, channelId, topicId) {
contentScopeId: topicId,
userScope: ReportConstants.UserScopes.CLASSROOM,
userScopeId: classId,
+ showRecentOnly: false,
});
}
@@ -495,6 +509,7 @@ function showTopicLearnersForItem(store, classId, channelId, contentId) {
contentScopeId: contentId,
userScope: ReportConstants.UserScopes.CLASSROOM,
userScopeId: classId,
+ showRecentOnly: false,
});
}
@@ -513,25 +528,76 @@ function showLearnerList(store, classId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.LEARNER_LIST);
store.dispatch('CORE_SET_TITLE', 'Learners');
store.dispatch('CORE_SET_PAGE_LOADING', true);
+
+ const promises = [
+ FacilityUserResource.getCollection({ member_of: classId }).fetch({}, true),
+ LearnerGroupResource.getCollection({ parent: classId }).fetch(),
+ setClassState(store, classId),
+ ];
+
+ Promise.all(promises).then(
+ ([userData, groupData]) => {
+ store.dispatch('SET_REPORT_TABLE_DATA', _rootLearnerReportState(userData, groupData));
+ store.dispatch('SET_REPORT_SORTING',
+ ReportConstants.TableColumns.NAME,
+ ReportConstants.SortOrders.DESCENDING
+ );
+ store.dispatch('SET_REPORT_CONTENT_SUMMARY', {});
+ store.dispatch('SET_REPORT_PROPERTIES', {
+ contentScope: ReportConstants.ContentScopes.ALL,
+ userScope: ReportConstants.UserScopes.CLASSROOM,
+ userScopeId: classId,
+ viewBy: ReportConstants.ViewBy.LEARNER,
+ showRecentOnly: false,
+ });
+ store.dispatch('CORE_SET_PAGE_LOADING', false);
+ },
+ error => coreActions.handleError(store, error)
+ );
}
function showLearnerChannels(store, classId, userId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.LEARNER_CHANNELS);
store.dispatch('CORE_SET_TITLE', 'Learners - All channels');
store.dispatch('CORE_SET_PAGE_LOADING', true);
- _showChannelList(store, classId);
+ _showChannelList(store, classId, userId, false);
}
function showLearnerChannelRoot(store, classId, userId, channelId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.LEARNER_CHANNEL_ROOT);
store.dispatch('CORE_SET_TITLE', 'Learners - Channel');
store.dispatch('CORE_SET_PAGE_LOADING', true);
+
+ const channelPromise = ChannelResource.getModel(channelId).fetch();
+ channelPromise.then(
+ (channelData) => {
+ _showContentList(store, {
+ classId,
+ channelId,
+ contentScope: ReportConstants.ContentScopes.ROOT,
+ contentScopeId: channelData.root_pk,
+ userScope: ReportConstants.UserScopes.USER,
+ userScopeId: userId,
+ showRecentOnly: false,
+ });
+ },
+ error => coreActions.handleError(store, error)
+ );
}
function showLearnerItemList(store, classId, userId, channelId, topicId) {
store.dispatch('SET_PAGE_NAME', Constants.PageNames.LEARNER_ITEM_LIST);
store.dispatch('CORE_SET_TITLE', 'Learners - Items');
store.dispatch('CORE_SET_PAGE_LOADING', true);
+ _showContentList(store, {
+ classId,
+ channelId,
+ contentScope: ReportConstants.ContentScopes.TOPIC,
+ contentScopeId: topicId,
+ userScope: ReportConstants.UserScopes.USER,
+ userScopeId: userId,
+ showRecentOnly: false,
+ });
}
function showLearnerItemDetails(store, classId, userId, channelId, contentId,
@@ -562,5 +628,4 @@ module.exports = {
showLearnerItemList,
showLearnerItemDetails,
setReportSorting,
- _setUserSummary,
};
diff --git a/kolibri/plugins/coach/assets/src/state/getters/reportUtils.js b/kolibri/plugins/coach/assets/src/state/getters/reportUtils.js
index 66cf3b75fbe..8e7a9a72dc0 100644
--- a/kolibri/plugins/coach/assets/src/state/getters/reportUtils.js
+++ b/kolibri/plugins/coach/assets/src/state/getters/reportUtils.js
@@ -38,6 +38,7 @@ function genCompareFunc(sortColumn, sortOrder) {
columnToKey[ReportConstants.TableColumns.EXERCISE] = 'exerciseProgress';
columnToKey[ReportConstants.TableColumns.CONTENT] = 'contentProgress';
columnToKey[ReportConstants.TableColumns.DATE] = 'lastActive';
+ columnToKey[ReportConstants.TableColumns.GROUP] = 'groupName';
const key = columnToKey[sortColumn];
// take into account sort order
diff --git a/kolibri/plugins/coach/assets/src/state/getters/reports.js b/kolibri/plugins/coach/assets/src/state/getters/reports.js
index 422ba520e38..f1e66b8fe5e 100644
--- a/kolibri/plugins/coach/assets/src/state/getters/reports.js
+++ b/kolibri/plugins/coach/assets/src/state/getters/reports.js
@@ -1,8 +1,11 @@
const ReportConstants = require('../../reportConstants');
+const CoachConstants = require('../../constants');
const CoreConstants = require('kolibri.coreVue.vuex.constants');
const logging = require('kolibri.lib.logging');
+const { now } = require('kolibri.utils.serverClock');
const ReportUtils = require('./reportUtils');
const { classMemberCount } = require('./main');
+const differenceInDays = require('date-fns/difference_in_days');
const ContentNodeKinds = CoreConstants.ContentNodeKinds;
@@ -22,15 +25,19 @@ function _genRow(state, item) {
row.kind = CoreConstants.USER;
row.id = item.id;
row.title = item.fullName;
+ row.groupName = item.groupName;
row.parent = undefined; // not currently used. Eventually, maybe classes/groups?
- // for learners, the exercise counts are the global values
- row.exerciseProgress = ReportUtils.calcProgress(
- item.progress, ReportUtils.onlyExercises, getters.exerciseCount(state), 1
- );
- row.contentProgress = ReportUtils.calcProgress(
- item.progress, ReportUtils.onlyContent, getters.contentCount(state), 1
- );
+ // for root list (of channels) we don't currently calculate progress
+ if (state.pageName !== CoachConstants.PageNames.LEARNER_LIST) {
+ // for learners, the exercise counts are the global values
+ row.exerciseProgress = ReportUtils.calcProgress(
+ item.progress, ReportUtils.onlyExercises, getters.exerciseCount(state), 1
+ );
+ row.contentProgress = ReportUtils.calcProgress(
+ item.progress, ReportUtils.onlyContent, getters.contentCount(state), 1
+ );
+ }
} else if (state.pageState.viewBy === ReportConstants.ViewBy.CHANNEL) {
row.id = item.id;
row.title = item.title;
@@ -38,6 +45,7 @@ function _genRow(state, item) {
// CONTENT NODES
row.kind = item.kind;
row.id = item.id;
+ row.contentId = item.contentId;
row.title = item.title;
row.parent = { id: item.parent.id, title: item.parent.title };
@@ -135,6 +143,12 @@ Object.assign(getters, {
if (state.pageState.sortOrder !== ReportConstants.SortOrders.NONE) {
data.sort(ReportUtils.genCompareFunc(state.pageState.sortColumn, state.pageState.sortOrder));
}
+ if (state.pageState.showRecentOnly) {
+ return data.filter(row =>
+ Boolean(row.lastActive) &&
+ differenceInDays(now(), row.lastActive) <= ReportConstants.RECENCY_THRESHOLD_IN_DAYS
+ );
+ }
return data;
},
});
diff --git a/kolibri/plugins/coach/assets/src/state/store.js b/kolibri/plugins/coach/assets/src/state/store.js
index b707b372f99..ae4a27bdd02 100644
--- a/kolibri/plugins/coach/assets/src/state/store.js
+++ b/kolibri/plugins/coach/assets/src/state/store.js
@@ -24,9 +24,6 @@ const mutations = {
},
// report
- SET_RECENT_ONLY(state, showRecentOnly) {
- Vue.set(state.pageState, 'showRecentOnly', showRecentOnly);
- },
SET_REPORT_SORTING(state, sortColumn, sortOrder) {
Vue.set(state.pageState, 'sortColumn', sortColumn);
Vue.set(state.pageState, 'sortOrder', sortOrder);
@@ -38,6 +35,7 @@ const mutations = {
Vue.set(state.pageState, 'userScope', options.userScope);
Vue.set(state.pageState, 'userScopeId', options.userScopeId);
Vue.set(state.pageState, 'viewBy', options.viewBy);
+ Vue.set(state.pageState, 'showRecentOnly', options.showRecentOnly);
},
SET_REPORT_TABLE_DATA(state, tableData) {
Vue.set(state.pageState, 'tableData', tableData);
diff --git a/kolibri/plugins/coach/assets/src/views/class-list-page/index.vue b/kolibri/plugins/coach/assets/src/views/class-list-page/index.vue
index 838ad4db28d..469eb969eaf 100644
--- a/kolibri/plugins/coach/assets/src/views/class-list-page/index.vue
+++ b/kolibri/plugins/coach/assets/src/views/class-list-page/index.vue
@@ -58,7 +58,7 @@
methods: {
recentPageLink(id) {
return {
- name: constants.PageNames.RECENT_CHANNELS,
+ name: constants.PageNames.TOPIC_CHANNELS,
params: { classId: id },
};
},
diff --git a/kolibri/plugins/coach/assets/src/views/exam-report-page/index.vue b/kolibri/plugins/coach/assets/src/views/exam-report-page/index.vue
index 456420fa2f2..e354d738068 100644
--- a/kolibri/plugins/coach/assets/src/views/exam-report-page/index.vue
+++ b/kolibri/plugins/coach/assets/src/views/exam-report-page/index.vue
@@ -49,11 +49,11 @@
</td>
<td class="table-data">
- <span v-if="examTaker.score === undefined">—</span>
+ <span v-if="examTaker.score === undefined">–</span>
<span v-else>{{ $tr('scorePercentage', { num: examTaker.score / exam.question_count }) }}</span>
</td>
- <td class="table-data">{{ examTaker.group.name || $tr('ungrouped') }}</td>
+ <td class="table-data">{{ examTaker.group.name || '–' }}</td>
</tr>
</tbody>
</table>
@@ -126,7 +126,6 @@
scorePercentage: '{num, number, percent}',
group: 'Group',
noExamData: 'No data to show.',
- ungrouped: 'Ungrouped',
},
};
diff --git a/kolibri/plugins/coach/assets/src/views/index.vue b/kolibri/plugins/coach/assets/src/views/index.vue
index 23285ee0b19..18bec3814b3 100644
--- a/kolibri/plugins/coach/assets/src/views/index.vue
+++ b/kolibri/plugins/coach/assets/src/views/index.vue
@@ -77,11 +77,11 @@
[Constants.PageNames.TOPIC_ITEM_LIST]: 'item-list-page',
[Constants.PageNames.TOPIC_LEARNERS_FOR_ITEM]: 'learner-list-page',
[Constants.PageNames.TOPIC_LEARNER_ITEM_DETAILS]: 'learner-exercise-detail-page',
- [Constants.PageNames.LEARNER_LIST]: 'item-list-page',
+ [Constants.PageNames.LEARNER_LIST]: 'learner-list-page',
[Constants.PageNames.LEARNER_CHANNELS]: 'channel-list-page',
[Constants.PageNames.LEARNER_CHANNEL_ROOT]: 'item-list-page',
[Constants.PageNames.LEARNER_ITEM_LIST]: 'item-list-page',
- [Constants.PageNames.LEARNER_ITEM_DETAILS]: 'learner-item-details-page',
+ [Constants.PageNames.LEARNER_ITEM_DETAILS]: 'learner-exercise-detail-page',
[Constants.PageNames.EXAM_REPORT]: 'exam-report-page',
[Constants.PageNames.EXAM_REPORT_DETAIL]: 'exam-report-detail-page',
};
diff --git a/kolibri/plugins/coach/assets/src/views/reports/channel-list-page.vue b/kolibri/plugins/coach/assets/src/views/reports/channel-list-page.vue
index 916b7982c62..e9e23d838f6 100644
--- a/kolibri/plugins/coach/assets/src/views/reports/channel-list-page.vue
+++ b/kolibri/plugins/coach/assets/src/views/reports/channel-list-page.vue
@@ -3,11 +3,10 @@
<div>
<div v-if="showRecentOnly" ref="recentHeader">
<h1>{{ $tr('recentTitle') }}</h1>
- <sub v-if="anyActivity">{{ $tr('recentSubHeading') }}</sub>
- <sub v-else>{{ $tr('noRecentSubHeading') }}</sub>
+ <report-subheading />
</div>
- <report-table v-if="anyActivity" :caption="$tr('channelList')">
+ <report-table v-if="standardDataTable.length" :caption="$tr('channelList')">
<thead slot="thead">
<tr>
<header-cell
@@ -24,7 +23,7 @@
</thead>
<tbody slot="tbody">
<template v-for="channel in standardDataTable">
- <tr v-if="channelIsVisible(channel.lastActive)" :key="channel.id">
+ <tr :key="channel.id">
<name-cell :kind="CHANNEL" :title="channel.title" :link="reportLink(channel.id)"/>
<activity-cell :date="channel.lastActive"/>
</tr>
@@ -40,8 +39,6 @@
const { ContentNodeKinds } = require('kolibri.coreVue.vuex.constants');
const { PageNames } = require('../../constants');
- const differenceInDays = require('date-fns/difference_in_days');
- const { now } = require('kolibri.utils.serverClock');
const reportConstants = require('../../reportConstants');
const reportGetters = require('../../state/getters/reports');
@@ -50,19 +47,13 @@
$trNameSpace: 'coachRecentPageChannelList',
$trs: {
recentTitle: 'Recent Activity',
- recentSubHeading: 'Showing recent activity in past 7 days',
- noRecentSubHeading: 'No recent activity in past 7 days',
channels: 'Channels',
channelList: 'Channel list',
lastActivity: 'Last active',
},
- data() {
- return {
- currentDateTime: now(),
- };
- },
components: {
'report-table': require('./report-table'),
+ 'report-subheading': require('./report-subheading'),
'header-cell': require('./table-cells/header-cell'),
'name-cell': require('./table-cells/name-cell'),
'activity-cell': require('./table-cells/activity-cell'),
@@ -74,19 +65,8 @@
tableColumns() {
return reportConstants.TableColumns;
},
- anyActivity() {
- return this.standardDataTable.some(channel => this.channelIsVisible(channel.lastActive));
- },
},
methods: {
- channelIsVisible(lastActiveTime) {
- const THREHOLD_IN_DAYS = 7;
- if (!this.showRecentOnly) return true;
- return (
- Boolean(lastActiveTime) &&
- differenceInDays(this.currentDateTime, lastActiveTime) <= THREHOLD_IN_DAYS
- );
- },
reportLink(channelId) {
const linkTargets = {
[PageNames.RECENT_CHANNELS]: PageNames.RECENT_ITEMS_FOR_CHANNEL,
diff --git a/kolibri/plugins/coach/assets/src/views/reports/item-list-page.vue b/kolibri/plugins/coach/assets/src/views/reports/item-list-page.vue
index cd3dcda5ffb..23e098c6b96 100644
--- a/kolibri/plugins/coach/assets/src/views/reports/item-list-page.vue
+++ b/kolibri/plugins/coach/assets/src/views/reports/item-list-page.vue
@@ -87,24 +87,47 @@
},
methods: {
genRowLink(row) {
- if (row.kind === CoreConstants.ContentNodeKinds.TOPIC) {
+ if (CoachConstants.TopicReports.includes(this.pageName)) {
+ if (row.kind === CoreConstants.ContentNodeKinds.TOPIC) {
+ return {
+ name: CoachConstants.PageNames.TOPIC_ITEM_LIST,
+ params: {
+ classId: this.classId,
+ channelId: this.pageState.channelId,
+ topicId: row.id,
+ },
+ };
+ }
return {
- name: CoachConstants.PageNames.TOPIC_ITEM_LIST,
+ name: CoachConstants.PageNames.TOPIC_LEARNERS_FOR_ITEM,
params: {
classId: this.classId,
channelId: this.pageState.channelId,
- topicId: row.id,
- }
+ contentId: row.id,
+ },
};
- }
- return {
- name: CoachConstants.PageNames.TOPIC_LEARNERS_FOR_ITEM,
- params: {
- classId: this.classId,
- channelId: this.pageState.channelId,
- contentId: row.id,
+ } else if (CoachConstants.LearnerReports.includes(this.pageName)) {
+ if (row.kind === CoreConstants.ContentNodeKinds.TOPIC) {
+ return {
+ name: CoachConstants.PageNames.LEARNER_ITEM_LIST,
+ params: {
+ classId: this.classId,
+ channelId: this.pageState.channelId,
+ topicId: row.id,
+ },
+ };
+ } else if (row.kind === CoreConstants.ContentNodeKinds.EXERCISE) {
+ return {
+ name: CoachConstants.PageNames.LEARNER_ITEM_DETAILS_ROOT,
+ params: {
+ classId: this.classId,
+ channelId: this.pageState.channelId,
+ contentId: row.id,
+ },
+ };
}
- };
+ }
+ return null;
},
},
computed: {
@@ -115,6 +138,7 @@
vuex: {
getters: {
classId: state => state.classId,
+ pageName: state => state.pageName,
pageState: state => state.pageState,
exerciseCount: reportGetters.exerciseCount,
contentCount: reportGetters.contentCount,
diff --git a/kolibri/plugins/coach/assets/src/views/reports/learner-exercise-detail-page/index.vue b/kolibri/plugins/coach/assets/src/views/reports/learner-exercise-detail-page/index.vue
index fbf9b9f3150..1e8d4089661 100644
--- a/kolibri/plugins/coach/assets/src/views/reports/learner-exercise-detail-page/index.vue
+++ b/kolibri/plugins/coach/assets/src/views/reports/learner-exercise-detail-page/index.vue
@@ -1,9 +1,6 @@
<template>
- <immersive-full-screen
- :backPageLink="backPageLink"
- :backPageText="$tr('backPrompt', { exerciseTitle: exercise.title })"
- >
+ <immersive-full-screen :backPageLink="backPageLink" :backPageText="backPageText">
<template>
<div class="summary-container">
<attempt-summary
@@ -57,7 +54,7 @@
module.exports = {
$trNameSpace: 'coachExerciseRenderPage',
$trs: {
- backPrompt: 'Back to { exerciseTitle }',
+ backPrompt: 'Back to { backTitle }',
},
components: {
'immersive-full-screen': require('kolibri.coreVue.components.immersiveFullScreen'),
@@ -74,7 +71,7 @@
params: {
classId: this.classId,
channelId: this.channelId,
- contentId: this.contentId,
+ contentId: this.exercise.pk,
}
};
}
@@ -84,31 +81,41 @@
params: {
classId: this.classId,
channelId: this.channelId,
- contentId: this.contentId,
+ contentId: this.exercise.pk,
}
};
}
- return {
- name: constants.PageNames.LEARNER_ITEM_LIST,
- params: {
- classId: this.classId,
- channelId: this.channelId,
- contentId: this.contentId,
- }
- };
+ if (this.pageName === constants.PageNames.LEARNER_ITEM_DETAILS) {
+ return {
+ name: constants.PageNames.LEARNER_ITEM_LIST,
+ params: {
+ classId: this.classId,
+ channelId: this.channelId,
+ userId: this.user.id,
+ topicId: this.parentTopic.pk,
+ }
+ };
+ }
+ return undefined;
+ },
+ backPageText() {
+ if (constants.LearnerReports.includes(this.pageName)) {
+ return this.$tr('backPrompt', { backTitle: this.parentTopic.title });
+ }
+ return this.$tr('backPrompt', { backTitle: this.exercise.title });
+ },
+ parentTopic() {
+ return this.exercise.ancestors[this.exercise.ancestors.length - 1];
},
},
methods: {
- backtoText(text) {
- return this.$tr('backto', { text });
- },
navigateToNewAttempt(attemptLogIndex) {
this.$router.push({
name: this.pageName,
params: {
channelId: this.channelId,
userId: this.user.id,
- contentId: this.exercise.content_id,
+ contentId: this.exercise.pk,
interactionIndex: 0,
attemptLogIndex,
},
@@ -120,7 +127,7 @@
params: {
channelId: this.channelId,
userId: this.user.id,
- contentId: this.exercise.content_id,
+ contentId: this.exercise.pk,
attemptLogIndex: this.attemptLogIndex,
interactionIndex,
},
@@ -136,7 +143,6 @@
currentInteraction: state => state.pageState.currentInteraction,
currentInteractionHistory: state => state.pageState.currentInteractionHistory,
classId: state => state.classId,
- contentId: state => state.pageState.exercise.pk,
channelId: state => state.pageState.channelId,
user: state => state.pageState.user,
exercise: state => state.pageState.exercise,
diff --git a/kolibri/plugins/coach/assets/src/views/reports/learner-list-page.vue b/kolibri/plugins/coach/assets/src/views/reports/learner-list-page.vue
index 3dd47f46362..8f7c39a66c0 100644
--- a/kolibri/plugins/coach/assets/src/views/reports/learner-list-page.vue
+++ b/kolibri/plugins/coach/assets/src/views/reports/learner-list-page.vue
@@ -3,20 +3,43 @@
<div>
<breadcrumbs/>
- <h1>
+ <h1 v-if="!isRootLearnerPage">
<content-icon
:kind="pageState.contentScopeSummary.kind"
colorstyle="text-default"
/>
{{ pageState.contentScopeSummary.title }}
</h1>
+ <report-subheading />
<report-table>
<thead slot="thead">
<tr>
- <header-cell :text="$tr('name')" align="left"/>
- <header-cell :text="isExercisePage ? $tr('exerciseProgress') : $tr('contentProgress')"/>
- <header-cell :text="$tr('lastActivity')" align="left"/>
+ <header-cell
+ align="left"
+ :text="$tr('name')"
+ :column="TableColumns.NAME"
+ :sortable="true"
+ />
+ <header-cell
+ v-if="!isRootLearnerPage"
+ :text="isExercisePage ? $tr('exerciseProgress') : $tr('contentProgress')"
+ :column="isExercisePage ? TableColumns.EXERCISE : TableColumns.CONTENT"
+ :sortable="true"
+ />
+ <header-cell
+ align="left"
+ :text="$tr('group')"
+ :column="TableColumns.GROUP"
+ :sortable="true"
+ />
+ <header-cell
+ align="left"
+ v-if="!isRootLearnerPage"
+ :text="$tr('lastActivity')"
+ :column="TableColumns.DATE"
+ :sortable="true"
+ />
</tr>
</thead>
<tbody slot="tbody">
@@ -27,10 +50,12 @@
:link="genLink(row)"
/>
<progress-cell
+ v-if="!isRootLearnerPage"
:num="isExercisePage ? row.exerciseProgress : row.contentProgress"
:isExercise="isExercisePage"
/>
- <activity-cell :date="row.lastActive" />
+ <td>{{ row.groupName || '–' }}</td>
+ <activity-cell v-if="!isRootLearnerPage" :date="row.lastActive" />
</tr>
</tbody>
</report-table>
@@ -45,11 +70,13 @@
const CoreConstants = require('kolibri.coreVue.vuex.constants');
const CoachConstants = require('../../constants');
const reportGetters = require('../../state/getters/reports');
+ const ReportConstants = require('../../reportConstants');
module.exports = {
$trNameSpace: 'learnerReportPage',
$trs: {
name: 'Name',
+ group: 'Group',
exerciseProgress: 'Exercise progress',
contentProgress: 'Resource progress',
lastActivity: 'Last activity',
@@ -60,6 +87,7 @@
'content-icon': require('kolibri.coreVue.components.contentIcon'),
'breadcrumbs': require('./breadcrumbs'),
'report-table': require('./report-table'),
+ 'report-subheading': require('./report-subheading'),
'header-cell': require('./table-cells/header-cell'),
'name-cell': require('./table-cells/name-cell'),
'progress-cell': require('./table-cells/progress-cell'),
@@ -69,6 +97,12 @@
isExercisePage() {
return this.pageState.contentScopeSummary.kind === CoreConstants.ContentNodeKinds.EXERCISE;
},
+ isRootLearnerPage() {
+ return this.pageName === CoachConstants.PageNames.LEARNER_LIST;
+ },
+ TableColumns() {
+ return ReportConstants.TableColumns;
+ },
},
methods: {
genLink(row) {
@@ -82,7 +116,15 @@
classId: this.classId,
userId: row.id,
channelId: this.pageState.channelId,
- contentId: this.pageState.contentScopeSummary.contentId,
+ contentId: this.pageState.contentScopeSummary.id,
+ }
+ };
+ } else if (this.isRootLearnerPage) {
+ return {
+ name: CoachConstants.PageNames.LEARNER_CHANNELS,
+ params: {
+ classId: this.classId,
+ userId: row.id,
}
};
}
diff --git a/kolibri/plugins/coach/assets/src/views/reports/recent-items-page.vue b/kolibri/plugins/coach/assets/src/views/reports/recent-items-page.vue
index 7aa8416fff4..081872ed876 100644
--- a/kolibri/plugins/coach/assets/src/views/reports/recent-items-page.vue
+++ b/kolibri/plugins/coach/assets/src/views/reports/recent-items-page.vue
@@ -4,8 +4,7 @@
<breadcrumbs/>
<h1>{{ $tr('title') }}</h1>
- <sub v-if="standardDataTable.length">{{ $tr('subHeading') }}</sub>
- <sub v-else>{{ $tr('noRecentProgress') }}</sub>
+ <report-subheading />
<report-table v-if="standardDataTable.length">
<thead slot="thead">
@@ -61,10 +60,8 @@
$trNameSpace: 'coachRecentReports',
$trs: {
title: 'Recent Activity',
- subHeading: 'Showing recent activity in past 7 days',
name: 'Name',
progress: 'Class progress',
- noRecentProgress: 'No recent activity in past 7 days',
reportProgress: '{completed} {descriptor}',
listened: '{proportionCompleted} listened',
opened: '{proportionCompleted} opened',
@@ -75,6 +72,7 @@
components: {
'breadcrumbs': require('./breadcrumbs'),
'report-table': require('./report-table'),
+ 'report-subheading': require('./report-subheading'),
'header-cell': require('./table-cells/header-cell'),
'name-cell': require('./table-cells/name-cell'),
'activity-cell': require('./table-cells/activity-cell'),
diff --git a/kolibri/plugins/coach/assets/src/views/reports/report-subheading.vue b/kolibri/plugins/coach/assets/src/views/reports/report-subheading.vue
new file mode 100644
index 00000000000..90ed2bd2b06
--- /dev/null
+++ b/kolibri/plugins/coach/assets/src/views/reports/report-subheading.vue
@@ -0,0 +1,38 @@
+<template>
+
+ <div v-if="showRecentOnly">
+ <sub v-if="standardDataTable.length">{{ $tr('subHeading', { threshold }) }}</sub>
+ <sub v-else>{{ $tr('noRecentProgress', { threshold }) }}</sub>
+ </div>
+
+</template>
+
+
+<script>
+
+ const ReportConstants = require('../../reportConstants');
+ const reportGetters = require('../../state/getters/reports');
+
+ module.exports = {
+ $trNameSpace: 'coachReportSubheading',
+ $trs: {
+ subHeading: 'Only showing activity in past {threshold} days',
+ noRecentProgress: 'No activity in past {threshold} days',
+ },
+ computed: {
+ threshold() {
+ return ReportConstants.RECENCY_THRESHOLD_IN_DAYS;
+ },
+ },
+ vuex: {
+ getters: {
+ standardDataTable: reportGetters.standardDataTable,
+ showRecentOnly: state => state.pageState.showRecentOnly,
+ },
+ },
+ };
+
+</script>
+
+
+<style lang="stylus" scoped></style>
diff --git a/kolibri/plugins/coach/assets/src/views/top-nav/index.vue b/kolibri/plugins/coach/assets/src/views/top-nav/index.vue
index 73591b3c6b6..15f038654b4 100644
--- a/kolibri/plugins/coach/assets/src/views/top-nav/index.vue
+++ b/kolibri/plugins/coach/assets/src/views/top-nav/index.vue
@@ -1,33 +1,31 @@
<template>
<div class="top">
- <nav-link
- :to="recentLink"
- :active="isRecentPage"
- :text="$tr('recent')"
- />
<nav-link
:to="topicsLink"
:active="isTopicPage"
:text="$tr('topics')"
/>
<nav-link
- :to="examsLink"
- :active="Constants.ExamPages.includes(pageName)"
- :text="$tr('exams')"
+ :to="recentLink"
+ :active="isRecentPage"
+ :text="$tr('recent')"
/>
- <!--
<nav-link
:to="learnersLink"
:active="isLearnerPage"
:text="$tr('learners')"
/>
- -->
<nav-link
:to="groupsLink"
:active="pageName === Constants.PageNames.GROUPS"
:text="$tr('groups')"
/>
+ <nav-link
+ :to="examsLink"
+ :active="Constants.ExamPages.includes(pageName)"
+ :text="$tr('exams')"
+ />
</div>
</template>
diff --git a/kolibri/plugins/coach/assets/test/views/channel-list-page.spec.js b/kolibri/plugins/coach/assets/test/views/channel-list-page.spec.js
index aef8d2f6cee..add5f7e1b25 100644
--- a/kolibri/plugins/coach/assets/test/views/channel-list-page.spec.js
+++ b/kolibri/plugins/coach/assets/test/views/channel-list-page.spec.js
@@ -50,6 +50,7 @@ function makeVm(options = {}, state) {
});
const components = {
'name-cell': '<div></div>',
+ 'report-subheading': '<div></div>',
};
const Ctor = Vue.extend(ChannelListPage);
return new Ctor(Object.assign(options, { store, components })).$mount();
diff --git a/kolibri/plugins/coach/assets/test/views/exam-report-page.spec.js b/kolibri/plugins/coach/assets/test/views/exam-report-page.spec.js
index 319e9794a75..4ac6e63d09d 100644
--- a/kolibri/plugins/coach/assets/test/views/exam-report-page.spec.js
+++ b/kolibri/plugins/coach/assets/test/views/exam-report-page.spec.js
@@ -81,6 +81,6 @@ describe('exam report page', () => {
// score isn't properly formatted
assert.equal(getTextInScoreColumn(els.tableRows()[0]), '{num, number, percent} ');
// emdash
- assert.equal(getTextInScoreColumn(els.tableRows()[1]), '\u2014 ');
+ assert.equal(getTextInScoreColumn(els.tableRows()[1]), '– ');
});
});
diff --git a/kolibri/plugins/coach/serializers.py b/kolibri/plugins/coach/serializers.py
index 773e3083049..b1fe23f26f4 100644
--- a/kolibri/plugins/coach/serializers.py
+++ b/kolibri/plugins/coach/serializers.py
@@ -18,7 +18,7 @@ class UserReportSerializer(serializers.ModelSerializer):
class Meta:
model = FacilityUser
fields = (
- 'pk', 'full_name', 'progress', 'last_active',
+ 'pk', 'username', 'full_name', 'progress', 'last_active',
)
def get_progress(self, target_user):
|
googleapis__google-cloud-python-5375 | Updated SubscriberClient docs
`subscribe_experimental` was promoted to `subscribe` but the docs for the `SubscriberClient` still suggested using `subscribe_experimental`
| [
{
"content": "# Copyright 2017, Google LLC 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# Unless... | [
{
"content": "# Copyright 2017, Google LLC 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# Unless... | diff --git a/pubsub/google/cloud/pubsub_v1/subscriber/client.py b/pubsub/google/cloud/pubsub_v1/subscriber/client.py
index b567ed6cb9f2..c4906bbbeb21 100644
--- a/pubsub/google/cloud/pubsub_v1/subscriber/client.py
+++ b/pubsub/google/cloud/pubsub_v1/subscriber/client.py
@@ -135,7 +135,7 @@ def callback(message):
print(message)
message.ack()
- future = subscriber.subscribe_experimental(
+ future = subscriber.subscribe(
subscription, callback)
try:
|
liqd__a4-product-655 | Error 500 when trying to edit landing page
I need to add a partner to the landing page on beteiligung.in productive soon. Currently, I can’t edit the page (500 error).
https://www.beteiligung.in/admin/pages/3/edit/
Could you look into it?
| [
{
"content": "\"\"\"Django settings for Beteiligung.in.\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nfrom django.utils.translation import ugettext_lazy as _\n\nCONFIG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_DIR = os.path.dirnam... | [
{
"content": "\"\"\"Django settings for Beteiligung.in.\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nfrom django.utils.translation import ugettext_lazy as _\n\nCONFIG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_DIR = os.path.dirnam... | diff --git a/liqd_product/config/settings/base.py b/liqd_product/config/settings/base.py
index 83ee5957d..42e41e75f 100644
--- a/liqd_product/config/settings/base.py
+++ b/liqd_product/config/settings/base.py
@@ -444,3 +444,9 @@
# The default language is used for emails and strings
# that are stored translated to the database.
DEFAULT_LANGUAGE = 'de'
+
+WAGTAILADMIN_RICH_TEXT_EDITORS = {
+ 'default': {
+ 'WIDGET': 'wagtail.admin.rich_text.HalloRichTextArea'
+ }
+}
|
bids-standard__pybids-467 | Improved reprs for SQLAlchemy model objects
This should help provide more useful exception messages for obscure SQLAlchemy error conditions. And just be generally more readable in a REPL.
Related to #465.
Including a .json sidecar for events.tsv files causes a SQLAlchemy Tag conflict
We have an fMRIPrep user experiencing the following issue (more details here https://neurostars.org/t/naming-of-bids-events-tsv-files-seems-to-disrupt-fmriprep-1-5-0rc1/4771):
```
File "/usr/local/miniconda/lib/python3.7/site-packages/fmriprep/cli/run.py", line 524, in build_workflow
layout = BIDSLayout(str(bids_dir), validate=False)
File "/usr/local/miniconda/lib/python3.7/site-packages/bids/layout/layout.py", line 212, in __init__
indexer.index_metadata()
File "/usr/local/miniconda/lib/python3.7/site-packages/bids/layout/index.py", line 338, in index_metadata
self.session.commit()
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1027, in commit
self.transaction.commit()
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 494, in commit
self._prepare_impl()
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 473, in _prepare_impl
self.session.flush()
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2459, in flush
self._flush(objects)
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2597, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 153, in reraise
raise value
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2557, in _flush
flush_context.execute()
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 213, in save_obj
) in _organize_states_for_save(base_mapper, states, uowtransaction):
File "/usr/local/miniconda/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 408, in _organize_states_for_save
% (state_str(state), instance_key, state_str(existing))
sqlalchemy.orm.exc.FlushError: New instance <Tag at 0x2b66784f7ba8> with identity key (<class 'bids.layout.models.Tag'>, ('/inp/sub-02/func/sub-02_task-Emotion_run-1_events.tsv', 'run'), None) conflicts with persistent instance <Tag at 0x2b66784c6630>
```
| [
{
"content": "from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\nfrom sqlalchemy import (Column, Integer, String, Boolean, ForeignKey, Table)\nfrom sqlalchemy.orm import recon... | [
{
"content": "from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\nfrom sqlalchemy import (Column, Integer, String, Boolean, ForeignKey, Table)\nfrom sqlalchemy.orm import recon... | diff --git a/bids/layout/models.py b/bids/layout/models.py
index 41f49596e..997e7a63d 100644
--- a/bids/layout/models.py
+++ b/bids/layout/models.py
@@ -491,6 +491,10 @@ def __init__(self, file, entity, value, dtype=None):
self._dtype = dtype
self._init_on_load()
+
+ def __repr__(self):
+ msg = "<Tag file:{!r} entity:{!r} value:{!r}>"
+ return msg.format(self.file_path, self.entity_name, self.value)
@reconstructor
def _init_on_load(self):
diff --git a/bids/layout/tests/test_models.py b/bids/layout/tests/test_models.py
index b9075f5e9..fce088649 100644
--- a/bids/layout/tests/test_models.py
+++ b/bids/layout/tests/test_models.py
@@ -97,6 +97,13 @@ def test_file_associations():
assert set(results) == {md1, md2}
+def test_tag_init(sample_bidsfile, subject_entity):
+ f, e = sample_bidsfile, subject_entity
+ tag = Tag(f, e, 'zzz')
+ rep = str(tag)
+ assert rep.startswith("<Tag file:") and f.path in rep and 'zzz' in rep
+
+
def test_tag_dtype(sample_bidsfile, subject_entity):
f, e = sample_bidsfile, subject_entity
# Various ways of initializing--should all give same result
|
uccser__cs-unplugged-537 | Center navbar menu text on mobile devices

Always display curriculum areas for learning outcomes on a new line
This prevents a confusing interface, like so:

| [
{
"content": "\"\"\"Views for the topics application.\"\"\"\n\nfrom django.shortcuts import get_object_or_404\nfrom django.views import generic\nfrom django.http import JsonResponse, Http404\nfrom config.templatetags.render_html_field import render_html_with_static\nfrom utils.group_lessons_by_age import group_... | [
{
"content": "\"\"\"Views for the topics application.\"\"\"\n\nfrom django.shortcuts import get_object_or_404\nfrom django.views import generic\nfrom django.http import JsonResponse, Http404\nfrom config.templatetags.render_html_field import render_html_with_static\nfrom utils.group_lessons_by_age import group_... | diff --git a/csunplugged/static/img/topics/kids-parity-trick.png b/csunplugged/static/img/topics/kids-parity-trick.jpg
similarity index 100%
rename from csunplugged/static/img/topics/kids-parity-trick.png
rename to csunplugged/static/img/topics/kids-parity-trick.jpg
diff --git a/csunplugged/static/img/topics/sorting-network-variation-alphabet.png b/csunplugged/static/img/topics/sorting-network-variation-alphabet.jpg
similarity index 100%
rename from csunplugged/static/img/topics/sorting-network-variation-alphabet.png
rename to csunplugged/static/img/topics/sorting-network-variation-alphabet.jpg
diff --git a/csunplugged/static/img/topics/sorting-network-variation-aural.png b/csunplugged/static/img/topics/sorting-network-variation-aural.jpg
similarity index 100%
rename from csunplugged/static/img/topics/sorting-network-variation-aural.png
rename to csunplugged/static/img/topics/sorting-network-variation-aural.jpg
diff --git a/csunplugged/static/img/topics/sorting-network-variation-music.png b/csunplugged/static/img/topics/sorting-network-variation-music.jpg
similarity index 100%
rename from csunplugged/static/img/topics/sorting-network-variation-music.png
rename to csunplugged/static/img/topics/sorting-network-variation-music.jpg
diff --git a/csunplugged/static/img/topics/sorting-network-variation-words-2.png b/csunplugged/static/img/topics/sorting-network-variation-words-2.jpg
similarity index 100%
rename from csunplugged/static/img/topics/sorting-network-variation-words-2.png
rename to csunplugged/static/img/topics/sorting-network-variation-words-2.jpg
diff --git a/csunplugged/static/img/topics/sorting-network-variation-words.png b/csunplugged/static/img/topics/sorting-network-variation-words.jpg
similarity index 100%
rename from csunplugged/static/img/topics/sorting-network-variation-words.png
rename to csunplugged/static/img/topics/sorting-network-variation-words.jpg
diff --git a/csunplugged/static/scss/website.scss b/csunplugged/static/scss/website.scss
index 550cc9a50..51e35a64d 100644
--- a/csunplugged/static/scss/website.scss
+++ b/csunplugged/static/scss/website.scss
@@ -13,7 +13,7 @@ $ct-pattern: #82358C;
img {
&.content-image {
- max-height: 10em;
+ max-height: 18em;
}
&.inline-image {
max-height: 3rem;
@@ -100,6 +100,7 @@ $rounded-corner-radius: 0.5rem;
transition: 0.1s;
display: flex;
flex-direction: column;
+ text-align: center;
align-items: center;
justify-content: space-around;
&.link-box-md-3 {
@@ -122,8 +123,6 @@ $rounded-corner-radius: 0.5rem;
}
h2,
h3 {
- margin-bottom: 0;
- text-align: center;
color: $gray;
}
&:hover {
diff --git a/csunplugged/templates/base.html b/csunplugged/templates/base.html
index ed92f438a..5c5d19023 100644
--- a/csunplugged/templates/base.html
+++ b/csunplugged/templates/base.html
@@ -35,7 +35,7 @@
2.0 sneak peek
</a>
<div class="collapse navbar-collapse" id="navbarNav">
- <div class="navbar-nav ml-auto">
+ <div class="navbar-nav ml-auto text-center">
<a class="nav-item nav-link" href="{% url 'topics:index' %}">Topics</a>
<a class="nav-item nav-link" href="{% url 'resources:index' %}">Resources</a>
<a class="nav-item nav-link" href="{% url 'general:about' %}">About</a>
diff --git a/csunplugged/templates/topics/index.html b/csunplugged/templates/topics/index.html
index 9d795ff65..c7e160a0d 100644
--- a/csunplugged/templates/topics/index.html
+++ b/csunplugged/templates/topics/index.html
@@ -23,8 +23,15 @@ <h1>{% trans "Topics" %}</h1>
<div class="link-box-container">
{% for topic in all_topics %}
<a class="link-box link-box-md-3 link-box-lg-4" href="{% url 'topics:topic' topic.slug %}">
- <img class="img-fluid" src="{% if topic.icon %}{% static topic.icon %}{% else %}http://placehold.it/238x200{% endif %}">
+ <img class="img-fluid" src="{% static topic.icon %}">
<h3 class="link-box-title">{{ topic.name }}</h3>
+ {% if topic.unit_plans.count > 1 %}
+ <h5 class="text-muted">
+ {% for unit_plan in topic.unit_plans.all %}
+ {{ unit_plan.name }}{% if not forloop.last %}, {% endif %}
+ {% endfor %}
+ </h5>
+ {% endif %}
</a>
{% endfor %}
</div>
diff --git a/csunplugged/templates/topics/lesson.html b/csunplugged/templates/topics/lesson.html
index 2b4802454..af8add8ae 100644
--- a/csunplugged/templates/topics/lesson.html
+++ b/csunplugged/templates/topics/lesson.html
@@ -34,7 +34,7 @@ <h2 class="heading-underline">Learning outcomes</h2>
<ul>
{% for learning_outcome in learning_outcomes %}
<li>
- {{ learning_outcome.text }}
+ {{ learning_outcome.text }}<br>
{% for area in learning_outcome.curriculum_areas.all %}
{% include "topics/curriculum-area-badge.html" %}
{% endfor %}
diff --git a/csunplugged/templates/topics/lessons-table.html b/csunplugged/templates/topics/lessons-table.html
index c239ab5a9..e6932e6b6 100644
--- a/csunplugged/templates/topics/lessons-table.html
+++ b/csunplugged/templates/topics/lessons-table.html
@@ -18,21 +18,21 @@
{% endif %}
{% for lesson in lessons %}
<tr class="align-middle">
- <td class="text-center">
+ <td class="text-center" style="width:10%">
{{ lesson.number }}
</td>
- <td>
+ <td style="width:60%">
<a href="{% url 'topics:lesson' topic.slug unit_plan.slug lesson.slug %}">
<strong>{{ lesson.name }}</strong>
</a>
</td>
{% if lesson.has_programming_challenges %}
- <td class="text-center table-success-cell">
+ <td class="text-center table-success-cell" style="width:20%">
<a href="{% url 'topics:programming_challenges_list' topic.slug unit_plan.slug lesson.slug %}">
Yes
</a>
{% else %}
- <td class="text-center">
+ <td class="text-center" style="width:20%">
No
{% endif %}
</td>
diff --git a/csunplugged/templates/topics/programming-challenge.html b/csunplugged/templates/topics/programming-challenge.html
index c57141445..986072d85 100644
--- a/csunplugged/templates/topics/programming-challenge.html
+++ b/csunplugged/templates/topics/programming-challenge.html
@@ -49,7 +49,7 @@ <h2>Learning outcomes</h2>
<ul>
{% for learning_outcome in learning_outcomes %}
<li>
- {{ learning_outcome.text }}
+ {{ learning_outcome.text }}<br>
{% for area in learning_outcome.curriculum_areas.all %}
{% include "topics/curriculum-area-badge.html" %}
{% endfor %}
diff --git a/csunplugged/templates/topics/topic.html b/csunplugged/templates/topics/topic.html
index 3ca8456e4..43663deee 100644
--- a/csunplugged/templates/topics/topic.html
+++ b/csunplugged/templates/topics/topic.html
@@ -24,7 +24,7 @@ <h1 id="{{ topic.slug }}" class="heading-underline">{{ topic.name }}</h1>
{% for unit_plan in unit_plans %}
<div class="link-box-container">
<a class="link-box link-box-md-6" href="{% url 'topics:unit_plan' topic.slug unit_plan.slug %}">
- <h3 id="{{ unit_plan.slug }}" class="link-box-title">{{ unit_plan.name }}</h3>
+ <h3 id="{{ unit_plan.slug }}" class="link-box-title"><span class="text-muted">Unit plan:</span> {{ unit_plan.name }}</h3>
</a>
</div>
@@ -38,6 +38,10 @@ <h3 id="{{ unit_plan.slug }}" class="link-box-title">{{ unit_plan.name }}</h3>
{% include "topics/lessons-table.html" %}
{% endwith %}
{% endif %}
+
+ {% if not forloop.last %}
+ <hr>
+ {% endif %}
{% endfor %}
{% if curriculum_integrations %}
@@ -83,12 +87,16 @@ <h2 class="heading-underline">Table of contents</h2>
<a class="nav-link" href="#{{ unit_plan.slug }}">{{ unit_plan.name }}</a>
</li>
{% endfor %}
- <li class="nav-item">
- <a class="nav-link" href="#integrations">Curriculum integrations</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" href="#resources">Resources</a>
- </li>
+ {% if curriculum_integrations %}
+ <li class="nav-item">
+ <a class="nav-link" href="#integrations">Curriculum integrations</a>
+ </li>
+ {% endif %}
+ {% if resources %}
+ <li class="nav-item">
+ <a class="nav-link" href="#resources">Resources</a>
+ </li>
+ {% endif %}
{% if topic.other_resources %}
<li class="nav-item">
<a class="nav-link" href="#other-resources">Other resources</a>
diff --git a/csunplugged/templates/topics/unit-plan.html b/csunplugged/templates/topics/unit-plan.html
index 5169a934c..b8a510909 100644
--- a/csunplugged/templates/topics/unit-plan.html
+++ b/csunplugged/templates/topics/unit-plan.html
@@ -15,7 +15,7 @@
{% endblock breadcrumbs %}
{% block page_heading %}
- <h1 id="{{ unit_plan.slug }}" class="heading-underline">{{ unit_plan.name }}</h1>
+ <h1 id="{{ unit_plan.slug }}" class="heading-underline"><span class="text-muted">Unit plan:</span> {{ unit_plan.name }}</h1>
{% endblock page_heading %}
{% block left_column_content %}
diff --git a/csunplugged/topics/content/en/binary-numbers/unit-plan/unit-plan.md b/csunplugged/topics/content/en/binary-numbers/unit-plan/unit-plan.md
index c5f7a9e78..acc29487d 100644
--- a/csunplugged/topics/content/en/binary-numbers/unit-plan/unit-plan.md
+++ b/csunplugged/topics/content/en/binary-numbers/unit-plan/unit-plan.md
@@ -1,4 +1,4 @@
-# Binary Numbers Unit Plan
+# Binary numbers
## See Teaching the Binary Number System in Action!
diff --git a/csunplugged/topics/content/en/error-detection-and-correction/curriculum-integrations/quick-card-flip-magic.md b/csunplugged/topics/content/en/error-detection-and-correction/curriculum-integrations/quick-card-flip-magic.md
index a2aa7ae7b..6379c04e0 100644
--- a/csunplugged/topics/content/en/error-detection-and-correction/curriculum-integrations/quick-card-flip-magic.md
+++ b/csunplugged/topics/content/en/error-detection-and-correction/curriculum-integrations/quick-card-flip-magic.md
@@ -1,18 +1,18 @@
-# Quick card flip magic
+# Quick card flip magic
-{image file-path="img/topics/kids-parity-trick.png"}
+{image file-path="img/topics/kids-parity-trick.jpg"}
*Every item of data that we store and transmit has extra bits added to it to prevent errors.
Can you find the error and correct it?*
-
-### Equipment:
+
+### Equipment:
At least 36, or even 100 or more cards that are black on one side and white on the other, about 20mm by 20mm (or any two colours that are easily distinguished)
A clear space on the floor or a table that the students can stand around
-
-### Preparation:
-Select a ‘magic master’.
+### Preparation:
+
+Select a ‘magic master’.
This is the person who is in control of the game.
This person will change at the end of each round.
@@ -22,24 +22,24 @@ This person will change at the end of each round.
The grid can be any size; it should be at least 6 by 6, although it can be increased up to 10 by 10 or more to make the challenge harder.
The grid doesn't have to be square (e.g. 9 by 8 is fine), but the effect is greatest when it is close to square.
-2. The magic master asks everyone to close their eyes and turn away, except for the magic master and the assistant.
+2. The magic master asks everyone to close their eyes and turn away, except for the magic master and the assistant.
3. The magic master asks the assistant to choose a card, place a counter or a mark under where the card goes and flip it over.
4. Once this has been done, the magic master calls out (quietly)…” let the magic begin” and presses the timer.
- When the other students hear this they turn around and try to find the ‘error’.
+ When the other students hear this they turn around and try to find the ‘error’.
-5. As soon as they spot the error, they put their finger on their nose.
+5. As soon as they spot the error, they put their finger on their nose.
-6. The magic master stops the timer and asks the first person who put their finger on their nose to show where the flipped card was.
+6. The magic master stops the timer and asks the first person who put their finger on their nose to show where the flipped card was.
-7. The student points to the flipped card, checks if they are correct by flipping the card over.
+7. The student points to the flipped card, checks if they are correct by flipping the card over.
-8. If they are correct, that person explains how they worked out which was the flipped card.
+8. If they are correct, that person explains how they worked out which was the flipped card.
-9. The magic master records the person's name who won that round and the time.
+9. The magic master records the person's name who won that round and the time.
-10. Did they beat the previous time?
+10. Did they beat the previous time?
11. If they did beat the previous time, that person becomes the assistant.
- The person who won that round stays the assistant until their time is beaten.
+ The person who won that round stays the assistant until their time is beaten.
diff --git a/csunplugged/topics/content/en/error-detection-and-correction/unit-plan/unit-plan.md b/csunplugged/topics/content/en/error-detection-and-correction/unit-plan/unit-plan.md
index 59c40f171..714e80654 100644
--- a/csunplugged/topics/content/en/error-detection-and-correction/unit-plan/unit-plan.md
+++ b/csunplugged/topics/content/en/error-detection-and-correction/unit-plan/unit-plan.md
@@ -1,4 +1,4 @@
-# Error detection and correction unit plan
+# Error detection and correction
{panel type="teaching" title="See teaching this in action!"}
diff --git a/csunplugged/topics/content/en/sorting-networks/unit-plan/lessons/investigating-variations-using-the-sorting-network.md b/csunplugged/topics/content/en/sorting-networks/unit-plan/lessons/investigating-variations-using-the-sorting-network.md
index 5e2f3aec3..ceeee6077 100644
--- a/csunplugged/topics/content/en/sorting-networks/unit-plan/lessons/investigating-variations-using-the-sorting-network.md
+++ b/csunplugged/topics/content/en/sorting-networks/unit-plan/lessons/investigating-variations-using-the-sorting-network.md
@@ -67,7 +67,7 @@ By reversing the left/right decision, the final result will be in the reverse or
### Variation 3: Letters of the alphabet
-{image file-path="img/topics/sorting-network-variation-alphabet.png"}
+{image file-path="img/topics/sorting-network-variation-alphabet.jpg"}
Give the students cards with letters on them.
Ask how we could compare these (students should observe that they could be in alphabetical order).
@@ -96,7 +96,7 @@ AFFLUX, AGLOOS, ALMOST, BEGILT, BEGINS, BEGIRT, BEKNOT, BELLOW, BIJOUX, BILLOW,
### Variation 5: Sorting words in dictionary order
-{image file-path="img/topics/sorting-network-variation-words.png"}
+{image file-path="img/topics/sorting-network-variation-words.jpg"}
Give the students cards with dictionary words on them, and ask how these might be compared.
Students should observe that they could be placed in dictionary order.
@@ -106,14 +106,14 @@ A variation is to give them books and have them sort them in order of the author
Comparing two words or names is challenging; they will need to know to compare each character until two differ (e.g. for "crochet" and "crocodile", the "croc" prefix is the same, so it is the "h" and "o" that determine their order; this process is an algorithm in itself!)
-{image file-path="img/topics/sorting-network-variation-words-2.png"}
+{image file-path="img/topics/sorting-network-variation-words-2.jpg"}
The words being compared could also be used to reinforce spelling or meaning; for example, the words above are the colours in Te Reo Māori, so the student with the word "kowhai" would be reinforcing that it means the colour yellow.
The use of macrons and other diacritical marks also gives the opportunity to explore the order that is used in the such languages for those letters.
### Variation 6: Music notation
-{image file-path="img/topics/sorting-network-variation-music.png"}
+{image file-path="img/topics/sorting-network-variation-music.jpg"}
Students can compare the pitch of music notation, with higher notes going to the right.
If all the cards have the same clef (such as the treble clef here) then it reinforces that the height on the stave corresponds to the pitch.
@@ -121,7 +121,7 @@ Advanced music students can do the comparisons with different clefs (bass, alto
### Variation 7: Music pitch - aural
-{image file-path="img/topics/sorting-network-variation-aural.png"}
+{image file-path="img/topics/sorting-network-variation-aural.jpg"}
In this variation, students compare the pitch of simple instruments that they are carrying.
The bells shown above are ideal because they are all the same size, and force students to compare them by listening.
diff --git a/csunplugged/topics/content/en/sorting-networks/unit-plan/unit-plan.md b/csunplugged/topics/content/en/sorting-networks/unit-plan/unit-plan.md
index 92fdf2fe7..c187386ba 100644
--- a/csunplugged/topics/content/en/sorting-networks/unit-plan/unit-plan.md
+++ b/csunplugged/topics/content/en/sorting-networks/unit-plan/unit-plan.md
@@ -1,4 +1,4 @@
-# Sorting networks unit plan
+# Sorting networks
{panel type="teaching" title="See teaching this in action!"}
diff --git a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan-ct-links.md b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan-ct-links.md
new file mode 100644
index 000000000..a09c70c09
--- /dev/null
+++ b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan-ct-links.md
@@ -0,0 +1,52 @@
+{panel type="ct-algorithm" title="Algorithmic thinking"}
+
+Throughout this unit students will be creating algorithms to ‘program’ the bot to move across grids.
+The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
+
+{panel end}
+
+{panel type="ct-abstraction" title="Abstraction"}
+
+The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
+In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
+This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
+
+The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
+
+In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
+
+{panel end}
+
+{panel type="ct-decomposition" title="Decomposition"}
+
+In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
+They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
+
+{panel end}
+
+{panel type="ct-pattern" title="Generalising and patterns"}
+
+As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
+Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
+
+{panel end}
+
+{panel type="ct-evaluation" title="Evaluation"}
+
+Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
+
+There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
+Students can compare these and explain why they think certain programs are better than others.
+
+There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
+
+{panel end}
+
+{panel type="ct-logic" title="Logic"}
+
+Students will be continuously exercising their logical thinking skills throughout this unit.
+As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
+They will also need a logical approach to debugging their programs when they do not work correctly.
+They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+
+{panel end}
diff --git a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.md b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.md
index 65b90dac3..9d59b95cf 100644
--- a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.md
+++ b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.md
@@ -10,7 +10,7 @@ A version of this can curently be seen at 1:09:56 [here](https://educationonair.
Writing a computer program involves planning what you're going to do, "coding" the instructions, testing them, tracking down any bugs, and changing the program to that it works correctly.
In these activities students explore a simple programming language by taking on separate roles to make these elements of programming explicit.
-
+
This isn't completely artificial; most substantial program is written by a team of people, and often the roles of design, coding and testing are separated out. The program is made because there is a problem to solve to help other people to improve their lives.
The people who write the program using a programming language are called the **programmer** (or possibly a **developer** or **software engineer**) - they write the instructions to tell the computer what to do.
To be sure that the code is working exactly as it needs to for the people it’s been written for, someone needs to test the program and feeds back to the programmer(s) what needs fixing and why.
@@ -22,8 +22,8 @@ The Geometry programming activities separate the programming from the testing to
## Digital Technologies | Programming
Programming or "coding" is when a person (**a programmer**) types in instructions in a programming language so that the computer knows what it needs to do (programmers do lots of other things as well).
-Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
-
+Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
+
Being a programmer isn't so much about knowing the particular commands in a programming language, but knowing how to put together the building blocks such as loops, if statements, variables, input and output in a way that the computer will do what is intended.
This involves working out the general process for achieving the goal, representing that process in the particular language, and making sure that it does what is intended.
@@ -32,7 +32,7 @@ This involves working out the general process for achieving the goal, representi
{panel type="math" title="Mathematical links"}
There are strong connections between mathematics and programming.
-Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
+Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
{panel end}
@@ -42,71 +42,15 @@ Good programmers need to have a good base of mathematical knowledge, since a pro
Giving sequential instructions are an important element of all programming languages, and so the Geometry programming activities lay the foundation for understanding more conventional languages.
It also exercises the ability to predict what a program will do, reason about where any bugs are, and understand that there can be multiple correct ways to program a solution.
-
-Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-
-## Seeing the Computational Thinking connections
-
-
-{panel type="ct-algorithm" title="Algorithmic thinking"}
-
-Throughout this unit students will be creating algorithms to ‘program’ the bot to move across grids.
-The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
-
-{panel end}
-{panel type="ct-abstraction" title="Abstraction"}
+Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
-In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
-This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
-
-The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
-
-In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
-
-{panel end}
-
-{panel type="ct-decomposition" title="Decomposition"}
-
-In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
-They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
-
-{panel end}
-
-{panel type="ct-pattern" title="Generalising and patterns"}
-
-As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
-Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
-
-{panel end}
-
-{panel type="ct-evaluation" title="Evaluation"}
-
-Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
-
-There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
-Students can compare these and explain why they think certain programs are better than others.
-
-There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
-
-{panel end}
-
-{panel type="ct-logic" title="Logic"}
-
-Students will be continuously exercising their logical thinking skills throughout this unit.
-As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
-They will also need a logical approach to debugging their programs when they do not work correctly.
-They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+## Reflection questions
-{panel end}
+- What was most surprising about the learning that happened from the teaching of this unit?
-## Reflection questions
+- Who were the students who were very systematic in their activities?
-- What was most surprising about the learning that happened from the teaching of this unit?
+- Who were the students who were very detailed in their activities?
-- Who were the students who were very systematic in their activities?
-
-- Who were the students who were very detailed in their activities?
-
-- What would I change in my delivery of this unit?
+- What would I change in my delivery of this unit?
diff --git a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.yaml b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.yaml
index b14e01e4f..1102a9694 100644
--- a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.yaml
+++ b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/geometry-unit-plan.yaml
@@ -1,4 +1,5 @@
lessons: lessons/lessons.yaml
+computational-thinking-links: geometry-unit-plan-ct-links.md
age-groups:
5-7:
diff --git a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/lessons/lessons.yaml b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/lessons/lessons.yaml
index 57f307a96..d55dcfdf8 100644
--- a/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/lessons/lessons.yaml
+++ b/csunplugged/topics/content/en/unplugged-programming/geometry-unit-plan/lessons/lessons.yaml
@@ -25,6 +25,7 @@ finding-2d-shapes:
moving-in-a-shape:
duration: 30
+ computational-thinking-links: moving-in-a-shape-ct-links.md
learning-outcomes:
- unplugged-programming-give-instructions-shape
- unplugged-programming-identify-bug-shape
diff --git a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan-ct-links.md b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan-ct-links.md
new file mode 100644
index 000000000..a09c70c09
--- /dev/null
+++ b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan-ct-links.md
@@ -0,0 +1,52 @@
+{panel type="ct-algorithm" title="Algorithmic thinking"}
+
+Throughout this unit students will be creating algorithms to ‘program’ the bot to move across grids.
+The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
+
+{panel end}
+
+{panel type="ct-abstraction" title="Abstraction"}
+
+The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
+In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
+This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
+
+The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
+
+In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
+
+{panel end}
+
+{panel type="ct-decomposition" title="Decomposition"}
+
+In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
+They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
+
+{panel end}
+
+{panel type="ct-pattern" title="Generalising and patterns"}
+
+As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
+Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
+
+{panel end}
+
+{panel type="ct-evaluation" title="Evaluation"}
+
+Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
+
+There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
+Students can compare these and explain why they think certain programs are better than others.
+
+There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
+
+{panel end}
+
+{panel type="ct-logic" title="Logic"}
+
+Students will be continuously exercising their logical thinking skills throughout this unit.
+As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
+They will also need a logical approach to debugging their programs when they do not work correctly.
+They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+
+{panel end}
diff --git a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.md b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.md
index 9d0858237..5cc53955e 100644
--- a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.md
+++ b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.md
@@ -10,7 +10,7 @@ A version of this can curently be seen at 1:09:56 [here](https://educationonair.
Writing a computer program involves planning what you're going to do, "coding" the instructions, testing them, tracking down any bugs, and changing the program to that it works correctly.
In these activities students explore a simple programming language by taking on separate roles to make these elements of programming explicit.
-
+
This isn't completely artificial; most substantial program is written by a team of people, and often the roles of design, coding and testing are separated out. The program is made because there is a problem to solve to help other people to improve their lives.
The people who write the program using a programming language are called the **programmer** (or possibly a **developer** or **software engineer**) - they write the instructions to tell the computer what to do.
To be sure that the code is working exactly as it needs to for the people it’s been written for, someone needs to test the program and feeds back to the programmer(s) what needs fixing and why.
@@ -22,8 +22,8 @@ The Kidbots activities separates the programming from the testing to avoid the p
## Digital Technologies | Programming
Programming or "coding" is when a person (**a programmer**) types in instructions in a programming language so that the computer knows what it needs to do (programmers do lots of other things as well).
-Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
-
+Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
+
Being a programmer isn't so much about knowing the particular commands in a programming language, but knowing how to put together the building blocks such as loops, if statements, variables, input and output in a way that the computer will do what is intended.
This involves working out the general process for achieving the goal, representing that process in the particular language, and making sure that it does what is intended.
@@ -32,7 +32,7 @@ This involves working out the general process for achieving the goal, representi
{panel type="math" title="Mathematical links"}
There are strong connections between mathematics and programming.
-Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
+Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
{panel end}
@@ -42,71 +42,15 @@ Good programmers need to have a good base of mathematical knowledge, since a pro
Giving sequential instructions are an important element of all programming languages, and so the Kidbots activity lays the foundation for understanding more conventional languages.
It also exercises the ability to predict what a program will do, reason about where any bugs are, and understand that there can be multiple correct ways to program a solution.
-
-Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-
-## Seeing the Computational Thinking connections
-
-
-{panel type="ct-algorithm" title="Algorithmic thinking"}
-
-Throughout this unit students will be creating algorithms to ‘program’ the bot to move across grids.
-The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
-
-{panel end}
-{panel type="ct-abstraction" title="Abstraction"}
+Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
-In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
-This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
-
-The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
-
-In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
-
-{panel end}
-
-{panel type="ct-decomposition" title="Decomposition"}
-
-In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
-They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
-
-{panel end}
-
-{panel type="ct-pattern" title="Generalising and patterns"}
-
-As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
-Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
-
-{panel end}
-
-{panel type="ct-evaluation" title="Evaluation"}
-
-Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
-
-There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
-Students can compare these and explain why they think certain programs are better than others.
-
-There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
-
-{panel end}
-
-{panel type="ct-logic" title="Logic"}
-
-Students will be continuously exercising their logical thinking skills throughout this unit.
-As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
-They will also need a logical approach to debugging their programs when they do not work correctly.
-They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+## Reflection questions
-{panel end}
+- What was most surprising about the learning that happened from the teaching of this unit?
-## Reflection questions
+- Who were the students who were very systematic in their activities?
-- What was most surprising about the learning that happened from the teaching of this unit?
+- Who were the students who were very detailed in their activities?
-- Who were the students who were very systematic in their activities?
-
-- Who were the students who were very detailed in their activities?
-
-- What would I change in my delivery of this unit?
+- What would I change in my delivery of this unit?
diff --git a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.yaml b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.yaml
index 3351027a2..0b3512e35 100644
--- a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.yaml
+++ b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/kidbots-unit-plan.yaml
@@ -1,4 +1,5 @@
lessons: lessons/lessons.yaml
+computational-thinking-links: kidbots-unit-plan-ct-links.md
age-groups:
5-7:
diff --git a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/lessons/fitness-unplugged-ct-links.md b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/lessons/fitness-unplugged-ct-links.md
index 28e86356a..1cc07f816 100644
--- a/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/lessons/fitness-unplugged-ct-links.md
+++ b/csunplugged/topics/content/en/unplugged-programming/kidbots-unit-plan/lessons/fitness-unplugged-ct-links.md
@@ -15,7 +15,6 @@ Were they able to interpret the loop correctly?
{panel type="ct-abstraction" title="Abstraction"}
The symbols on the cards represented the physical actions students needed to perform; they were an abstract representation.
-Abstraction was also used to simplify things when the hula hoop was used as a
#### Examples of what you could look for:
@@ -25,7 +24,7 @@ Were the students able to work with the symbols?
{panel type="ct-decomposition" title="Decomposition"}
-The hula hoop represents a compound action, as the cards inside it were a sub-list of actions that could be thought of as a single action that is composed of the sub-actions.
+The hula hoop represents a compound action, as the cards inside it were a sub-list of actions that could be thought of as a single action that is composed of the sub-actions.
#### Examples of what you could look for:
@@ -62,7 +61,7 @@ When students encounter bugs in their programs they will need to logically step
They will need to think about what they expect to happen when each instruction is followed, and if they do not get the result they expected they will need to identify what went wrong, why it went wrong, and how to fix it.
This requires students to apply their logical thinking skills
-#### Examples of what you could look for:
+#### Examples of what you could look for:
Do students go through their instructions and predict what will happen each time one is executed?
When they debug their instructions do they use a logical method to do this?
diff --git a/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan-ct-links.md b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan-ct-links.md
new file mode 100644
index 000000000..d41a339b1
--- /dev/null
+++ b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan-ct-links.md
@@ -0,0 +1,52 @@
+{panel type="ct-algorithm" title="Algorithmic thinking"}
+
+Throughout this unit students will be creating algorithms to ‘program’ the Bot to move across grids.
+The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
+
+{panel end}
+
+{panel type="ct-abstraction" title="Abstraction"}
+
+The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
+In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
+This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
+
+The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
+
+In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
+
+{panel end}
+
+{panel type="ct-decomposition" title="Decomposition"}
+
+In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
+They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
+
+{panel end}
+
+{panel type="ct-pattern" title="Generalising and patterns"}
+
+As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
+Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
+
+{panel end}
+
+{panel type="ct-evaluation" title="Evaluation"}
+
+Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
+
+There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
+Students can compare these and explain why they think certain programs are better than others.
+
+There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
+
+{panel end}
+
+{panel type="ct-logic" title="Logic"}
+
+Students will be continuously exercising their logical thinking skills throughout this unit.
+As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
+They will also need a logical approach to debugging their programs when they do not work correctly.
+They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+
+{panel end}
diff --git a/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.md b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.md
index ec8dbb6d6..620aeb87d 100644
--- a/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.md
+++ b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.md
@@ -6,7 +6,7 @@
Writing a computer program involves planning what you're going to do, "coding" the instructions, testing them, tracking down any bugs, and changing the program to that it works correctly.
In these activities students explore a simple programming language by taking on separate roles to make these elements of programming explicit.
-
+
This isn't completely artificial; most substantial program is written by a team of people, and often the roles of design, coding and testing are separated out. The program is made because there is a problem to solve to help other people to improve their lives.
The people who write the program using a programming language are called the **programmer** (or possibly a **developer** or **software engineer**) - they write the instructions to tell the computer what to do.
To be sure that the code is working exactly as it needs to for the people it’s been written for, someone needs to test the program and feeds back to the programmer(s) what needs fixing and why.
@@ -18,8 +18,8 @@ The Numeracy programming activities separates the programming from the testing t
## Digital Technologies | Programming
Programming or "coding" is when a person (**a programmer**) types in instructions in a programming language so that the computer knows what it needs to do (programmers do lots of other things as well).
-Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
-
+Common programming languages that are used in the junior classroom include Scratch, ScratchJr, Python, Snap!, Blockly, and some older languages like Basic and Logo (which are still popular today).
+
Being a programmer isn't so much about knowing the particular commands in a programming language, but knowing how to put together the building blocks such as loops, if statements, variables, input and output in a way that the computer will do what is intended.
This involves working out the general process for achieving the goal, representing that process in the particular language, and making sure that it does what is intended.
@@ -28,7 +28,7 @@ This involves working out the general process for achieving the goal, representi
{panel type="math" title="Mathematical links"}
There are strong connections between mathematics and programming.
-Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
+Good programmers need to have a good base of mathematical knowledge, since a program is effectively a mathematical formula, and getting the structure of a program right requires good reasoning.
{panel end}
@@ -38,71 +38,15 @@ Good programmers need to have a good base of mathematical knowledge, since a pro
Giving sequential instructions are an important element of all programming languages, and so the numeracy programming activities lay the foundation for understanding more conventional languages.
It also exercises the ability to predict what a program will do, reason about where any bugs are, and understand that there can be multiple correct ways to program a solution.
-
-Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-
-## Seeing the Computational Thinking connections
-
-
-{panel type="ct-algorithm" title="Algorithmic thinking"}
-
-Throughout this unit students will be creating algorithms to ‘program’ the Bot to move across grids.
-The algorithmic thinking focuses on students learning to sequence a set of instructions to complete a task, to use specific types of instructions in their algorithms, and to find equivalent ways to achieve the same outcome.
-
-{panel end}
-{panel type="ct-abstraction" title="Abstraction"}
+Being able to give exact sequential instructions, work well together and understand how to break a big problem into small pieces and then tackling the small piece one at a time are all life skills that can be transferred from computer programming to other tasks that students need to do.
-The ‘programming’ students will be doing in these activities is an abstract version of the type of programming we do on computers using conventional programming languages.
-In this unit students will use a small set of very basic instructions as their programming language, write their programs in simple words, and give their instructions verbally to the bot.
-This allows students to learn about sequencing in programming and practice creating algorithms without needing to learn a programming language first or use technical terminology and tools.
-
-The choice of commands for the programming language also demonstrate the use of abstraction (such as using "L" or an arrow to represent the command "Left").
-
-In lesson 3 students will also be using another level of abstraction, as some instructions will be encapsulated inside a loop.
-
-{panel end}
-
-{panel type="ct-decomposition" title="Decomposition"}
-
-In every activity in this unit students will be practicing decomposition, as they break down the movements they want the bot to make into basic and specific instructions.
-They will also be encouraged to write their programs incrementally, to write the first few steps, test them, and then add the next steps to the program, instead of trying to solve the whole problem at once.
-
-{panel end}
-
-{panel type="ct-pattern" title="Generalising and patterns"}
-
-As students write their algorithms and programs in this unit there are many different patterns that emerge in how the instructions are sequenced.
-Groups of instructions might tell the Bot to move a specific way, such as walk in a square, and if students identify these patterns they can reuse these groups of instructions if they need to have the Bot make the same movements again.
-
-{panel end}
-
-{panel type="ct-evaluation" title="Evaluation"}
-
-Each time students write their programs and test them they will be evaluating them, because the most important thing they need to determine is “did the program work?”. Each time they test their programs they can identify whether it accomplished the task or not.
-
-There will almost always be multiple programs students could use to accomplish each task, but some will be more efficient than others as they will use fewer steps.
-Students can compare these and explain why they think certain programs are better than others.
-
-There is also the opportunity to compare programming languages. We explore reducing the number of instructions available; in some cases the same goals can be achieved (the language has the same computing ability), but the programs might be longer.
-
-{panel end}
-
-{panel type="ct-logic" title="Logic"}
-
-Students will be continuously exercising their logical thinking skills throughout this unit.
-As they are planning their algorithms they will need to step through what they think will happen with each instruction, e.g. “at this point they’ll be facing that way so if I then say move forward twice then they’ll end up on that square”.
-They will also need a logical approach to debugging their programs when they do not work correctly.
-They will need to step through each instruction and identify when something goes wrong and how they can fix the bug so the program then behaves as expected.
+## Reflection questions
-{panel end}
+- What was most surprising about the learning that happened from the teaching of this unit?
-## Reflection questions
+- Who were the students who were very systematic in their activities?
-- What was most surprising about the learning that happened from the teaching of this unit?
+- Who were the students who were very detailed in their activities?
-- Who were the students who were very systematic in their activities?
-
-- Who were the students who were very detailed in their activities?
-
-- What would I change in my delivery of this unit?
+- What would I change in my delivery of this unit?
diff --git a/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.yaml b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.yaml
index dcc863030..e88c11bc8 100644
--- a/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.yaml
+++ b/csunplugged/topics/content/en/unplugged-programming/numeracy-unit-plan/numeracy-unit-plan.yaml
@@ -1,4 +1,5 @@
lessons: lessons/lessons.yaml
+computational-thinking-links: numeracy-unit-plan-ct-links.md
age-groups:
8-10:
diff --git a/csunplugged/topics/views.py b/csunplugged/topics/views.py
index 1272507ea..3a94d82f8 100644
--- a/csunplugged/topics/views.py
+++ b/csunplugged/topics/views.py
@@ -31,7 +31,7 @@ def get_queryset(self):
Returns:
Queryset of Topic objects ordered by name.
"""
- return Topic.objects.order_by("name")
+ return Topic.objects.order_by("name").prefetch_related("unit_plans")
class TopicView(generic.DetailView):
|
django-json-api__django-rest-framework-json-api-715 | Use extra requires to seperate optional features django-filter and polymorphic
The optional features (Polymorphic and Django filter) should define their dependencies as extra.
Currently this is only done as test requires but actual users won't have enforced minimum requirements.
Once this is done a user can simply add following into their requirements to properly activate an optional feature:
```
djangorestframework-jsonapi[django-filter] == 2.8.0
```
see
https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies
| [
{
"content": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\n\nfrom setuptools import setup\n\n\ndef read(*paths):\n \"\"\"\n Build a file path from paths and return the contents.\n \"\"\"\n with open(os.path.join(*paths), 'r') as f:\n return... | [
{
"content": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\n\nfrom setuptools import setup\n\n\ndef read(*paths):\n \"\"\"\n Build a file path from paths and return the contents.\n \"\"\"\n with open(os.path.join(*paths), 'r') as f:\n return... | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ac200cd..3e967fc7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,15 @@ This release is not backwards compatible. For easy migration best upgrade first
* Add support for Django REST framework 3.10.
* Add code from ErrorDetail into the JSON:API error object
+### Changed
+
+* Moved dependency definition for `django-polymorphic` and `django-filter` into extra requires.
+ Hence dependencies of each optional module can be installed with pip using
+ ```
+ pip install djangorestframework-jsonapi['django-polymorphic']
+ pip install djangorestframework-jsonapi['django-filter']`
+ ```
+
### Removed
* Removed support for Python 2.7 and 3.4.
diff --git a/README.rst b/README.rst
index 4f3d8aaa..2a53723c 100644
--- a/README.rst
+++ b/README.rst
@@ -101,6 +101,9 @@ From PyPI
::
$ pip install djangorestframework-jsonapi
+ $ # for optional package integrations
+ $ pip install djangorestframework-jsonapi['django-filter']
+ $ pip install djangorestframework-jsonapi['django-polymorphic']
From Source
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 93096d79..d89eb248 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -60,6 +60,9 @@ like the following:
From PyPI
pip install djangorestframework-jsonapi
+ # for optional package integrations
+ pip install djangorestframework-jsonapi['django-filter']
+ pip install djangorestframework-jsonapi['django-polymorphic']
From Source
diff --git a/docs/usage.md b/docs/usage.md
index a655687a..fc8e2895 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -4,7 +4,7 @@
The DJA package implements a custom renderer, parser, exception handler, query filter backends, and
pagination. To get started enable the pieces in `settings.py` that you want to use.
-Many features of the [JSON:API](http://jsonapi.org/format) format standard have been implemented using
+Many features of the [JSON:API](http://jsonapi.org/format) format standard have been implemented using
Mixin classes in `serializers.py`.
The easiest way to make use of those features is to import ModelSerializer variants
from `rest_framework_json_api` instead of the usual `rest_framework`
@@ -108,7 +108,8 @@ class MyLimitPagination(JsonApiLimitOffsetPagination):
Following are descriptions of JSON:API-specific filter backends and documentation on suggested usage
for a standard DRF keyword-search filter backend that makes it consistent with JSON:API.
-#### `QueryParameterValidationFilter`
+#### QueryParameterValidationFilter
+
`QueryParameterValidationFilter` validates query parameters to be one of the defined JSON:API query parameters
(sort, include, filter, fields, page) and returns a `400 Bad Request` if a non-matching query parameter
is used. This can help the client identify misspelled query parameters, for example.
@@ -131,7 +132,8 @@ class MyQPValidator(QueryValidationFilter):
If you don't care if non-JSON:API query parameters are allowed (and potentially silently ignored),
simply don't use this filter backend.
-#### `OrderingFilter`
+#### OrderingFilter
+
`OrderingFilter` implements the [JSON:API `sort`](http://jsonapi.org/format/#fetching-sorting) and uses
DRF's [ordering filter](http://django-rest-framework.readthedocs.io/en/latest/api-guide/filtering/#orderingfilter).
@@ -155,7 +157,8 @@ field name and the other two are not valid:
If you want to silently ignore bad sort fields, just use `rest_framework.filters.OrderingFilter` and set
`ordering_param` to `sort`.
-#### `DjangoFilterBackend`
+#### DjangoFilterBackend
+
`DjangoFilterBackend` implements a Django ORM-style [JSON:API `filter`](http://jsonapi.org/format/#fetching-filtering)
using the [django-filter](https://django-filter.readthedocs.io/) package.
@@ -178,13 +181,6 @@ Filters can be:
- A related resource path can be used:
`?filter[inventory.item.partNum]=123456` (where `inventory.item` is the relationship path)
-If you are also using [`SearchFilter`](#searchfilter)
-(which performs single parameter searches across multiple fields) you'll want to customize the name of the query
-parameter for searching to make sure it doesn't conflict with a field name defined in the filterset.
-The recommended value is: `search_param="filter[search]"` but just make sure it's
-`filter[_something_]` to comply with the JSON:API spec requirement to use the filter
-keyword. The default is `REST_FRAMEWORK['SEARCH_PARAM']` unless overriden.
-
The filter returns a `400 Bad Request` error for invalid filter query parameters as in this example
for `GET http://127.0.0.1:8000/nopage-entries?filter[bad]=1`:
```json
@@ -201,7 +197,11 @@ for `GET http://127.0.0.1:8000/nopage-entries?filter[bad]=1`:
}
```
-#### `SearchFilter`
+As this feature depends on `django-filter` you need to run
+
+ pip install djangorestframework-jsonapi['django-filter']
+
+#### SearchFilter
To comply with JSON:API query parameter naming standards, DRF's
[SearchFilter](https://django-rest-framework.readthedocs.io/en/latest/api-guide/filtering/#searchfilter) should
@@ -211,12 +211,11 @@ adding the `.search_param` attribute to a custom class derived from `SearchFilte
use [`DjangoFilterBackend`](#djangofilterbackend), make sure you set the same values for both classes.
-
#### Configuring Filter Backends
You can configure the filter backends either by setting the `REST_FRAMEWORK['DEFAULT_FILTER_BACKENDS']` as shown
in the [example settings](#configuration) or individually add them as `.filter_backends` View attributes:
-
+
```python
from rest_framework_json_api import filters
from rest_framework_json_api import django_filters
@@ -699,6 +698,10 @@ DJA tests its polymorphic support against [django-polymorphic](https://django-po
The polymorphic feature should also work with other popular libraries like
django-polymodels or django-typed-models.
+As this feature depends on `django-polymorphic` you need to run
+
+ pip install djangorestframework-jsonapi['django-polymorphic']
+
#### Writing polymorphic resources
A polymorphic endpoint can be set up if associated with a polymorphic serializer.
diff --git a/setup.py b/setup.py
index d9c1c926..7181beb0 100755
--- a/setup.py
+++ b/setup.py
@@ -90,6 +90,10 @@ def get_package_data(package):
'djangorestframework>=3.10',
'django>=1.11',
],
+ extras_require={
+ 'django-polymorphic': ['django-polymorphic>=2.0'],
+ 'django-filter': ['django-filter>=2.0']
+ },
python_requires=">=3.5",
zip_safe=False,
)
|
pydantic__pydantic-3197 | <Model>.schema() method handles Enum and IntEnum default field resolution differently
### Checks
* [x] I added a descriptive title to this issue
* [x] I have searched (google, github) for similar issues and couldn't find anything
* [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug
<!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) -->
# Bug
Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
pydantic version: 1.8.2
pydantic compiled: True
install path: C:\Users\jmartins\.virtualenvs\pydantic_bug_report-NJE4-7fw\Lib\site-packages\pydantic
python version: 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)]
platform: Windows-10-10.0.19042-SP0
optional deps. installed: ['typing-extensions']
```
<!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version -->
<!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to
confirm your bug hasn't already been reported. -->
<!-- Where possible please include a self-contained code snippet describing your bug: -->
Generating a schema with the .schema() method works as expected when resolving default values of Enum type, while it does not resolve default values of IntEnum type the same way. A minimum example follows:
```py
# std lib imports
from enum import Enum, IntEnum
# external imports
from pydantic import BaseModel
class ExampleEnum(Enum):
A = "a"
class ExampleIntEnum(IntEnum):
A = 1
class ExampleModel(BaseModel):
example_enum: ExampleEnum = ExampleEnum.A
example_int_enum: ExampleIntEnum = ExampleIntEnum.A
generated_schema_properties = ExampleModel.schema().get("properties", {})
example_enum_generated_default = generated_schema_properties.get("example_enum", {}).get("default", None)
example_int_enum_generated_default = generated_schema_properties.get("example_int_enum", {}).get("default", None)
print(example_enum_generated_default is ExampleEnum.A.value)
# -> True
print(example_int_enum_generated_default is ExampleIntEnum.A.value)
# -> False
```
I've tracked the issue down to the `encode_default` function in `schema.py`:
```py
def encode_default(dft: Any) -> Any:
if isinstance(dft, (int, float, str)):
return dft
elif sequence_like(dft):
t = dft.__class__
return t(encode_default(v) for v in dft)
elif isinstance(dft, dict):
return {encode_default(k): encode_default(v) for k, v in dft.items()}
elif dft is None:
return None
else:
return pydantic_encoder(dft)
```
When resolving defaults for Enum the else clause is correctly used, but since `isinstance(ExampleIntEnum.A, int)` is truthy it returns ExampleIntEnum.A when using an IntEnum. I would suggest changing the first if to a stricter direct 'primitive' type check like `if type(dft) in (int, float, str):`.
I can do this myself and open a PR if there is interest and no opposition to a stricter type check.
| [
{
"content": "import re\nimport warnings\nfrom collections import defaultdict\nfrom datetime import date, datetime, time, timedelta\nfrom decimal import Decimal\nfrom enum import Enum\nfrom ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network\nfrom pathlib import Pat... | [
{
"content": "import re\nimport warnings\nfrom collections import defaultdict\nfrom datetime import date, datetime, time, timedelta\nfrom decimal import Decimal\nfrom enum import Enum\nfrom ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network\nfrom pathlib import Pat... | diff --git a/changes/3190-joaommartins.md b/changes/3190-joaommartins.md
new file mode 100644
index 00000000000..74af4f13a4e
--- /dev/null
+++ b/changes/3190-joaommartins.md
@@ -0,0 +1 @@
+Always use `Enum` value as default in generated JSON schema.
\ No newline at end of file
diff --git a/pydantic/schema.py b/pydantic/schema.py
index 581b248d370..7f44be924a1 100644
--- a/pydantic/schema.py
+++ b/pydantic/schema.py
@@ -909,7 +909,9 @@ def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelFie
def encode_default(dft: Any) -> Any:
- if isinstance(dft, (int, float, str)):
+ if isinstance(dft, Enum):
+ return dft.value
+ elif isinstance(dft, (int, float, str)):
return dft
elif sequence_like(dft):
t = dft.__class__
diff --git a/tests/test_schema.py b/tests/test_schema.py
index cd4e2e4f8d7..7bdfcfebb60 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -1404,6 +1404,26 @@ class UserModel(BaseModel):
}
+def test_enum_str_default():
+ class MyEnum(str, Enum):
+ FOO = 'foo'
+
+ class UserModel(BaseModel):
+ friends: MyEnum = MyEnum.FOO
+
+ assert UserModel.schema()['properties']['friends']['default'] is MyEnum.FOO.value
+
+
+def test_enum_int_default():
+ class MyEnum(IntEnum):
+ FOO = 1
+
+ class UserModel(BaseModel):
+ friends: MyEnum = MyEnum.FOO
+
+ assert UserModel.schema()['properties']['friends']['default'] is MyEnum.FOO.value
+
+
def test_dict_default():
class UserModel(BaseModel):
friends: Dict[str, float] = {'a': 1.1, 'b': 2.2}
|
instadeepai__Mava-626 | [TEST] Jax Datasets
### What do you want to test?
Jax dataset components
### Outline of test structure
* Unit tests
* Test components and hooks
### Definition of done
Passing checks, cover all hooks, edge cases considered
### Mandatory checklist before making a PR
* [ ] The success criteria laid down in “Definition of done” are met.
* [ ] Test code is documented - docstrings for methods and classes, static types for arguments.
* [ ] Documentation is updated - README, CONTRIBUTING, or other documentation.
| [
{
"content": "# python3\n# Copyright 2021 InstaDeep Ltd. 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.... | [
{
"content": "# python3\n# Copyright 2021 InstaDeep Ltd. 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.... | diff --git a/mava/components/jax/building/datasets.py b/mava/components/jax/building/datasets.py
index e60804f18..f5d038a84 100644
--- a/mava/components/jax/building/datasets.py
+++ b/mava/components/jax/building/datasets.py
@@ -98,7 +98,7 @@ def on_building_trainer_dataset(self, builder: SystemBuilder) -> None:
postprocess=self.config.postprocess,
)
- builder.store.dataset = iter(dataset)
+ builder.store.dataset_iterator = iter(dataset)
@staticmethod
def config_class() -> Optional[Callable]:
diff --git a/tests/jax/components/building/datasets_test.py b/tests/jax/components/building/datasets_test.py
new file mode 100644
index 000000000..aef6f4206
--- /dev/null
+++ b/tests/jax/components/building/datasets_test.py
@@ -0,0 +1,263 @@
+# python3
+# Copyright 2021 InstaDeep Ltd. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests for TransitionDataset and TrajectoryDataset classes for Jax-based Mava"""
+
+from types import SimpleNamespace
+from typing import Any, Callable, Dict
+
+import pytest
+import reverb
+from tensorflow.python.framework import dtypes, ops
+
+from mava import specs
+from mava.adders import reverb as reverb_adders
+from mava.components.jax.building.datasets import (
+ TrajectoryDataset,
+ TrajectoryDatasetConfig,
+ TransitionDataset,
+ TransitionDatasetConfig,
+)
+from mava.systems.jax.builder import Builder
+from tests.jax.mocks import make_fake_env_specs
+
+env_spec = make_fake_env_specs()
+Transform = Callable[[reverb.ReplaySample], reverb.ReplaySample]
+
+
+def adder_signature_fn(
+ ma_environment_spec: specs.MAEnvironmentSpec,
+ extras_specs: Dict[str, Any],
+) -> Any:
+ """Signature function that helps in building a simple server"""
+ return reverb_adders.ParallelNStepTransitionAdder.signature(
+ ma_environment_spec=ma_environment_spec, extras_specs=extras_specs
+ )
+
+
+class MockBuilder(Builder):
+ def __init__(self) -> None:
+ """Creates a mock builder for testing"""
+ self.simple_server = reverb.Server(
+ [
+ reverb.Table.queue(
+ name="table_0",
+ max_size=100,
+ signature=adder_signature_fn(env_spec, {}),
+ )
+ ]
+ )
+ data_server_client = SimpleNamespace(
+ server_address=f"localhost:{self.simple_server.port}"
+ )
+ trainer_id = "table_0"
+ self.store = SimpleNamespace(
+ data_server_client=data_server_client, trainer_id=trainer_id
+ )
+
+
+@pytest.fixture
+def mock_builder() -> MockBuilder:
+ """Create builder mock"""
+ return MockBuilder()
+
+
+@pytest.fixture
+def transition_dataset() -> TransitionDataset:
+ config = TransitionDatasetConfig()
+ config.sample_batch_size = 512
+ config.prefetch_size = None
+ config.num_parallel_calls = 24
+ config.max_in_flight_samples_per_worker = None
+ config.postprocess = None
+
+ transition_dataset = TransitionDataset(config=config)
+ return transition_dataset
+
+
+@pytest.fixture
+def trajectory_dataset() -> TrajectoryDataset:
+ config = TrajectoryDatasetConfig()
+ config.sample_batch_size = 512
+ config.max_in_flight_samples_per_worker = 1024
+ config.num_workers_per_iterator = -2
+ config.max_samples_per_stream = -2
+ config.rate_limiter_timeout_ms = -2
+ config.get_signature_timeout_secs = None
+
+ trajectory_dataset = TrajectoryDataset(config=config)
+ return trajectory_dataset
+
+
+def test_init_transition_dataset(transition_dataset: TransitionDataset) -> None:
+ """Test initiator of TransitionDataset component"""
+ assert transition_dataset.config.sample_batch_size == 512
+ assert transition_dataset.config.prefetch_size is None
+ assert transition_dataset.config.num_parallel_calls == 24
+ assert transition_dataset.config.max_in_flight_samples_per_worker is None
+ assert transition_dataset.config.postprocess is None
+
+
+def test_on_building_trainer_dataset_transition_dataset_non_max_in_flight(
+ mock_builder: MockBuilder,
+) -> None:
+ """Test on_building_trainer_dataset of TransitionDataset Component
+ Case max_in_flight_samples_per_worker is None and sample_batch_size not None
+ Args:
+ mock_builder: Builder
+ """
+ transition_dataset = TransitionDataset()
+ transition_dataset.on_building_trainer_dataset(builder=mock_builder)
+
+ # mock_builder.store.dataset_iterator._dataset._map_func._func(1)._dataset \
+ # is needed to check the parameters i.e. obtain the dataset from the \
+ # tf.data.Dataset dataset iterator
+
+ dataset = mock_builder.store.dataset_iterator._dataset._map_func._func(1)._dataset
+ assert (
+ dataset._input_dataset._server_address
+ == mock_builder.store.data_server_client.server_address
+ )
+ assert dataset._input_dataset._table == mock_builder.store.trainer_id
+ assert dataset._batch_size == transition_dataset.config.sample_batch_size
+ assert (
+ dataset._input_dataset._max_in_flight_samples_per_worker
+ == 2 * transition_dataset.config.sample_batch_size
+ )
+ assert (
+ mock_builder.store.dataset_iterator._dataset._num_parallel_calls
+ == ops.convert_to_tensor(
+ transition_dataset.config.num_parallel_calls,
+ dtype=dtypes.int64,
+ name="num_parallel_calls",
+ )
+ )
+
+
+def test_on_building_trainer_dataset_transition_dataset_non_max_in_flight_non_batch(
+ mock_builder: MockBuilder,
+) -> None:
+ """Test on_building_trainer_dataset of TransitionDataset Component
+ Case max_in_flight_samples_per_worker is None and sample_batch_size is None
+ Args:
+ mock_builder: Builder
+ """
+ transition_dataset = TransitionDataset()
+ transition_dataset.config.sample_batch_size = None
+ transition_dataset.on_building_trainer_dataset(builder=mock_builder)
+
+ dataset = mock_builder.store.dataset_iterator._dataset._map_func._func(1)
+ assert (
+ dataset._server_address == mock_builder.store.data_server_client.server_address
+ )
+ assert dataset._table == mock_builder.store.trainer_id
+ assert dataset._max_in_flight_samples_per_worker == 100
+ assert (
+ mock_builder.store.dataset_iterator._dataset._num_parallel_calls
+ == ops.convert_to_tensor(
+ transition_dataset.config.num_parallel_calls,
+ dtype=dtypes.int64,
+ name="num_parallel_calls",
+ )
+ )
+
+
+def test_on_building_trainer_dataset_transition_dataset(
+ mock_builder: MockBuilder,
+) -> None:
+ """Test on_building_trainer_dataset of TransitionDataset Component
+ With max_in_flight_samples_per_worker and with sample_batch_size
+ Args:
+ mock_builder: Builder
+ """
+ transition_dataset = TransitionDataset()
+ transition_dataset.config.sample_batch_size = 512
+ transition_dataset.config.max_in_flight_samples_per_worker = 120
+ transition_dataset.on_building_trainer_dataset(builder=mock_builder)
+
+ # mock_builder.store.dataset_iterator._dataset._map_func._func(1)._dataset \
+ # is needed to check the parameters i.e. obtain the dataset from the \
+ # tf.data.Dataset dataset iterator
+
+ dataset = mock_builder.store.dataset_iterator._dataset._map_func._func(1)._dataset
+ assert (
+ dataset._input_dataset._server_address
+ == mock_builder.store.data_server_client.server_address
+ )
+ assert dataset._input_dataset._table == mock_builder.store.trainer_id
+ assert dataset._batch_size == transition_dataset.config.sample_batch_size
+ assert dataset._input_dataset._max_in_flight_samples_per_worker == 120
+ assert (
+ mock_builder.store.dataset_iterator._dataset._num_parallel_calls
+ == ops.convert_to_tensor(
+ transition_dataset.config.num_parallel_calls,
+ dtype=dtypes.int64,
+ name="num_parallel_calls",
+ )
+ )
+
+
+def test_init_trajectory_dataset(trajectory_dataset: TrajectoryDataset) -> None:
+ """Test initiator of TrajectoryDataset component"""
+ assert trajectory_dataset.config.sample_batch_size == 512
+ assert trajectory_dataset.config.max_in_flight_samples_per_worker == 1024
+ assert trajectory_dataset.config.num_workers_per_iterator == -2
+ assert trajectory_dataset.config.max_samples_per_stream == -2
+ assert trajectory_dataset.config.rate_limiter_timeout_ms == -2
+ assert trajectory_dataset.config.get_signature_timeout_secs is None
+
+
+def test_on_building_trainer_dataset_trajectory_dataset(
+ mock_builder: MockBuilder,
+) -> None:
+ """Test on_building_trainer_dataset of TrajectoryDataset Component
+
+ Args:
+ mock_builder: Builder
+ """
+ trajectory_dataset = TrajectoryDataset()
+ trajectory_dataset.on_building_trainer_dataset(builder=mock_builder)
+
+ assert (
+ mock_builder.store.sample_batch_size
+ == trajectory_dataset.config.sample_batch_size
+ )
+
+ # mock_builder.store.dataset_iterator._iterator._dataset is needed \
+ # to check the parameters i.e. obtain the dataset from the numpy \
+ # dataset iterator
+
+ dataset = mock_builder.store.dataset_iterator._iterator._dataset
+ assert (
+ dataset._input_dataset._server_address
+ == mock_builder.store.data_server_client.server_address
+ )
+ assert dataset._input_dataset._table == mock_builder.store.trainer_id
+ assert (
+ dataset._input_dataset._max_in_flight_samples_per_worker
+ == 2 * trajectory_dataset.config.sample_batch_size
+ )
+ assert (
+ dataset._input_dataset._num_workers_per_iterator
+ == trajectory_dataset.config.num_workers_per_iterator
+ )
+ assert (
+ dataset._input_dataset._max_samples_per_stream
+ == trajectory_dataset.config.max_samples_per_stream
+ )
+ assert (
+ dataset._input_dataset._rate_limiter_timeout_ms
+ == trajectory_dataset.config.rate_limiter_timeout_ms
+ )
|
conan-io__conan-4324 | tools.environment_append raises if tries to unset variable which was never set
after #4224, I may use the following code, for instance, to ensure variable is not set:
```
with environment_append({'CONAN_BASH_PATH': None}):
pass
```
however, it raises if `CONAN_BASH_PATH` is not set (prior to the environment_append invocation):
```
Traceback (most recent call last):
File "C:\bincrafters\conan\conans\test\unittests\client\tools\os_info\osinfo_test.py", line 39, in test_windows
with environment_append(new_env):
File "c:\users\sse4\appdata\local\programs\python\python36\lib\contextlib.py", line 81, in __enter__
return next(self.gen)
File "C:\bincrafters\conan\conans\client\tools\env.py", line 57, in environment_append
os.environ.pop(var)
File "c:\users\sse4\appdata\local\programs\python\python36\lib\_collections_abc.py", line 795, in pop
value = self[key]
File "c:\users\sse4\appdata\local\programs\python\python36\lib\os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'CONAN_BASH_PATH'
```
I would expect `tools.environment_append` to be no op in such case, otherwise, it requires additional logic to workaround this behavior.
To help us debug your issue please explain:
- [ ] I've read the [CONTRIBUTING guide](https://github.com/conan-io/conan/blob/develop/.github/CONTRIBUTING.md).
- [ ] I've specified the Conan version, operating system version and any tool that can be relevant.
- [ ] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion.
| [
{
"content": "import os\nimport sys\nfrom contextlib import contextmanager\n\nfrom conans.client.run_environment import RunEnvironment\nfrom conans.client.tools.files import _path_equals, which\nfrom conans.errors import ConanException\n\n\n@contextmanager\ndef pythonpath(conanfile):\n python_path = conanfil... | [
{
"content": "import os\nimport sys\nfrom contextlib import contextmanager\n\nfrom conans.client.run_environment import RunEnvironment\nfrom conans.client.tools.files import _path_equals, which\nfrom conans.errors import ConanException\n\n\n@contextmanager\ndef pythonpath(conanfile):\n python_path = conanfil... | diff --git a/conans/client/tools/env.py b/conans/client/tools/env.py
index 079f549fd12..2584065ddbb 100644
--- a/conans/client/tools/env.py
+++ b/conans/client/tools/env.py
@@ -54,7 +54,7 @@ def environment_append(env_vars):
old_env = dict(os.environ)
os.environ.update(env_vars)
for var in unset_vars:
- os.environ.pop(var)
+ os.environ.pop(var, None)
try:
yield
finally:
diff --git a/conans/test/unittests/client/tools/test_env.py b/conans/test/unittests/client/tools/test_env.py
index 2fcc1c1c82e..556139e306e 100644
--- a/conans/test/unittests/client/tools/test_env.py
+++ b/conans/test/unittests/client/tools/test_env.py
@@ -46,3 +46,9 @@ def test_environment_append_unsetting_all_variables(self):
'env_var2': 'value2'}),\
env.environment_append({'env_var1': None}):
self.assertNotIn('env_var1', os.environ)
+
+ def test_environment_append_unsetting_non_existing_variables(self):
+ with mock.patch.dict('os.environ',
+ {'env_var2': 'value2'}),\
+ env.environment_append({'env_var1': None}):
+ self.assertNotIn('env_var1', os.environ)
|
translate__pootle-4882 | Make `pootle webpack` not require system checks
`pootle webpack` fails if eg the db is not set up/correctly. It would be helpful if it didnt
| [
{
"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport os\nos.... | [
{
"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport os\nos.... | diff --git a/pootle/apps/pootle_app/management/commands/webpack.py b/pootle/apps/pootle_app/management/commands/webpack.py
index fc5d602f8f8..1f6ce4b774c 100644
--- a/pootle/apps/pootle_app/management/commands/webpack.py
+++ b/pootle/apps/pootle_app/management/commands/webpack.py
@@ -19,6 +19,7 @@
class Command(BaseCommand):
help = 'Builds and bundles static assets using webpack'
+ requires_system_checks = False
def add_arguments(self, parser):
parser.add_argument(
|
encode__django-rest-framework-1836 | Adding the `DjangoFilterBackend` filter changes queryset ordering.
Tried posting on StackOverflow with no reply (http://stackoverflow.com/questions/21848095/adding-filtering-changes-ordering) => decided to open bug here
I have a ModelViewSet that I want to add filtering to. My simple model looks like
```
class Article(models.Model):
date = = models.DateField()
language = models.CharField(max_length=10)
class Meta:
ordering = ['-date']
```
And the ModelViewSet (read only):
```
class ArticleViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
```
Articles on the API are now ordered by date descending as I would expect. Now I wich to allow filtering on language. I've set the filter backend to `DjangoFilterBackend` in settings.py. My updated ModelViewSet now looks like:
```
class ArticleViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filter_fields = ['language']
```
This changes the ordering to language ASC. Adding `order_by('-date')` to queryset does not change anything. Adding `ordering = ('-date', )` does not change anything. => How do I specify both filtering and ordering (or simply use default ordering while allowing filtering)?
**EDIT:**
Current functionality seems to come from AutoFilterSet created in Rest Framework by default:
https://github.com/tomchristie/django-rest-framework/blob/822eb39599b248c68573c3095639a831ab6df99a/rest_framework/filters.py#L53
... where `order_by=True` and the handing of this in django-filter `get_ordering_field` here: https://github.com/alex/django-filter/blob/d88b98dd2b70551deb9c128b209fcf783b325acc/django_filters/filterset.py#L325
=> Seems I have to create a FilterSet class:
```
class LanguageFilter(django_filters.FilterSet):
class Meta:
model = Article
fields = ['language']
order_by = model()._meta.ordering
class ArticleViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filter_class = LanguageFilter
```
Does this look correct? Seems a bit "much"/verbose/counter-intuitive to retain default ordering.
| [
{
"content": "\"\"\"\nProvides generic filtering backends that can be used to filter the results\nreturned by list views.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.utils import six\nfrom rest_framework.com... | [
{
"content": "\"\"\"\nProvides generic filtering backends that can be used to filter the results\nreturned by list views.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.utils import six\nfrom rest_framework.com... | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
index e20800130d..c580f9351b 100644
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -56,7 +56,6 @@ class AutoFilterSet(self.default_filter_set):
class Meta:
model = queryset.model
fields = filter_fields
- order_by = True
return AutoFilterSet
return None
diff --git a/tests/test_filters.py b/tests/test_filters.py
index 47bffd4366..5722fd7c5f 100644
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -408,16 +408,61 @@ class SearchListView(generics.ListAPIView):
)
-class OrdringFilterModel(models.Model):
+class OrderingFilterModel(models.Model):
title = models.CharField(max_length=20)
text = models.CharField(max_length=100)
class OrderingFilterRelatedModel(models.Model):
- related_object = models.ForeignKey(OrdringFilterModel,
+ related_object = models.ForeignKey(OrderingFilterModel,
related_name="relateds")
+class DjangoFilterOrderingModel(models.Model):
+ date = models.DateField()
+ text = models.CharField(max_length=10)
+
+ class Meta:
+ ordering = ['-date']
+
+
+class DjangoFilterOrderingTests(TestCase):
+ def setUp(self):
+ data = [{
+ 'date': datetime.date(2012, 10, 8),
+ 'text': 'abc'
+ }, {
+ 'date': datetime.date(2013, 10, 8),
+ 'text': 'bcd'
+ }, {
+ 'date': datetime.date(2014, 10, 8),
+ 'text': 'cde'
+ }]
+
+ for d in data:
+ DjangoFilterOrderingModel.objects.create(**d)
+
+ def test_default_ordering(self):
+ class DjangoFilterOrderingView(generics.ListAPIView):
+ model = DjangoFilterOrderingModel
+ filter_backends = (filters.DjangoFilterBackend,)
+ filter_fields = ['text']
+ ordering = ('-date',)
+
+ view = DjangoFilterOrderingView.as_view()
+ request = factory.get('/')
+ response = view(request)
+
+ self.assertEqual(
+ response.data,
+ [
+ {'id': 3, 'date': datetime.date(2014, 10, 8), 'text': 'cde'},
+ {'id': 2, 'date': datetime.date(2013, 10, 8), 'text': 'bcd'},
+ {'id': 1, 'date': datetime.date(2012, 10, 8), 'text': 'abc'}
+ ]
+ )
+
+
class OrderingFilterTests(TestCase):
def setUp(self):
# Sequence of title/text is:
@@ -436,11 +481,11 @@ def setUp(self):
chr(idx + ord('b')) +
chr(idx + ord('c'))
)
- OrdringFilterModel(title=title, text=text).save()
+ OrderingFilterModel(title=title, text=text).save()
def test_ordering(self):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
ordering_fields = ('text',)
@@ -459,7 +504,7 @@ class OrderingListView(generics.ListAPIView):
def test_reverse_ordering(self):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
ordering_fields = ('text',)
@@ -478,7 +523,7 @@ class OrderingListView(generics.ListAPIView):
def test_incorrectfield_ordering(self):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
ordering_fields = ('text',)
@@ -497,7 +542,7 @@ class OrderingListView(generics.ListAPIView):
def test_default_ordering(self):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
oredering_fields = ('text',)
@@ -516,7 +561,7 @@ class OrderingListView(generics.ListAPIView):
def test_default_ordering_using_string(self):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = 'title'
ordering_fields = ('text',)
@@ -536,7 +581,7 @@ class OrderingListView(generics.ListAPIView):
def test_ordering_by_aggregate_field(self):
# create some related models to aggregate order by
num_objs = [2, 5, 3]
- for obj, num_relateds in zip(OrdringFilterModel.objects.all(),
+ for obj, num_relateds in zip(OrderingFilterModel.objects.all(),
num_objs):
for _ in range(num_relateds):
new_related = OrderingFilterRelatedModel(
@@ -545,11 +590,11 @@ def test_ordering_by_aggregate_field(self):
new_related.save()
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = 'title'
ordering_fields = '__all__'
- queryset = OrdringFilterModel.objects.all().annotate(
+ queryset = OrderingFilterModel.objects.all().annotate(
models.Count("relateds"))
view = OrderingListView.as_view()
@@ -567,7 +612,7 @@ class OrderingListView(generics.ListAPIView):
def test_ordering_with_nonstandard_ordering_param(self):
with temporary_setting('ORDERING_PARAM', 'order', filters):
class OrderingListView(generics.ListAPIView):
- model = OrdringFilterModel
+ model = OrderingFilterModel
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
ordering_fields = ('text',)
|
codespell-project__codespell-3015 | ruff is causing PR checks to fail
PR checks are failing on "Run make check" due to this error:
```
ruff .
Error: codespell_lib/_codespell.py:194:17: PLE1300 Unsupported format character '}'
make: *** [Makefile:42: ruff] Error 1
Error: Process completed with exit code 2.
```
Recently, the ruff version increased from `ruff-0.0.282` to `ruff-0.0.283`. Either fix the Python code, or downgrade ruff.
| [
{
"content": "#\n# 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; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARR... | [
{
"content": "#\n# 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; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARR... | diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
index 1fe8c6306c..e7d2236b78 100644
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -190,10 +190,7 @@ def __str__(self) -> str:
keys.sort()
return "\n".join(
- [
- "{0}{1:{width}}".format(key, self.summary.get(key), width=15 - len(key))
- for key in keys
- ]
+ [f"{key}{self.summary.get(key):{15 - len(key)}}" for key in keys]
)
|
urllib3__urllib3-1912 | Add additional documentation for HTTPSConnection parameters
I'm not sure if this is intentional or not, but the reference doc for connection objects ( https://urllib3.readthedocs.io/en/latest/reference/index.html#urllib3.connection.VerifiedHTTPSConnection ) seems a little bit spare on details about the parameters accepted.
In particular, I was looking at using `server_hostname`, and I didn't find it anywhere in the reference doc.
I did eventually find it (I assume with the same meaning) documented on [this utility function](https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.ssl_wrap_socket).
Coming to these docs having very rarely needed to work directly with urllib3 (it's usually the transport used by some higher-level library I'm using, like `requests`), it seemed like the docs for the connection object were missing bits. If I were to open a PR adding a line to the docstring for each parameter, would it be welcome? Or are these params meant to be covered elsewhere in the docs?
| [
{
"content": "from __future__ import absolute_import\nimport re\nimport datetime\nimport logging\nimport os\nimport socket\nfrom socket import error as SocketError, timeout as SocketTimeout\nimport warnings\nfrom .packages import six\nfrom .packages.six.moves.http_client import HTTPConnection as _HTTPConnection... | [
{
"content": "from __future__ import absolute_import\nimport re\nimport datetime\nimport logging\nimport os\nimport socket\nfrom socket import error as SocketError, timeout as SocketTimeout\nimport warnings\nfrom .packages import six\nfrom .packages.six.moves.http_client import HTTPConnection as _HTTPConnection... | diff --git a/docs/advanced-usage.rst b/docs/advanced-usage.rst
index e36287a064..1a9b007b43 100644
--- a/docs/advanced-usage.rst
+++ b/docs/advanced-usage.rst
@@ -172,6 +172,45 @@ verified with that bundle will succeed. It's recommended to use a separate
:class:`~poolmanager.PoolManager` to make requests to URLs that do not need
the custom certificate.
+.. _sni_custom:
+
+Custom SNI Hostname
+-------------------
+
+If you want to create a connection to a host over HTTPS which uses SNI, there
+are two places where the hostname is expected. It must be included in the Host
+header sent, so that the server will know which host is being requested. The
+hostname should also match the certificate served by the server, which is
+checked by urllib3.
+
+Normally, urllib3 takes care of setting and checking these values for you when
+you connect to a host by name. However, it's sometimes useful to set a
+connection's expected Host header and certificate hostname (subject),
+especially when you are connecting without using name resolution. For example,
+you could connect to a server by IP using HTTPS like so::
+
+ >>> import urllib3
+ >>> pool = urllib3.HTTPSConnectionPool(
+ ... "10.0.0.10",
+ ... assert_hostname="example.org",
+ ... server_hostname="example.org"
+ ... )
+ >>> pool.urlopen(
+ ... "GET",
+ ... "/",
+ ... headers={"Host": "example.org"},
+ ... assert_same_host=False
+ ... )
+
+
+Note that when you use a connection in this way, you must specify
+``assert_same_host=False``.
+
+This is useful when DNS resolution for ``example.org`` does not match the
+address that you would like to use. The IP may be for a private interface, or
+you may want to use a specific host under round-robin DNS.
+
+
.. _ssl_client:
Client certificates
diff --git a/src/urllib3/connection.py b/src/urllib3/connection.py
index cf9cfee9a1..8c63f1fa8d 100644
--- a/src/urllib3/connection.py
+++ b/src/urllib3/connection.py
@@ -251,6 +251,11 @@ def request_chunked(self, method, url, body=None, headers=None):
class HTTPSConnection(HTTPConnection):
+ """
+ Many of the parameters to this constructor are passed to the underlying SSL
+ socket by means of :py:func:`util.ssl_wrap_socket`.
+ """
+
default_port = port_by_scheme["https"]
cert_reqs = None
|
keras-team__keras-1158 | problem with K.common._FLOATX
I tried to run:
```
a = K.random_normal((100, 200))
```
and I got the error:
```
/home/eders/python/Theano/theano/sandbox/rng_mrg.pyc in get_substream_rstates(self, n_streams, dtype, inc_rstate)
1167
1168 """
-> 1169 assert isinstance(dtype, str)
1170 assert n_streams < 2**72
1171 assert n_streams > 0
AssertionError:
```
I tried to print K.common._FLOATX to see what was going on and it is `u'float32'`. That little `u` upfront is making theano crash. I believe that when reading the type from json it was not converted to the right type of string. Anybody else had that problem? I'll check the code to see if I can fix it.
| [
{
"content": "import numpy as np\n\n# the type of float to use throughout the session.\n_FLOATX = 'float32'\n_EPSILON = 10e-8\n\n\ndef epsilon():\n return _EPSILON\n\n\ndef set_epsilon(e):\n global _EPSILON\n _EPSILON = e\n\n\ndef floatx():\n return _FLOATX\n\n\ndef set_floatx(floatx):\n global _... | [
{
"content": "import numpy as np\n\n# the type of float to use throughout the session.\n_FLOATX = 'float32'\n_EPSILON = 10e-8\n\n\ndef epsilon():\n return _EPSILON\n\n\ndef set_epsilon(e):\n global _EPSILON\n _EPSILON = e\n\n\ndef floatx():\n return _FLOATX\n\n\ndef set_floatx(floatx):\n global _... | diff --git a/keras/backend/common.py b/keras/backend/common.py
index 1a84aaf37c41..86284713e297 100644
--- a/keras/backend/common.py
+++ b/keras/backend/common.py
@@ -22,6 +22,8 @@ def set_floatx(floatx):
global _FLOATX
if floatx not in {'float32', 'float64'}:
raise Exception('Unknown floatx type: ' + str(floatx))
+ if isinstance(floatx, unicode):
+ floatx = floatx.encode('ascii')
_FLOATX = floatx
|
apache__airflow-23674 | PythonSensor is not considering mode='reschedule', instead marking task UP_FOR_RETRY
### Apache Airflow version
2.3.0 (latest released)
### What happened
A PythonSensor that works on versions <2.3.0 in mode reschedule is now marking the task as `UP_FOR_RETRY` instead.
Log says:
```
[2022-05-02, 15:48:23 UTC] {python.py:66} INFO - Poking callable: <function test at 0x7fd56286bc10>
[2022-05-02, 15:48:23 UTC] {taskinstance.py:1853} INFO - Rescheduling task, marking task as UP_FOR_RESCHEDULE
[2022-05-02, 15:48:23 UTC] {local_task_job.py:156} INFO - Task exited with return code 0
[2022-05-02, 15:48:23 UTC] {local_task_job.py:273} INFO - 0 downstream tasks scheduled from follow-on schedule check
```
But it directly marks it as `UP_FOR_RETRY` and then follows `retry_delay` and `retries`
### What you think should happen instead
It should mark the task as `UP_FOR_RESCHEDULE` and reschedule it according to the `poke_interval`
### How to reproduce
```
from datetime import datetime, timedelta
from airflow import DAG
from airflow.sensors.python import PythonSensor
def test():
return False
default_args = {
"owner": "airflow",
"depends_on_past": False,
"start_date": datetime(2022, 5, 2),
"email_on_failure": False,
"email_on_retry": False,
"retries": 1,
"retry_delay": timedelta(minutes=1),
}
dag = DAG("dag_csdepkrr_development_v001",
default_args=default_args,
catchup=False,
max_active_runs=1,
schedule_interval=None)
t1 = PythonSensor(task_id="PythonSensor",
python_callable=test,
poke_interval=30,
mode='reschedule',
dag=dag)
```
### Operating System
Latest Docker image
### Versions of Apache Airflow Providers
```
apache-airflow-providers-amazon==3.3.0
apache-airflow-providers-celery==2.1.4
apache-airflow-providers-cncf-kubernetes==4.0.1
apache-airflow-providers-docker==2.6.0
apache-airflow-providers-elasticsearch==3.0.3
apache-airflow-providers-ftp==2.1.2
apache-airflow-providers-google==6.8.0
apache-airflow-providers-grpc==2.0.4
apache-airflow-providers-hashicorp==2.2.0
apache-airflow-providers-http==2.1.2
apache-airflow-providers-imap==2.2.3
apache-airflow-providers-microsoft-azure==3.8.0
apache-airflow-providers-mysql==2.2.3
apache-airflow-providers-odbc==2.0.4
apache-airflow-providers-oracle==2.2.3
apache-airflow-providers-postgres==4.1.0
apache-airflow-providers-redis==2.0.4
apache-airflow-providers-sendgrid==2.0.4
apache-airflow-providers-sftp==2.5.2
apache-airflow-providers-slack==4.2.3
apache-airflow-providers-sqlite==2.1.3
apache-airflow-providers-ssh==2.4.3
```
### Deployment
Docker-Compose
### Deployment details
Latest Docker compose from the documentation
### Anything else
_No response_
### Are you willing to submit PR?
- [ ] Yes I am willing to submit a PR!
### Code of Conduct
- [X] I agree to follow this project's [Code of Conduct](https://github.com/apache/airflow/blob/main/CODE_OF_CONDUCT.md)
| [
{
"content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (th... | [
{
"content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (th... | diff --git a/airflow/sensors/base.py b/airflow/sensors/base.py
index 5cbe009c82b95..590b48f04bc73 100644
--- a/airflow/sensors/base.py
+++ b/airflow/sensors/base.py
@@ -339,6 +339,10 @@ def reschedule(self):
"""Define mode rescheduled sensors."""
return self.mode == 'reschedule'
+ @classmethod
+ def get_serialized_fields(cls):
+ return super().get_serialized_fields() | {"reschedule"}
+
def poke_mode_only(cls):
"""
diff --git a/tests/serialization/test_dag_serialization.py b/tests/serialization/test_dag_serialization.py
index 0144501f1a13d..fe9fc7c7e5447 100644
--- a/tests/serialization/test_dag_serialization.py
+++ b/tests/serialization/test_dag_serialization.py
@@ -1462,6 +1462,7 @@ def poke(self, context: Context):
assert "deps" in blob
serialized_op = SerializedBaseOperator.deserialize_operator(blob)
+ assert serialized_op.reschedule == (mode == "reschedule")
assert op.deps == serialized_op.deps
@pytest.mark.parametrize(
diff --git a/tests/ti_deps/deps/test_ready_to_reschedule_dep.py b/tests/ti_deps/deps/test_ready_to_reschedule_dep.py
index 470166db21c8d..99416bbbc8927 100644
--- a/tests/ti_deps/deps/test_ready_to_reschedule_dep.py
+++ b/tests/ti_deps/deps/test_ready_to_reschedule_dep.py
@@ -31,7 +31,7 @@
class TestNotInReschedulePeriodDep(unittest.TestCase):
def _get_task_instance(self, state):
dag = DAG('test_dag')
- task = Mock(dag=dag)
+ task = Mock(dag=dag, reschedule=True)
ti = TaskInstance(task=task, state=state, run_id=None)
return ti
@@ -52,6 +52,11 @@ def test_should_pass_if_ignore_in_reschedule_period_is_set(self):
dep_context = DepContext(ignore_in_reschedule_period=True)
assert ReadyToRescheduleDep().is_met(ti=ti, dep_context=dep_context)
+ def test_should_pass_if_not_reschedule_mode(self):
+ ti = self._get_task_instance(State.UP_FOR_RESCHEDULE)
+ del ti.task.reschedule
+ assert ReadyToRescheduleDep().is_met(ti=ti)
+
def test_should_pass_if_not_in_none_state(self):
ti = self._get_task_instance(State.UP_FOR_RETRY)
assert ReadyToRescheduleDep().is_met(ti=ti)
|
vispy__vispy-2592 | What's the status of GLFW?
I see there's a `glfw` backend, but in `setup.py` it is neither listed as a dependency nor defined as an extra. Is that an oversight or deliberately?
I'm packaging `vispy` for Fedora and with [glfw](https://pypi.org/project/glfw/) added as a dependency, I'm seeing `glfw` listed in the output of `vispy.sys_info()`. Tests using `glsw` as a backend also appear to work fine.
| [
{
"content": "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"Vispy setup script.\n\nSteps to do a new release:\n\nPreparations:\n * Test on Windows, Linux, Mac\n * Make release notes\n * U... | [
{
"content": "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"Vispy setup script.\n\nSteps to do a new release:\n\nPreparations:\n * Test on Windows, Linux, Mac\n * Make release notes\n * U... | diff --git a/setup.py b/setup.py
index 65cd9febc..2b49960d9 100644
--- a/setup.py
+++ b/setup.py
@@ -106,6 +106,7 @@ def set_builtin(name, value):
'pyside': ['PySide'],
'pyside2': ['PySide2'],
'pyside6': ['PySide6'],
+ 'glfw': ['glfw'],
'sdl2': ['PySDL2'],
'wx': ['wxPython'],
'tk': ['pyopengltk'],
|
cocotb__cocotb-1470 | Documentation building: "WARNING: duplicate label"
With ``sphinx.ext.autosectionlabel`` (in use since https://github.com/cocotb/cocotb/commit/862012b3c01f90ea1fb715c206b4eb785119f964), we got quite some new "duplicate label" warnings.
To fix some of those warnings, we could set ``autosectionlabel_prefix_document = True`` which prefixes each automatically generated section label with the name of the document it is in, followed by a colon.
A drawback is that we would now hardcode the file name of the document into the reference,
so that we are not as free with renaming documents anymore. Also, we cannot catch all those duplicates that way, e.g. in the release notes, there are multiple "new features" subsections.
The alternative is to remove ``sphinx.ext.autosectionlabel`` and set our own reference anchors.
I would prefer this.
Ping @Martoni
| [
{
"content": "# -*- coding: utf-8 -*-\n#\n# cocotb documentation build configuration file\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport datetime\nimport os\... | [
{
"content": "# -*- coding: utf-8 -*-\n#\n# cocotb documentation build configuration file\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport datetime\nimport os\... | diff --git a/documentation/source/building.rst b/documentation/source/building.rst
index 763b1c270d..5c5bbcb1a8 100644
--- a/documentation/source/building.rst
+++ b/documentation/source/building.rst
@@ -53,7 +53,7 @@ and
.. make:var:: WAVES
Set this to 1 to enable wave traces dump for the Aldec Riviera-PRO and Mentor Graphics Questa simulators.
- To get wave traces in Icarus Verilog see :ref:`Simulator Support`.
+ To get wave traces in Icarus Verilog see :ref:`sim-icarus-waveforms`.
.. make:var:: VERILOG_SOURCES
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
index ef46877454..87f2bc9583 100644
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -42,7 +42,6 @@
'sphinx.ext.napoleon',
'sphinx.ext.intersphinx',
'sphinxcontrib.makedomain',
- 'sphinx.ext.autosectionlabel',
'sphinx.ext.inheritance_diagram',
'cairosvgconverter',
'breathe',
diff --git a/documentation/source/coroutines.rst b/documentation/source/coroutines.rst
index 1f96bfc133..1314aa5487 100644
--- a/documentation/source/coroutines.rst
+++ b/documentation/source/coroutines.rst
@@ -1,3 +1,5 @@
+.. _coroutines:
+
**********
Coroutines
**********
diff --git a/documentation/source/extensions.rst b/documentation/source/extensions.rst
index 1256e6f26f..661e3ad719 100644
--- a/documentation/source/extensions.rst
+++ b/documentation/source/extensions.rst
@@ -14,6 +14,8 @@ In cocotb, such functionality can be packaged and distributed as extensions.
Technically, cocotb extensions are normal Python packages, and all standard Python packaging and distribution techniques can be used.
Additionally, the cocotb community has agreed on a set of conventions to make extensions easier to use and to discover.
+.. _extensions-naming-conventions:
+
Naming conventions
==================
@@ -52,7 +54,7 @@ Bus monitors should inherit from the :any:`cocotb.monitors.BusMonitor` class.
Packaging extensions
====================
-To package a cocotb extension as Python package follow the :ref:`naming conventions <Naming conventions>`, and the `normal Python packaging rules <https://packaging.python.org/tutorials/packaging-projects/>`_.
+To package a cocotb extension as Python package follow the :ref:`extensions-naming-conventions`, and the `normal Python packaging rules <https://packaging.python.org/tutorials/packaging-projects/>`_.
Extensions namespaced packages, implemented using the `native namespacing <https://packaging.python.org/guides/packaging-namespace-packages/#native-namespace-packages>`_ approach discussed in :pep:`420`.
The module file hierarchy should be as follows (replace ``EXTNAME`` with the name of the extension, e.g. ``spi``).
diff --git a/documentation/source/quickstart.rst b/documentation/source/quickstart.rst
index 965fed428b..2186c5838f 100644
--- a/documentation/source/quickstart.rst
+++ b/documentation/source/quickstart.rst
@@ -252,7 +252,7 @@ Use ``sig.setimmediatevalue(new_val)`` to set a new value immediately
In addition to regular value assignments (deposits), signals can be forced
to a predetermined value or frozen at their current value. To achieve this,
-the various actions described in :ref:`Assignment Methods <assignment-methods>` can be used.
+the various actions described in :ref:`assignment-methods` can be used.
.. code-block:: python3
@@ -303,7 +303,7 @@ We can also cast the signal handle directly to an integer:
Parallel and sequential execution
---------------------------------
-A :keyword:`yield` will run a function (that must be marked as a "coroutine", see :ref:`Coroutines`)
+A :keyword:`yield` will run a function (that must be marked as a "coroutine", see :ref:`coroutines`)
sequentially, i.e. wait for it to complete.
If a coroutine should be run "in the background", i.e. in parallel to other coroutines,
the way to do this is to :func:`~cocotb.fork` it.
diff --git a/documentation/source/release_notes.rst b/documentation/source/release_notes.rst
index 35a2e712c2..b82afffb83 100644
--- a/documentation/source/release_notes.rst
+++ b/documentation/source/release_notes.rst
@@ -18,7 +18,7 @@ This will likely be the last release to support Python 2.7.
New features
------------
-- Initial support for the :ref:`Verilator` simulator (version 4.020 and above).
+- Initial support for the :ref:`sim-verilator` simulator (version 4.020 and above).
The integration of Verilator into cocotb is not yet as fast or as powerful as it is for other simulators.
Please use the latest version of Verilator, and `report bugs <https://github.com/cocotb/cocotb/issues/new>`_ if you experience problems.
- New makefile variables :make:var:`COCOTB_HDL_TIMEUNIT` and :make:var:`COCOTB_HDL_TIMEPRECISION` for setting the default time unit and precision that should be assumed for simulation when not specified by modules in the design. (:pr:`1113`)
diff --git a/documentation/source/simulator_support.rst b/documentation/source/simulator_support.rst
index 520be11b48..020fe18699 100644
--- a/documentation/source/simulator_support.rst
+++ b/documentation/source/simulator_support.rst
@@ -1,12 +1,19 @@
+.. _simulator-support:
+
*****************
Simulator Support
*****************
This page documents any known quirks and gotchas in the various simulators.
+
+.. _sim-icarus:
+
Icarus
======
+.. _sim-icarus-accessing-bits:
+
Accessing bits in a vector
--------------------------
@@ -18,6 +25,8 @@ Accessing bits of a vector doesn't work:
See ``access_single_bit`` test in :file:`examples/functionality/tests/test_discovery.py`.
+.. _sim-icarus-waveforms:
+
Waveforms
---------
@@ -44,12 +53,17 @@ to the top component as shown in the example below:
`endif
endmodule
+.. _sim-icarus-time:
+
Time unit and precision
-----------------------
Setting the time unit and time precision is not possible from the command-line,
and therefore make variables :make:var:`COCOTB_HDL_TIMEUNIT` and :make:var:`COCOTB_HDL_TIMEPRECISION` are ignored.
+
+.. _sim-verilator:
+
Verilator
=========
@@ -69,20 +83,31 @@ If your design's clocks vary in precision, the performance of the simulation can
.. versionadded:: 1.3
+
+.. _sim-vcs:
+
Synopsys VCS
============
+.. _sim-aldec:
+
Aldec Riviera-PRO
=================
The :envvar:`LICENSE_QUEUE` environment variable can be used for this simulator –
this setting will be mirrored in the TCL ``license_queue`` variable to control runtime license checkouts.
+
+.. _sim-questa:
+
Mentor Questa
=============
+
+.. _sim-modelsim:
+
Mentor ModelSim
===============
@@ -95,9 +120,20 @@ If you try to run with FLI enabled, you will see a ``vsim-FLI-3155`` error:
ModelSim DE and SE (and Questa, of course) supports the FLI.
-Cadence Incisive, Cadence Xcelium
-=================================
+.. _sim-incisive:
+
+Cadence Incisive
+================
+
+
+.. _sim-xcelium:
+
+Cadence Xcelium
+===============
+
+
+.. _sim-ghdl:
GHDL
====
|
pymedusa__Medusa-9273 | IPT Provider error
Hello, it has been like a month since I am having this problem.
Medusa is unable to use IPTorrents to search and download, it always worked perfect until one day. I have double check the cookie values and they are an exact match.
Anyone can help me? here's the log with the error
2021-02-09 16:18:43 INFO FORCEDSEARCHQUEUE-MANUAL-364928 :: [2ab9d45] Unable to find manual results for: Snowpiercer - S02E02 - Smolder to Life
2021-02-09 16:18:43 INFO FORCEDSEARCHQUEUE-MANUAL-364928 :: IPTorrents :: [2ab9d45] Performing season pack search for Snowpiercer
2021-02-09 16:18:43 WARNING FORCEDSEARCHQUEUE-MANUAL-364928 :: IPTorrents :: [2ab9d45] Please configure the required cookies for this provider. Check your provider settings
2021-02-09 16:18:43 INFO FORCEDSEARCHQUEUE-MANUAL-364928 :: IPTorrents :: [2ab9d45] Unknown exception in url https://iptorrents.eu Error: Cloudflare IUAM possibility malformed, issue extracing delay value.
2021-02-09 16:18:43 INFO FORCEDSEARCHQUEUE-MANUAL-364928 :: IPTorrents :: [2ab9d45] Performing episode search for Snowpiercer
Could it be because it's using iptorrents.eu instead of iptorrents.com?
| [
{
"content": "# coding=utf-8\n\n\"\"\"Provider code for IPTorrents.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport logging\nimport re\n\nfrom medusa import tv\nfrom medusa.bs4_parser import BS4Parser\nfrom medusa.helper.common import convert_size\nfrom medusa.logger.adapters.style import BraceAdapte... | [
{
"content": "# coding=utf-8\n\n\"\"\"Provider code for IPTorrents.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport logging\nimport re\n\nfrom medusa import tv\nfrom medusa.bs4_parser import BS4Parser\nfrom medusa.helper.common import convert_size\nfrom medusa.logger.adapters.style import BraceAdapte... | diff --git a/medusa/providers/torrent/html/iptorrents.py b/medusa/providers/torrent/html/iptorrents.py
index 9f16a540b3..1751ea6783 100644
--- a/medusa/providers/torrent/html/iptorrents.py
+++ b/medusa/providers/torrent/html/iptorrents.py
@@ -42,6 +42,7 @@ def __init__(self):
self.cookies = ''
self.required_cookies = ('uid', 'pass')
self.categories = '73=&60='
+ self.custom_url = None
# Cache
self.cache = tv.Cache(self)
|
RedHatInsights__insights-core-2085 | Dmesg combiner always succeeds
The [Dmesg combiner has only optional dependencies](https://github.com/RedHatInsights/insights-core/blob/master/insights/combiners/dmesg.py#L51), which means it always succeeds. This is an anti-pattern.
| [
{
"content": "\"\"\"\nDmesg\n=====\n\nCombiner for Dmesg information. It uses the results of the following parsers (if they are present):\n:class:`insights.parsers.dmesg.DmesgLineList`,\n:class:`insights.parsers.dmesg_log.DmesgLog`\n\nTypical output of the ``/var/log/dmesg`` file is::\n\n[ 0.000000] Initiali... | [
{
"content": "\"\"\"\nDmesg\n=====\n\nCombiner for Dmesg information. It uses the results of the following parsers (if they are present):\n:class:`insights.parsers.dmesg.DmesgLineList`,\n:class:`insights.parsers.dmesg_log.DmesgLog`\n\nTypical output of the ``/var/log/dmesg`` file is::\n\n[ 0.000000] Initiali... | diff --git a/insights/combiners/dmesg.py b/insights/combiners/dmesg.py
index 671a26cb5d..8424bb552f 100644
--- a/insights/combiners/dmesg.py
+++ b/insights/combiners/dmesg.py
@@ -48,7 +48,7 @@
from insights.parsers.dmesg_log import DmesgLog
-@combiner(optional=[DmesgLineList, DmesgLog])
+@combiner([DmesgLineList, DmesgLog])
class Dmesg(object):
"""
Combiner for ``dmesg`` command and ``/var/log/dmesg`` file.
|
geopandas__geopandas-2398 | Drop Python 3.7
We should consider dropping support for Python 3.7. We are roughly following numpy model (#1457) and numpy itself is 3.8+ now. Same applies to pyproj, which requires 3.8 (and causes some macOS CI failures because of some conda issues).
I forgot about Python versions when doing #2358 and bumped only packages.
@jorisvandenbossche if you're fine with that, I'll update CI matrix and related things.
| [
{
"content": "#!/usr/bin/env/python\n\"\"\"Installation script\n\n\"\"\"\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nimport versioneer\n\nLONG_DESCRIPTION = \"\"\"GeoPandas is a project to add support for geographic data to\n`pandas`_ obje... | [
{
"content": "#!/usr/bin/env/python\n\"\"\"Installation script\n\n\"\"\"\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nimport versioneer\n\nLONG_DESCRIPTION = \"\"\"GeoPandas is a project to add support for geographic data to\n`pandas`_ obje... | diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml
index 6e5e99e9c4..2a0da2bc23 100644
--- a/.github/workflows/tests.yaml
+++ b/.github/workflows/tests.yaml
@@ -17,8 +17,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
- - uses: actions/setup-python@v2
+ - uses: actions/checkout@v3
+ - uses: actions/setup-python@v3
- uses: pre-commit/action@v2.0.3
Test:
@@ -35,28 +35,28 @@ jobs:
postgis: [false]
dev: [false]
env:
- - ci/envs/37-minimal.yaml
- - ci/envs/38-no-optional-deps.yaml
- - ci/envs/37-pd11.yaml
- - ci/envs/37-latest-defaults.yaml
- - ci/envs/37-latest-conda-forge.yaml
+ - ci/envs/38-minimal.yaml
+ - ci/envs/39-no-optional-deps.yaml
+ - ci/envs/38-pd11-defaults.yaml
+ - ci/envs/38-latest-defaults.yaml
- ci/envs/38-latest-conda-forge.yaml
+ - ci/envs/39-pd12-conda-forge.yaml
- ci/envs/39-latest-conda-forge.yaml
- ci/envs/310-latest-conda-forge.yaml
include:
- - env: ci/envs/37-latest-conda-forge.yaml
+ - env: ci/envs/38-latest-conda-forge.yaml
os: macos-latest
postgis: false
dev: false
- - env: ci/envs/38-latest-conda-forge.yaml
+ - env: ci/envs/39-latest-conda-forge.yaml
os: macos-latest
postgis: false
dev: false
- - env: ci/envs/37-latest-conda-forge.yaml
+ - env: ci/envs/38-latest-conda-forge.yaml
os: windows-latest
postgis: false
dev: false
- - env: ci/envs/38-latest-conda-forge.yaml
+ - env: ci/envs/39-latest-conda-forge.yaml
os: windows-latest
postgis: false
dev: false
@@ -65,7 +65,7 @@ jobs:
dev: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Setup Conda
uses: conda-incubator/setup-miniconda@v2
@@ -106,7 +106,7 @@ jobs:
pytest -v -r s -n auto --color=yes --cov=geopandas --cov-append --cov-report term-missing --cov-report xml geopandas/
- name: Test with PostGIS
- if: contains(matrix.env, '38-latest-conda-forge.yaml') && contains(matrix.os, 'ubuntu')
+ if: contains(matrix.env, '39-pd12-conda-forge.yaml') && contains(matrix.os, 'ubuntu')
env:
PGUSER: postgres
PGPASSWORD: postgres
@@ -118,7 +118,7 @@ jobs:
pytest -v -r s --color=yes --cov=geopandas --cov-append --cov-report term-missing --cov-report xml geopandas/io/tests/test_sql.py | tee /dev/stderr | if grep SKIPPED >/dev/null;then echo "TESTS SKIPPED, FAILING" && exit 1;fi
- name: Test docstrings
- if: contains(matrix.env, '38-latest-conda-forge.yaml') && contains(matrix.os, 'ubuntu')
+ if: contains(matrix.env, '39-pd12-conda-forge.yaml') && contains(matrix.os, 'ubuntu')
env:
USE_PYGEOS: 1
run: |
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 40fecd6bb6..76bbf2fbf5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -13,7 +13,6 @@ In general, GeoPandas follows the conventions of the pandas project
where applicable. Please read the [contributing
guidelines](https://geopandas.readthedocs.io/en/latest/community/contributing.html).
-
In particular, when submitting a pull request:
- Install the requirements for the development environment (one can do this
@@ -39,7 +38,7 @@ is a great way to get started if you'd like to make a contribution.
Style
-----
-- GeoPandas supports Python 3.7+ only. The last version of GeoPandas
+- GeoPandas supports Python 3.8+ only. The last version of GeoPandas
supporting Python 2 is 0.6.
- GeoPandas follows [the PEP 8
diff --git a/ci/envs/38-latest-conda-forge.yaml b/ci/envs/38-latest-conda-forge.yaml
index 6d2348f1b4..c6ea71260d 100644
--- a/ci/envs/38-latest-conda-forge.yaml
+++ b/ci/envs/38-latest-conda-forge.yaml
@@ -4,7 +4,7 @@ channels:
dependencies:
- python=3.8
# required
- - pandas=1.2
+ - pandas
- shapely
- fiona
- pyproj
@@ -23,12 +23,6 @@ dependencies:
- xyzservices
- scipy
- geopy
- # installed in tests.yaml, because not available on windows
- # - postgis
- SQLalchemy
- - psycopg2
- libspatialite
- - geoalchemy2
- pyarrow
- # doctest testing
- - pytest-doctestplus
diff --git a/ci/envs/37-latest-defaults.yaml b/ci/envs/38-latest-defaults.yaml
similarity index 96%
rename from ci/envs/37-latest-defaults.yaml
rename to ci/envs/38-latest-defaults.yaml
index 071d3eac43..a4c4ef7ef6 100644
--- a/ci/envs/37-latest-defaults.yaml
+++ b/ci/envs/38-latest-defaults.yaml
@@ -2,7 +2,7 @@ name: test
channels:
- defaults
dependencies:
- - python=3.7
+ - python=3.8
# required
- pandas
- shapely
diff --git a/ci/envs/37-minimal.yaml b/ci/envs/38-minimal.yaml
similarity index 96%
rename from ci/envs/37-minimal.yaml
rename to ci/envs/38-minimal.yaml
index 9df7b6df4e..b697c63ca7 100644
--- a/ci/envs/37-minimal.yaml
+++ b/ci/envs/38-minimal.yaml
@@ -3,7 +3,7 @@ channels:
- defaults
- conda-forge
dependencies:
- - python=3.7
+ - python=3.8
# required
- numpy=1.18
- pandas==1.0.5
diff --git a/ci/envs/37-pd11.yaml b/ci/envs/38-pd11-defaults.yaml
similarity index 96%
rename from ci/envs/37-pd11.yaml
rename to ci/envs/38-pd11-defaults.yaml
index a58c7ec556..eb524c2bdf 100644
--- a/ci/envs/37-pd11.yaml
+++ b/ci/envs/38-pd11-defaults.yaml
@@ -2,7 +2,7 @@ name: test
channels:
- defaults
dependencies:
- - python=3.7
+ - python=3.8
# required
- pandas=1.1
- shapely
diff --git a/ci/envs/38-no-optional-deps.yaml b/ci/envs/39-no-optional-deps.yaml
similarity index 92%
rename from ci/envs/38-no-optional-deps.yaml
rename to ci/envs/39-no-optional-deps.yaml
index 7261cc6f60..cb6f036a57 100644
--- a/ci/envs/38-no-optional-deps.yaml
+++ b/ci/envs/39-no-optional-deps.yaml
@@ -2,7 +2,7 @@ name: test
channels:
- conda-forge
dependencies:
- - python=3.8
+ - python=3.9
# required
- pandas
- shapely
diff --git a/ci/envs/37-latest-conda-forge.yaml b/ci/envs/39-pd12-conda-forge.yaml
similarity index 65%
rename from ci/envs/37-latest-conda-forge.yaml
rename to ci/envs/39-pd12-conda-forge.yaml
index dadd2c4038..fc675bf98d 100644
--- a/ci/envs/37-latest-conda-forge.yaml
+++ b/ci/envs/39-pd12-conda-forge.yaml
@@ -2,9 +2,9 @@ name: test
channels:
- conda-forge
dependencies:
- - python=3.7
+ - python=3.9
# required
- - pandas
+ - pandas=1.2
- shapely
- fiona
- pyproj
@@ -23,6 +23,12 @@ dependencies:
- xyzservices
- scipy
- geopy
+ # installed in tests.yaml, because not available on windows
+ # - postgis
- SQLalchemy
+ - psycopg2
- libspatialite
+ - geoalchemy2
- pyarrow
+ # doctest testing
+ - pytest-doctestplus
diff --git a/doc/source/community/contributing.rst b/doc/source/community/contributing.rst
index 21444db81e..1eb9520e34 100644
--- a/doc/source/community/contributing.rst
+++ b/doc/source/community/contributing.rst
@@ -44,7 +44,7 @@ In particular, when submitting a pull request:
imports when possible, and explicit relative imports for local
imports when necessary in tests.
-- GeoPandas supports Python 3.7+ only. The last version of GeoPandas
+- GeoPandas supports Python 3.8+ only. The last version of GeoPandas
supporting Python 2 is 0.6.
diff --git a/setup.py b/setup.py
index ca1d0ec129..277d6847c3 100644
--- a/setup.py
+++ b/setup.py
@@ -71,7 +71,7 @@
"geopandas.tools.tests",
],
package_data={"geopandas": data_files},
- python_requires=">=3.7",
+ python_requires=">=3.8",
install_requires=INSTALL_REQUIRES,
cmdclass=versioneer.get_cmdclass(),
)
|
ibis-project__ibis-7498 | bug: sqlite BLOB datatype not handled
### What happened?
I'm converting some old databases that had binary output as columns, and I am unable to work with these tables in ibis. I created this failing test to show the problem:
```
from __future__ import annotations
import sqlite3
import pandas as pd
import pytest
from packaging.version import parse as vparse
import ibis
import ibis.expr.datatypes as dt
@pytest.fixture(scope="session")
def db(tmp_path_factory):
path = str(tmp_path_factory.mktemp("databases") / "formats.db")
con = sqlite3.connect(path)
con.execute('CREATE TABLE blobs (data BLOB)')
blob_data = b'\x00\x01\x02\x03'
con.execute('INSERT INTO blobs (data) VALUES (?)', (blob_data,))
con.close()
return path
def test_insert_blob(db):
conn = ibis.sqlite.connect(db)
t = conn.table("blobs")
assert(t["data"].type() == dt.blob)
```
Fails with:
E TypeError: Unable to convert type: BLOB()
### What version of ibis are you using?
master branch
### What backend(s) are you using, if any?
.sqlite
### Relevant log output
```sh
db = '/private/var/folders/0b/z9kzmm317mb6r9nyt5q1889r0000gn/T/****/pytest-13/databases0/formats.db'
def test_insert_blob(db):
conn = ibis.sqlite.connect(db)
> t = conn.table("blobs")
ibis/backends/sqlite/tests/test_blob_types.py:24:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
ibis/backends/base/sql/alchemy/__init__.py:629: in table
schema = self._schema_from_sqla_table(
ibis/backends/base/sql/alchemy/__init__.py:555: in _schema_from_sqla_table
dtype = cls.compiler.translator_class.get_ibis_type(
ibis/backends/base/sql/alchemy/translator.py:81: in get_ibis_type
return cls.type_mapper.to_ibis(sqla_type, nullable=nullable)
ibis/backends/sqlite/datatypes.py:32: in to_ibis
return super().to_ibis(typ, nullable=nullable)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
cls = <class 'ibis.backends.sqlite.datatypes.SqliteType'>, typ = BLOB(), nullable = True
@classmethod
def to_ibis(cls, typ: sat.TypeEngine, nullable: bool = True) -> dt.DataType:
"""Convert a SQLAlchemy type to an Ibis type.
Parameters
----------
typ
SQLAlchemy type to convert.
nullable : bool, optional
Whether the returned type should be nullable.
Returns
-------
Ibis type.
"""
if dtype := _from_sqlalchemy_types.get(type(typ)):
return dtype(nullable=nullable)
elif isinstance(typ, sat.Float):
if (float_typ := _FLOAT_PREC_TO_TYPE.get(typ.precision)) is not None:
return float_typ(nullable=nullable)
return dt.Decimal(typ.precision, typ.scale, nullable=nullable)
elif isinstance(typ, sat.Numeric):
return dt.Decimal(typ.precision, typ.scale, nullable=nullable)
elif isinstance(typ, ArrayType):
return dt.Array(cls.to_ibis(typ.value_type), nullable=nullable)
elif isinstance(typ, sat.ARRAY):
ndim = typ.dimensions
if ndim is not None and ndim != 1:
raise NotImplementedError("Nested array types not yet supported")
return dt.Array(cls.to_ibis(typ.item_type), nullable=nullable)
elif isinstance(typ, StructType):
fields = {k: cls.to_ibis(v) for k, v in typ.fields.items()}
return dt.Struct(fields, nullable=nullable)
elif isinstance(typ, MapType):
return dt.Map(
cls.to_ibis(typ.key_type),
cls.to_ibis(typ.value_type),
nullable=nullable,
)
elif isinstance(typ, sa.DateTime):
timezone = "UTC" if typ.timezone else None
return dt.Timestamp(timezone, nullable=nullable)
elif isinstance(typ, sat.String):
return dt.String(nullable=nullable)
elif geospatial_supported and isinstance(typ, ga.types._GISType):
name = typ.geometry_type.upper()
try:
return _GEOSPATIAL_TYPES[name](geotype=typ.name, nullable=nullable)
except KeyError:
raise ValueError(f"Unrecognized geometry type: {name}")
else:
> raise TypeError(f"Unable to convert type: {typ!r}")
E TypeError: Unable to convert type: BLOB()
ibis/backends/base/sql/alchemy/datatypes.py:323: TypeError
```
### Code of Conduct
- [X] I agree to follow this project's Code of Conduct
| [
{
"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport sqlalchemy as sa\nimport sqlalchemy.types as sat\nimport toolz\nfrom sqlalchemy.ext.compiler import compiles\n\nimport ibis.expr.datatypes as dt\nfrom ibis.backends.base.sql.alchemy.geospatial import geospatial_suppor... | [
{
"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport sqlalchemy as sa\nimport sqlalchemy.types as sat\nimport toolz\nfrom sqlalchemy.ext.compiler import compiles\n\nimport ibis.expr.datatypes as dt\nfrom ibis.backends.base.sql.alchemy.geospatial import geospatial_suppor... | diff --git a/ibis/backends/base/sql/alchemy/datatypes.py b/ibis/backends/base/sql/alchemy/datatypes.py
index 84e16ca49dfc..214a80956259 100644
--- a/ibis/backends/base/sql/alchemy/datatypes.py
+++ b/ibis/backends/base/sql/alchemy/datatypes.py
@@ -142,6 +142,7 @@ class Unknown(sa.Text):
sat.BOOLEAN: dt.Boolean,
sat.Boolean: dt.Boolean,
sat.BINARY: dt.Binary,
+ sat.BLOB: dt.Binary,
sat.LargeBinary: dt.Binary,
sat.DATE: dt.Date,
sat.Date: dt.Date,
diff --git a/ibis/backends/sqlite/tests/test_types.py b/ibis/backends/sqlite/tests/test_types.py
index ab7813086e9f..8d2fbec6a834 100644
--- a/ibis/backends/sqlite/tests/test_types.py
+++ b/ibis/backends/sqlite/tests/test_types.py
@@ -39,6 +39,7 @@ def db(tmp_path_factory):
con.execute("CREATE TABLE timestamps (ts TIMESTAMP)")
con.execute("CREATE TABLE timestamps_tz (ts TIMESTAMP)")
con.execute("CREATE TABLE weird (str_col STRING, date_col ITSADATE)")
+ con.execute("CREATE TABLE blobs (data BLOB)")
with con:
con.executemany("INSERT INTO timestamps VALUES (?)", [(t,) for t in TIMESTAMPS])
con.executemany(
@@ -54,6 +55,7 @@ def db(tmp_path_factory):
("d", "2022-01-04"),
],
)
+ con.execute("INSERT INTO blobs (data) VALUES (?)", (b"\x00\x01\x02\x03",))
con.close()
return path
@@ -90,3 +92,9 @@ def test_type_map(db):
}
)
assert res.equals(sol)
+
+
+def test_read_blob(db):
+ con = ibis.sqlite.connect(db)
+ t = con.table("blobs")
+ assert t["data"].type() == dt.binary
|
elastic__apm-agent-python-1064 | Add support for Django 3.2
Django 3.2 is slated for a release in April. Running the test suite, a few problems came up:
- [ ] App label needs to be a valid Python identifier, ours is not (renaming it from `elasticapm.contrib.django` to `elasticapm` should suffice)
Several test failures:
- [ ] `test_broken_500_handler_with_middleware`
- [ ] `test_404_middleware`
- [ ] `test_response_error_id_middleware`
- [ ] `test_django_logging_request_kwarg`
- [ ] `test_django_logging_middleware`
- [ ] `test_capture_body_config_is_dynamic_for_transactions`
- [ ] `test_capture_headers_config_is_dynamic_for_transactions`
- [ ] `test_capture_headers`
- [ ] `test_transaction_name_from_route`
Most of these look similar in nature, I suspect an issue with middlewares. Nothing jumps out in the [release notes](https://docs.djangoproject.com/en/3.2/releases/3.2/), though.
| [
{
"content": "# BSD 3-Clause License\n#\n# Copyright (c) 2019, Elasticsearch BV\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain... | [
{
"content": "# BSD 3-Clause License\n#\n# Copyright (c) 2019, Elasticsearch BV\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain... | diff --git a/.ci/.jenkins_framework.yml b/.ci/.jenkins_framework.yml
index 95ba9afd9..db375c5bc 100644
--- a/.ci/.jenkins_framework.yml
+++ b/.ci/.jenkins_framework.yml
@@ -5,6 +5,7 @@ FRAMEWORK:
- django-1.11
- django-2.0
- django-3.1
+ - django-3.2
- flask-0.12
- flask-1.1
- opentracing-newest
diff --git a/.ci/.jenkins_framework_full.yml b/.ci/.jenkins_framework_full.yml
index 3f1f97a37..26dff1427 100644
--- a/.ci/.jenkins_framework_full.yml
+++ b/.ci/.jenkins_framework_full.yml
@@ -8,7 +8,8 @@ FRAMEWORK:
- django-2.2
- django-3.0
- django-3.1
-# - django-master
+ - django-3.2
+ # - django-master
- flask-0.10
- flask-0.11
- flask-0.12
diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc
index 94b466c34..d4f1977f4 100644
--- a/CHANGELOG.asciidoc
+++ b/CHANGELOG.asciidoc
@@ -50,6 +50,7 @@ endif::[]
* Fix transaction names for Starlette Mount routes {pull}1037[#1037]
* Fix for elastic excepthook arguments {pull}1050[#1050]
* Fix issue with remote configuration when resetting config values {pull}1068[#1068]
+* Use a label for the elasticapm Django app that is compatible with Django 3.2 validation {pull}1064[#1064]
[[release-notes-6.x]]
diff --git a/elasticapm/contrib/django/apps.py b/elasticapm/contrib/django/apps.py
index 24da893f7..1919b9f56 100644
--- a/elasticapm/contrib/django/apps.py
+++ b/elasticapm/contrib/django/apps.py
@@ -54,7 +54,7 @@
class ElasticAPMConfig(AppConfig):
name = "elasticapm.contrib.django"
- label = "elasticapm.contrib.django"
+ label = "elasticapm"
verbose_name = "ElasticAPM"
def __init__(self, *args, **kwargs):
diff --git a/tests/contrib/django/fixtures.py b/tests/contrib/django/fixtures.py
index ddf1e3070..538fda8b8 100644
--- a/tests/contrib/django/fixtures.py
+++ b/tests/contrib/django/fixtures.py
@@ -57,7 +57,7 @@ def django_elasticapm_client(request):
client_config.setdefault("service_name", "app")
client_config.setdefault("secret_token", "secret")
client_config.setdefault("span_frames_min_duration", -1)
- app = apps.get_app_config("elasticapm.contrib.django")
+ app = apps.get_app_config("elasticapm")
old_client = app.client
client = TempStoreClient(**client_config)
register_handlers(client)
@@ -83,7 +83,7 @@ def django_sending_elasticapm_client(request, validating_httpserver):
client_config.setdefault("secret_token", "secret")
client_config.setdefault("transport_class", "elasticapm.transport.http.Transport")
client_config.setdefault("span_frames_min_duration", -1)
- app = apps.get_app_config("elasticapm.contrib.django")
+ app = apps.get_app_config("elasticapm")
old_client = app.client
client = DjangoClient(**client_config)
register_handlers(client)
diff --git a/tests/contrib/django/testapp/urls.py b/tests/contrib/django/testapp/urls.py
index 1619ed608..8c7255029 100644
--- a/tests/contrib/django/testapp/urls.py
+++ b/tests/contrib/django/testapp/urls.py
@@ -32,11 +32,16 @@
import django
from django.conf import settings
-from django.conf.urls import url
from django.http import HttpResponse
from tests.contrib.django.testapp import views
+try:
+ from django.conf.urls import re_path
+except ImportError:
+ # Django < 2
+ from django.conf.urls import url as re_path
+
def handler500(request):
if getattr(settings, "BREAK_THAT_500", False):
@@ -45,27 +50,27 @@ def handler500(request):
urlpatterns = (
- url(r"^render-heavy-template$", views.render_template_view, name="render-heavy-template"),
- url(r"^render-user-template$", views.render_user_view, name="render-user-template"),
- url(r"^no-error$", views.no_error, name="elasticapm-no-error"),
- url(r"^no-error-slash/$", views.no_error, name="elasticapm-no-error-slash"),
- url(r"^http-error/(?P<status>[0-9]{3})$", views.http_error, name="elasticapm-http-error"),
- url(r"^logging$", views.logging_view, name="elasticapm-logging"),
- url(r"^ignored-exception/$", views.ignored_exception, name="elasticapm-ignored-exception"),
- url(r"^fake-login$", views.fake_login, name="elasticapm-fake-login"),
- url(r"^trigger-500$", views.raise_exc, name="elasticapm-raise-exc"),
- url(r"^trigger-500-ioerror$", views.raise_ioerror, name="elasticapm-raise-ioerror"),
- url(r"^trigger-500-decorated$", views.decorated_raise_exc, name="elasticapm-raise-exc-decor"),
- url(r"^trigger-500-django$", views.django_exc, name="elasticapm-django-exc"),
- url(r"^trigger-500-template$", views.template_exc, name="elasticapm-template-exc"),
- url(r"^trigger-500-log-request$", views.logging_request_exc, name="elasticapm-log-request-exc"),
- url(r"^streaming$", views.streaming_view, name="elasticapm-streaming-view"),
- url(r"^name-override$", views.override_transaction_name_view, name="elasticapm-name-override"),
+ re_path(r"^render-heavy-template$", views.render_template_view, name="render-heavy-template"),
+ re_path(r"^render-user-template$", views.render_user_view, name="render-user-template"),
+ re_path(r"^no-error$", views.no_error, name="elasticapm-no-error"),
+ re_path(r"^no-error-slash/$", views.no_error, name="elasticapm-no-error-slash"),
+ re_path(r"^http-error/(?P<status>[0-9]{3})$", views.http_error, name="elasticapm-http-error"),
+ re_path(r"^logging$", views.logging_view, name="elasticapm-logging"),
+ re_path(r"^ignored-exception/$", views.ignored_exception, name="elasticapm-ignored-exception"),
+ re_path(r"^fake-login$", views.fake_login, name="elasticapm-fake-login"),
+ re_path(r"^trigger-500$", views.raise_exc, name="elasticapm-raise-exc"),
+ re_path(r"^trigger-500-ioerror$", views.raise_ioerror, name="elasticapm-raise-ioerror"),
+ re_path(r"^trigger-500-decorated$", views.decorated_raise_exc, name="elasticapm-raise-exc-decor"),
+ re_path(r"^trigger-500-django$", views.django_exc, name="elasticapm-django-exc"),
+ re_path(r"^trigger-500-template$", views.template_exc, name="elasticapm-template-exc"),
+ re_path(r"^trigger-500-log-request$", views.logging_request_exc, name="elasticapm-log-request-exc"),
+ re_path(r"^streaming$", views.streaming_view, name="elasticapm-streaming-view"),
+ re_path(r"^name-override$", views.override_transaction_name_view, name="elasticapm-name-override"),
)
if django.VERSION >= (1, 8):
- urlpatterns += (url(r"^render-jinja2-template$", views.render_jinja2_template, name="render-jinja2-template"),)
+ urlpatterns += (re_path(r"^render-jinja2-template$", views.render_jinja2_template, name="render-jinja2-template"),)
if django.VERSION >= (2, 2):
from django.urls import path
diff --git a/tests/requirements/reqs-django-3.2.txt b/tests/requirements/reqs-django-3.2.txt
new file mode 100644
index 000000000..9414b669f
--- /dev/null
+++ b/tests/requirements/reqs-django-3.2.txt
@@ -0,0 +1,2 @@
+Django>=3.2b1,<3.3
+-r reqs-base.txt
|
elastic__apm-agent-python-1436 | [ci] tests.config.tests.test_config_all_upper_case failing
It appears that the `tests.config.tests.test_config_all_upper_case` test is failing [across a number of different platforms on the master branch](https://apm-ci.elastic.co/job/apm-agent-python/job/apm-agent-python-mbp/job/master/593/testReport/):
<img width="684" alt="Screen Shot 2021-12-16 at 9 04 34 AM" src="https://user-images.githubusercontent.com/111616/146331918-5ee9fa87-156b-42b1-8dc5-53ceea0d6df1.png">
| [
{
"content": "# BSD 3-Clause License\n#\n# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details\n# Copyright (c) 2019, Elasticsearch BV\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following c... | [
{
"content": "# BSD 3-Clause License\n#\n# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details\n# Copyright (c) 2019, Elasticsearch BV\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following c... | diff --git a/elasticapm/conf/__init__.py b/elasticapm/conf/__init__.py
index 65de90dca..660539b6e 100644
--- a/elasticapm/conf/__init__.py
+++ b/elasticapm/conf/__init__.py
@@ -594,7 +594,7 @@ class Config(_ConfigBase):
type=int,
)
exit_span_min_duration = _ConfigValue(
- "exit_span_min_duration",
+ "EXIT_SPAN_MIN_DURATION",
default=1,
validators=[duration_validator],
type=float,
|
conda__conda-build-570 | AppVeyor: AttributeError: 'module' object has no attribute 'get_pid_list
https://ci.appveyor.com/project/mpi4py/mpi4py/build/2.0.0a0-17/job/965h1pw9k7476768#L1187
conda info:
https://ci.appveyor.com/project/mpi4py/mpi4py/build/2.0.0a0-17/job/965h1pw9k7476768#L1076
Please note a few lines above I ran:
`C:\Anaconda\Scripts\conda.exe install --yes --quiet anaconda-client conda-build jinja2`
| [
{
"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport shutil\nfrom os.path import dirname, isdir, isfile, join, exists\n\nimport conda.config as cc\nfrom conda.compat import iteritems\n\nfrom conda_build.config import config\nfrom conda_build import envi... | [
{
"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport shutil\nfrom os.path import dirname, isdir, isfile, join, exists\n\nimport conda.config as cc\nfrom conda.compat import iteritems\n\nfrom conda_build.config import config\nfrom conda_build import envi... | diff --git a/conda_build/windows.py b/conda_build/windows.py
index 31621b82da..74592b709a 100644
--- a/conda_build/windows.py
+++ b/conda_build/windows.py
@@ -89,7 +89,7 @@ def msvc_env_cmd():
def kill_processes():
if psutil is None:
return
- for n in psutil.get_pid_list():
+ for n in psutil.pids():
try:
p = psutil.Process(n)
if p.name.lower() == 'msbuild.exe':
|
ibis-project__ibis-3630 | bug(duckdb): duckdb backend should add in CAST for some bind parameters
DuckDB casts bind parameters `?` to strings which leads to binder errors with some queries
If we have a small tpch dataset:
```python
import duckdb
con = duckdb.connect("tpch.ddb")
con.execute("CALL dbgen(sf=0.1)")
import ibis
con = ibis.duckdb.connect("tpch.ddb")
t = con.table('orders')
expr = t.aggregate(high_line_count=(t.o_orderpriority.case().when('1-URGENT', 1).else_(0).end().sum()
expr.execute()
```
raises
```
RuntimeError: Binder Error: No function matches the given name and argument types 'sum(VARCHAR)'. You might need to add explicit type casts.
Candidate functions:
sum(DECIMAL) -> DECIMAL
sum(SMALLINT) -> HUGEINT
sum(INTEGER) -> HUGEINT
sum(BIGINT) -> HUGEINT
sum(HUGEINT) -> HUGEINT
sum(DOUBLE) -> DOUBLE
LINE 1: SELECT sum(CASE WHEN (t0.o_orderpriority = ?) ...
```
because our generated SQL doesn't have explicit casts:
```
print(expr.compile())
SELECT sum(CASE WHEN (t0.o_orderpriority = ?) THEN ? ELSE ? END) AS high_line_count
FROM orders AS t0
```
we want to generate
```
SELECT sum(CASE WHEN (t0.o_orderpriority = ?) THEN cast(? as INTEGER) ELSE cast(? as INTEGER) END) AS high_line_count FROM orders as t0
```
| [
{
"content": "import collections\nimport operator\n\nimport numpy as np\nimport sqlalchemy as sa\n\nimport ibis.expr.datatypes as dt\nimport ibis.expr.operations as ops\nfrom ibis.backends.base.sql.alchemy import to_sqla_type, unary\n\nfrom ..base.sql.alchemy.registry import _geospatial_functions, _table_column... | [
{
"content": "import collections\nimport operator\n\nimport numpy as np\nimport sqlalchemy as sa\n\nimport ibis.expr.datatypes as dt\nimport ibis.expr.operations as ops\nfrom ibis.backends.base.sql.alchemy import to_sqla_type, unary\n\nfrom ..base.sql.alchemy.registry import _geospatial_functions, _table_column... | diff --git a/ibis/backends/duckdb/registry.py b/ibis/backends/duckdb/registry.py
index d6b5f4032785..a3cbbaf4edbb 100644
--- a/ibis/backends/duckdb/registry.py
+++ b/ibis/backends/duckdb/registry.py
@@ -99,7 +99,7 @@ def _literal(_, expr):
f"`{type(value).__name__}` isn't yet supported with the duckdb "
"backend"
)
- return sa.literal(value)
+ return sa.cast(sa.literal(value), sqla_type)
def _array_column(t, expr):
diff --git a/ibis/backends/tests/test_aggregation.py b/ibis/backends/tests/test_aggregation.py
index 36d9c7bff5d6..3b08455181f7 100644
--- a/ibis/backends/tests/test_aggregation.py
+++ b/ibis/backends/tests/test_aggregation.py
@@ -461,3 +461,14 @@ def collect_udf(v):
)
backend.assert_frame_equal(result, expected, check_like=True)
+
+
+@pytest.mark.notimpl(["datafusion", "pyspark"])
+def test_binds_are_cast(alltypes):
+ expr = alltypes.aggregate(
+ high_line_count=(
+ alltypes.string_col.case().when('1-URGENT', 1).else_(0).end().sum()
+ )
+ )
+
+ expr.execute()
diff --git a/ibis/backends/tests/test_generic.py b/ibis/backends/tests/test_generic.py
index 86f3e0aff62f..0c59dc884824 100644
--- a/ibis/backends/tests/test_generic.py
+++ b/ibis/backends/tests/test_generic.py
@@ -111,7 +111,7 @@ def test_coalesce(backend, con, expr, expected):
# False
assert result == decimal.Decimal(str(expected))
else:
- assert result == expected
+ assert result == pytest.approx(expected)
# TODO(dask) - identicalTo - #2553
diff --git a/ibis/backends/tests/test_temporal.py b/ibis/backends/tests/test_temporal.py
index 9e2a03f20e62..a49aaa48e4de 100644
--- a/ibis/backends/tests/test_temporal.py
+++ b/ibis/backends/tests/test_temporal.py
@@ -362,7 +362,7 @@ def convert_to_offset(x):
lambda t, be: t.timestamp_col.date() - ibis.date(date_value),
lambda t, be: t.timestamp_col.dt.floor('d') - date_value,
id='date-subtract-date',
- marks=pytest.mark.notimpl(["duckdb", 'pyspark']),
+ marks=pytest.mark.notimpl(["pyspark"]),
),
],
)
|
ansible__molecule-3446 | remnants of ansible-lint in molecule docs
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Do not report bugs before reproducing them with the code of the main branch! -->
<!--- Please also check https://molecule.readthedocs.io/en/latest/faq.html --->
<!--- Please use https://groups.google.com/forum/#!forum/molecule-users for usage questions -->
# Issue Type
- Bug report
# Molecule and Ansible details
Note: the python was installed via conda, but the python packages are installed using pip, not conda.
```
ansible [core 2.12.2]
python version = 3.9.10 | packaged by conda-forge | (main, Feb 1 2022, 21:25:34) [Clang 11.1.0 ]
jinja version = 3.0.3
libyaml = True
ansible python module location = /opt/homebrew/Caskroom/miniconda/base/envs/tmptest/lib/python3.9/site-packages/ansible
molecule 3.6.1 using python 3.9
ansible:2.12.2
delegated:3.6.1 from molecule
```
Molecule installation method (one of):
- pip
Ansible installation method (one of):
- pip
Detail any linters or test runners used:
ansible-lint
# Desired Behavior
Assuming ansible-lint was removed for good reason and shouldn't be added back into the `molecule[lint]` extra:
I think this would make clearer ansible-lint is never installed by molecule:
* add note here that ansible-lint is not installed by molecule, even if you installed the `[lint]` extra
https://molecule.readthedocs.io/en/latest/configuration.html?highlight=ansible-lint#lint
* remove misleading comment in setup.cfg https://github.com/ansible-community/molecule/blob/c33c205b570cd95d599d16afa8772fabba51dd40/setup.cfg#L112
* change to actual default (yamllint) https://github.com/ansible-community/molecule/blob/c7ae6a27bed9ba6423d6dfe11d8e0d5c54da094f/src/molecule/command/init/scenario.py#L165
# Actual Behaviour
I can't say for sure (don't know project history well enough) but I *think* ansible-lint was once available through the `molecule[lint]` extra, but was subsequently promoted to a regular dependency, and eventually removed from molecule deps altogether. It appears there were a few spots in docs that got missed and may mislead a new user (see: me) into thinking ansible-lint will be installed with `pip install molecule[lint]` when in fact it is not.
| [
{
"content": "# Copyright (c) 2015-2018 Cisco Systems, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# right... | [
{
"content": "# Copyright (c) 2015-2018 Cisco Systems, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# right... | diff --git a/docs/configuration.rst b/docs/configuration.rst
index dfa22f6c87..511a3e8344 100644
--- a/docs/configuration.rst
+++ b/docs/configuration.rst
@@ -14,7 +14,8 @@ In order to help Ansible find used modules and roles, molecule will perform
a prerun set of actions. These involve installing dependencies from
``requirements.yml`` specified at project level, install a standalone role
or a collection. The destination is ``project_dir/.cache`` and the code itself
-is reused from ansible-lint, which has to do the same actions.
+was reused from ansible-lint, which has to do the same actions.
+(Note: ansible-lint is not included with molecule.)
This assures that when you include a role inside molecule playbooks, Ansible
will be able to find that role, and that the include is exactly the same as
@@ -138,6 +139,9 @@ Molecule was able to use up to three linters and while it was aimed to flexible
about them, it ended up creating more confusions to the users. We decided to
maximize flexibility by just calling an external shell command.
+Note: ansible-lint is not included with molecule. The ``molecule[lint]`` extra
+does not install ansible-lint.
+
.. code-block:: yaml
lint: |
diff --git a/docs/getting-started.rst b/docs/getting-started.rst
index 63e77ff901..77e97f7187 100644
--- a/docs/getting-started.rst
+++ b/docs/getting-started.rst
@@ -122,7 +122,8 @@ keys represent the high level components that Molecule provides. These are:
the driver to delegate the task of creating instances.
* The :ref:`lint` command. Molecule can call external commands to ensure
- that best practices are encouraged.
+ that best practices are encouraged. Note: `ansible-lint` is not included with
+ molecule or molecule[lint].
* The :ref:`platforms` definitions. Molecule relies on this to know which
instances to create, name and to which group each instance belongs. If you
diff --git a/docs/installation.rst b/docs/installation.rst
index 1d88ef9e1a..6d24642c9c 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -94,7 +94,14 @@ Install Molecule:
.. code-block:: bash
- $ python3 -m pip install --user "molecule[lint]"
+ $ python3 -m pip install --user "molecule"
+
+Molecule does not include ansible-lint (nor does the lint extra), but
+is easily installed separately:
+
+.. code-block:: bash
+
+ $ python3 -m pip install --user "molecule ansible-lint"
Molecule uses the "delegated" driver by default. Other drivers can
be installed separately from PyPI, such as the molecule-docker driver.
@@ -103,7 +110,7 @@ command would look like this:
.. code-block:: bash
- $ python3 -m pip install --user "molecule[docker,lint]"
+ $ python3 -m pip install --user "molecule[docker]"
Other drivers, such as ``molecule-podman``, ``molecule-vagrant``,
``molecule-azure`` or ``molecule-hetzner`` are also available.
diff --git a/setup.cfg b/setup.cfg
index e278acf093..1020174040 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -105,7 +105,6 @@ test =
pytest-xdist >= 2.1.0
pytest >= 6.1.2
lint =
- # ansible-lint is now a core dependency, duplicating it here would confuse pip
flake8 >= 3.8.4
pre-commit >= 2.10.1
yamllint
diff --git a/src/molecule/command/init/scenario.py b/src/molecule/command/init/scenario.py
index cc8cba6d6f..32a1d0d79b 100644
--- a/src/molecule/command/init/scenario.py
+++ b/src/molecule/command/init/scenario.py
@@ -162,7 +162,7 @@ def _default_scenario_exists(ctx, param, value: str): # pragma: no cover
"--lint-name",
type=click.Choice(["yamllint"]),
default="yamllint",
- help="Name of lint to initialize. (ansible-lint)",
+ help="Name of lint to initialize. (yamllint)",
)
@click.option(
"--provisioner-name",
|
scipy__scipy-9996 | lsq_linear hangs/infinite loop with 'trf' method
<!--
Thank you for taking the time to report a SciPy issue.
Please describe the issue in detail, and for bug reports
fill in the fields below. You can delete the sections that
don't apply to your issue. You can view the final output
by clicking the preview button above.
-->
I have found several cases where scipy.optimize.lsq_linear with non-negative bounds (i.e. (0, numpy.Inf)) hangs, seemingly stuck in an infinite loop in some C code (LAPACK?) that can't be terminated via ctrl+c. It ran for at least two days the first time I noticed it. The non-default 'bvls' method and scipy.optimize.nnls() both work on the same data, one example of which I have attached:
[x.txt](https://github.com/scipy/scipy/files/3010094/x.txt)
[y.txt](https://github.com/scipy/scipy/files/3010095/y.txt)
### Reproducing code example:
<!--
If you place your code between the triple backticks below,
it will be marked as a code block automatically
-->
```
import numpy as np; import scipy.optimize as spopt
x = np.loadtxt('x.txt')
y = np.loadtxt('y.txt')
print(spopt.nnls(x,y))
print(spopt.lsq_linear(x, y, bounds=(0, np.Inf), method='bvls'))
print(spopt.lsq_linear(x, y, bounds=(0, np.Inf), method='trf', verbose=2))
```
### Output:
<!-- If any, paste the *full* error message inside a code block
as above (starting from line Traceback)
-->
```
In [1]: import numpy as np; import scipy.optimize as spopt
...: x = np.loadtxt('x.txt')
...: y = np.loadtxt('y.txt')
...: print(spopt.nnls(x,y))
...: print(spopt.lsq_linear(x, y, bounds=(0, np.Inf), method='bvls'))
...: print(spopt.lsq_linear(x, y, bounds=(0, np.Inf), method='trf', verbose=2))
...:
(array([ 2.09932938, 0. , 0. , 14.74758632]), 1.1295995521670104)
active_mask: array([ 0., -1., -1., 0.])
cost: 0.6379975741279486
fun: array([-0.003566 , -0.00431135, -0.00317054, ..., 0.00151165,
0.00256816, 0.00488628])
message: 'The first-order optimality measure is less than `tol`.'
nit: 3
optimality: 4.209012793594848e-15
status: 1
success: True
x: array([ 2.09932938, 0. , 0. , 14.74758632])
Iteration Cost Cost reduction Step norm Optimality
0 5.9926e+01 6.86e+01
1 9.5818e+00 5.03e+01 2.39e+00 1.62e+01
2 1.5210e+00 8.06e+00 1.07e+00 3.26e+00
3 8.3612e-01 6.85e-01 3.31e-01 3.94e-01
4 7.9232e-01 4.38e-02 6.33e-01 7.22e-02
5 6.9727e-01 9.51e-02 9.96e+00 4.75e-02
6 6.9645e-01 8.16e-04 1.43e-02 7.09e-02
/software/lsstsw/stack_20181012/python/miniconda3-4.5.4/envs/lsst-scipipe/lib/python3.6/site-packages/scipy/optimize/_lsq/common.py:321: RuntimeWarning: invalid value encountered in add
y = a * t**2 + b * t + c
/software/lsstsw/stack_20181012/python/miniconda3-4.5.4/envs/lsst-scipipe/lib/python3.6/site-packages/scipy/optimize/_lsq/common.py:362: RuntimeWarning: invalid value encountered in double_scalars
return 0.5 * q + l
7 inf nan inf inf
```
### Scipy/Numpy/Python version information:
<!-- You can simply run the following and paste the result in a code block
-->
```
1.1.0 1.14.5 sys.version_info(major=3, minor=6, micro=6, releaselevel='final', serial=0)
```
I have also reproduced this on a different machine with 1.0.0 and 1.2.1.
| [
{
"content": "\"\"\"Functions used by least-squares algorithms.\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nfrom math import copysign\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nfrom scipy.linalg import cho_factor, cho_solve, LinAlgError\nfrom scipy.sparse import isspa... | [
{
"content": "\"\"\"Functions used by least-squares algorithms.\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nfrom math import copysign\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nfrom scipy.linalg import cho_factor, cho_solve, LinAlgError\nfrom scipy.sparse import isspa... | diff --git a/scipy/optimize/_lsq/common.py b/scipy/optimize/_lsq/common.py
index 65444646ef4e..3bde207034a0 100644
--- a/scipy/optimize/_lsq/common.py
+++ b/scipy/optimize/_lsq/common.py
@@ -319,7 +319,7 @@ def minimize_quadratic_1d(a, b, lb, ub, c=0):
if lb < extremum < ub:
t.append(extremum)
t = np.asarray(t)
- y = a * t**2 + b * t + c
+ y = t * (a * t + b) + c
min_index = np.argmin(y)
return t[min_index], y[min_index]
diff --git a/scipy/optimize/tests/test_lsq_common.py b/scipy/optimize/tests/test_lsq_common.py
index bda69c9ec99a..35ee2f96d05b 100644
--- a/scipy/optimize/tests/test_lsq_common.py
+++ b/scipy/optimize/tests/test_lsq_common.py
@@ -156,20 +156,45 @@ def test_minimize_quadratic_1d(self):
t, y = minimize_quadratic_1d(a, b, 1, 2)
assert_equal(t, 1)
- assert_equal(y, a * t**2 + b * t)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
t, y = minimize_quadratic_1d(a, b, -2, -1)
assert_equal(t, -1)
- assert_equal(y, a * t**2 + b * t)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
t, y = minimize_quadratic_1d(a, b, -1, 1)
assert_equal(t, 0.1)
- assert_equal(y, a * t**2 + b * t)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
c = 10
t, y = minimize_quadratic_1d(a, b, -1, 1, c=c)
assert_equal(t, 0.1)
- assert_equal(y, a * t**2 + b * t + c)
+ assert_allclose(y, a * t**2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0, c=c)
+ assert_equal(t, 0)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ a = -1
+ b = 0.2
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf)
+ assert_equal(t, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0)
+ assert_equal(t, -np.inf)
+ assert_equal(y, -np.inf)
def test_evaluate_quadratic(self):
s = np.array([1.0, -1.0])
|
iterative__dvc-562 | dvc repro --force does not work
It looks like the flag was just ignored.
| [
{
"content": "import os\nimport stat\nimport networkx as nx\n\nimport dvc.cloud.base as cloud\n\nfrom dvc.logger import Logger\nfrom dvc.exceptions import DvcException\nfrom dvc.stage import Stage, Output\nfrom dvc.config import Config\nfrom dvc.state import State\nfrom dvc.lock import Lock\nfrom dvc.scm import... | [
{
"content": "import os\nimport stat\nimport networkx as nx\n\nimport dvc.cloud.base as cloud\n\nfrom dvc.logger import Logger\nfrom dvc.exceptions import DvcException\nfrom dvc.stage import Stage, Output\nfrom dvc.config import Config\nfrom dvc.state import State\nfrom dvc.lock import Lock\nfrom dvc.scm import... | diff --git a/.appveyor.yml b/.appveyor.yml
index ec4f0c6e3e..c00ffffaed 100644
--- a/.appveyor.yml
+++ b/.appveyor.yml
@@ -41,14 +41,11 @@ environment:
# PYTHON_ARCH: "64"
install:
- - cinst graphviz
- cinst wget
- cinst awscli
- cinst gsutil
- cinst openssl.light
- - wget --no-check-certificate https://github.com/dpinney/omf/raw/master/omf/static/pygraphviz-1.3.1-cp27-none-win32.whl
- - pip install --upgrade pip setuptools
- - pip install pygraphviz-1.3.1-cp27-none-win32.whl
+ - pip install --user --upgrade pip
- pip install -r requirements.txt
- python setup.py install
diff --git a/dvc/project.py b/dvc/project.py
index 7e48eda13b..0a9e3e1a4c 100644
--- a/dvc/project.py
+++ b/dvc/project.py
@@ -125,7 +125,7 @@ def run(self,
return stage
def _reproduce_stage(self, stages, node, force):
- if not stages[node].changed():
+ if not stages[node].changed() and not force:
return []
stages[node].reproduce(force=force)
diff --git a/tests/test_repro.py b/tests/test_repro.py
index fc995a67d4..afd58ddd58 100644
--- a/tests/test_repro.py
+++ b/tests/test_repro.py
@@ -25,6 +25,12 @@ def setUp(self):
cmd='python {} {} {}'.format(self.CODE, self.FOO, self.file1))
+class TestReproForce(TestRepro):
+ def test(self):
+ stages = self.dvc.reproduce(self.file1_stage, force=True)
+ self.assertEqual(len(stages), 2)
+
+
class TestReproChangedCode(TestRepro):
def test(self):
self.swap_code()
|
pypa__pip-10583 | `vendoring` is broken, due to a cyclic dependency during license fetching
Well, the lack of maintainance of the license fetching logic in `vendoring` has come to bite us. :)
`flit` recently established a cyclic dependency, by depending on `tomli`: see https://github.com/takluyver/flit/issues/451 and https://flit.readthedocs.io/en/latest/bootstrap.html.
We get licenses from sdists in `vendoring` (which means building metadata / wheels -- leading to https://github.com/pradyunsg/vendoring/issues/1). Since flit is no longer bootstrappable through regular mechanisms, it'd be best to switch to using wheels for the license fetch phase.
This is the tracking issue for actually fixing this, and adopting the fix in our workflow.
| [
{
"content": "\"\"\"Automation using nox.\n\"\"\"\n\nimport glob\nimport os\nimport shutil\nimport sys\nfrom pathlib import Path\nfrom typing import Iterator, List, Tuple\n\nimport nox\n\n# fmt: off\nsys.path.append(\".\")\nfrom tools import release # isort:skip # noqa\nsys.path.pop()\n# fmt: on\n\nnox.option... | [
{
"content": "\"\"\"Automation using nox.\n\"\"\"\n\nimport glob\nimport os\nimport shutil\nimport sys\nfrom pathlib import Path\nfrom typing import Iterator, List, Tuple\n\nimport nox\n\n# fmt: off\nsys.path.append(\".\")\nfrom tools import release # isort:skip # noqa\nsys.path.pop()\n# fmt: on\n\nnox.option... | diff --git a/noxfile.py b/noxfile.py
index df42af8b8f5..5b5a66d5307 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -171,7 +171,7 @@ def lint(session: nox.Session) -> None:
@nox.session
def vendoring(session: nox.Session) -> None:
- session.install("vendoring~=1.0.0")
+ session.install("vendoring~=1.2.0")
if "--upgrade" not in session.posargs:
session.run("vendoring", "sync", "-v")
diff --git a/pyproject.toml b/pyproject.toml
index fac27944798..9bb5900d0e5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -54,4 +54,6 @@ distro = []
setuptools = "pkg_resources"
[tool.vendoring.license.fallback-urls]
+CacheControl = "https://raw.githubusercontent.com/ionrock/cachecontrol/v0.12.6/LICENSE.txt"
+distlib = "https://bitbucket.org/pypa/distlib/raw/master/LICENSE.txt"
webencodings = "https://github.com/SimonSapin/python-webencodings/raw/master/LICENSE"
diff --git a/src/pip/_vendor/vendor.txt b/src/pip/_vendor/vendor.txt
index 0b74c2bacc2..1b5829a038a 100644
--- a/src/pip/_vendor/vendor.txt
+++ b/src/pip/_vendor/vendor.txt
@@ -1,4 +1,4 @@
-CacheControl==0.12.6
+CacheControl==0.12.6 # Make sure to update the license in pyproject.toml for this.
colorama==0.4.4
distlib==0.3.3
distro==1.6.0
diff --git a/tox.ini b/tox.ini
index 23738ad1ae5..9063c3ac340 100644
--- a/tox.ini
+++ b/tox.ini
@@ -70,10 +70,7 @@ basepython = python3
skip_install = True
commands_pre =
deps =
- vendoring~=1.0.0
- # Required, otherwise we interpret --no-binary :all: as
- # "do not build wheels", which fails for PEP 517 requirements
- pip>=19.3.1
+ vendoring~=1.2.0
whitelist_externals = git
commands =
# Check that the vendoring is up-to-date
|
iterative__dvc-4826 | Unexpected error on `dvc diff`
## Bug Report
When running `dvc diff staging`, I got a KeyError, here is the traceback:
```
Traceback (most recent call last):
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/main.py", line 76, in main
ret = cmd.run()
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/command/diff.py", line 130, in run
diff = self.repo.diff(self.args.a_rev, self.args.b_rev)
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/__init__.py", line 54, in wrapper
return f(repo, *args, **kwargs)
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/diff.py", line 43, in diff
missing = sorted(_filter_missing(self, deleted_or_missing))
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/diff.py", line 125, in _filter_missing
if out.status()[str(out)] == "not in cache":
KeyError: 'data/KPI/KPI_from_dvc/en/post_probs'
```
It only happens when I give a specific revision.
Any ideas? Could it be my data?
### Please provide information about your setup
**Output of `dvc version`:**
```console
$ dvc version
DVC version: 1.9.1 (pip)
---------------------------------
Platform: Python 3.7.3 on Linux-5.4.0-1029-aws-x86_64-with-debian-buster-sid
Supports: http, https, s3
Cache types: hardlink, symlink
Cache directory: ext4 on /dev/nvme0n1p1
Workspace directory: ext4 on /dev/nvme0n1p1
Repo: dvc, git
```
| [
{
"content": "import logging\nimport os\n\nfrom dvc.repo import locked\nfrom dvc.tree.local import LocalTree\nfrom dvc.tree.repo import RepoTree\n\nlogger = logging.getLogger(__name__)\n\n\n@locked\ndef diff(self, a_rev=\"HEAD\", b_rev=None):\n \"\"\"\n By default, it compares the workspace with the last ... | [
{
"content": "import logging\nimport os\n\nfrom dvc.repo import locked\nfrom dvc.tree.local import LocalTree\nfrom dvc.tree.repo import RepoTree\n\nlogger = logging.getLogger(__name__)\n\n\n@locked\ndef diff(self, a_rev=\"HEAD\", b_rev=None):\n \"\"\"\n By default, it compares the workspace with the last ... | diff --git a/dvc/repo/diff.py b/dvc/repo/diff.py
index cb5857a60b..ba7a4c44ca 100644
--- a/dvc/repo/diff.py
+++ b/dvc/repo/diff.py
@@ -122,5 +122,5 @@ def _filter_missing(repo, paths):
metadata = repo_tree.metadata(path)
if metadata.is_dvc:
out = metadata.outs[0]
- if out.status()[str(out)] == "not in cache":
+ if out.status().get(str(out)) == "not in cache":
yield path
|
python-poetry__poetry-3743 | Poetry install -q (and update -q) produce messages
<!-- Checked checkbox should look like this: [x] -->
- [x] I am on the [latest](https://github.com/python-poetry/poetry/releases/latest) Poetry version.
- [x] I have searched the [issues](https://github.com/python-poetry/poetry/issues) of this repo and believe that this is not a duplicate.
- [ ] If an exception occurs when executing a command, I executed it again in debug mode (`-vvv` option).
- **OS version and name**: Xubuntu 20.04
- **Poetry version**: 1.1.2
- **Link of a [Gist](https://gist.github.com/) with the contents of your pyproject.toml file**: https://gist.github.com/berislavlopac/949972163f24f734ea84c27fbb27b2f4
## Issue
Running `poetry update -q` and `poetry install -q` produces output, although somewhat more limited than normally.
```
~/D/test ❯❯❯ (test) poetry install
Updating dependencies
Resolving dependencies... (0.3s)
Writing lock file
Package operations: 6 installs, 0 updates, 0 removals
• Installing certifi (2020.6.20)
• Installing chardet (3.0.4)
• Installing idna (2.10)
• Installing urllib3 (1.25.10)
• Installing requests (2.24.0)
• Installing starlette (0.13.8)
```
```
~/D/test ❯❯❯ (test) poetry install -q
• Installing certifi (2020.6.20)
• Installing chardet (3.0.4)
• Installing idna (2.10)
• Installing urllib3 (1.25.10)
• Installing requests (2.24.0)
• Installing starlette (0.13.8)
```
Using multiple `q`s (`poetry install -qq`) has the same result as none at all.
I was expecting no messages at all, as was the case in earlier versions.
| [
{
"content": "# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport itertools\nimport os\nimport threading\n\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import wait\nfrom pathlib import Path\nfrom subprocess import CalledProcessError\nfrom typing import TYPE_CHECKING... | [
{
"content": "# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport itertools\nimport os\nimport threading\n\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import wait\nfrom pathlib import Path\nfrom subprocess import CalledProcessError\nfrom typing import TYPE_CHECKING... | diff --git a/poetry/installation/executor.py b/poetry/installation/executor.py
index 520487d2536..ea2940e1fbd 100644
--- a/poetry/installation/executor.py
+++ b/poetry/installation/executor.py
@@ -700,7 +700,4 @@ def _download_archive(self, operation: Union[Install, Update], link: Link) -> Pa
return archive
def _should_write_operation(self, operation: Operation) -> bool:
- if not operation.skipped:
- return True
-
- return self._dry_run or self._verbose
+ return not operation.skipped or self._dry_run or self._verbose
diff --git a/tests/installation/test_installer.py b/tests/installation/test_installer.py
index 32eb63149ea..738787c68d9 100644
--- a/tests/installation/test_installer.py
+++ b/tests/installation/test_installer.py
@@ -7,7 +7,11 @@
import pytest
+from cleo.io.inputs.input import Input
+from cleo.io.io import IO
from cleo.io.null_io import NullIO
+from cleo.io.outputs.buffered_output import BufferedOutput
+from cleo.io.outputs.output import Verbosity
from poetry.core.packages import ProjectPackage
from poetry.core.toml.file import TOMLFile
@@ -1889,3 +1893,28 @@ def test_installer_can_handle_old_lock_files(
# colorama will be added
assert 8 == installer.executor.installations_count
+
+
+@pytest.mark.parametrize("quiet", [True, False])
+def test_run_with_dependencies_quiet(installer, locker, repo, package, quiet):
+ package_a = get_package("A", "1.0")
+ package_b = get_package("B", "1.1")
+ repo.add_package(package_a)
+ repo.add_package(package_b)
+
+ installer._io = IO(Input(), BufferedOutput(), BufferedOutput())
+ installer._io.set_verbosity(Verbosity.QUIET if quiet else Verbosity.NORMAL)
+
+ package.add_dependency(Factory.create_dependency("A", "~1.0"))
+ package.add_dependency(Factory.create_dependency("B", "^1.0"))
+
+ installer.run()
+ expected = fixture("with-dependencies")
+
+ assert locker.written_data == expected
+
+ installer._io.output._buffer.seek(0)
+ if quiet:
+ assert installer._io.output._buffer.read() == ""
+ else:
+ assert installer._io.output._buffer.read() != ""
|
zigpy__zha-device-handlers-2902 | [Device Support Request] TS0601 _TZE204_yjjdcqsq temperature/humidity sensor
### Problem description
The TS0601 _TZE204_yjjdcqsq temperature/humidity sensor does not show any entities in current HA.
https://www.amazon.de/-/en/dp/B0BWJHHK89
There's an almost same id (_TZE200_yjjdcqsq, note 200 vs 204) in the repo. I've tried adding this one `TuyaTempHumiditySensorVar03` and `TuyaTempHumiditySensorVar04` (one at a time) and verified the quirk gets applied.
Doing so has not yielded useful data _except_ once for one sensor I got one temperature + humidity reading where the temperature seemed to be correct, but humidity pretty far off, and battery was "Unknown". I think that was for the Var03. I've tried with two sensors, the other has never shown anything but "Unknown" for temperature, humidity, and battery. And I haven't seen any new readings for the one that sent some values once either.
### Solution description
Sensor working out of the box.
### Screenshots/Video
<details><summary>Screenshots/Video</summary>
[Paste/upload your media here]
</details>
### Device signature
<details><summary>Device signature</summary>
```json
{
"node_descriptor": "NodeDescriptor(logical_type=<LogicalType.EndDevice: 2>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.AllocateAddress: 128>, manufacturer_code=4417, maximum_buffer_size=66, maximum_incoming_transfer_size=66, server_mask=10752, maximum_outgoing_transfer_size=66, descriptor_capability_field=<DescriptorCapability.NONE: 0>, *allocate_address=True, *is_alternate_pan_coordinator=False, *is_coordinator=False, *is_end_device=True, *is_full_function_device=False, *is_mains_powered=False, *is_receiver_on_when_idle=False, *is_router=False, *is_security_capable=False)",
"endpoints": {
"1": {
"profile_id": "0x0104",
"device_type": "0x0051",
"input_clusters": [
"0x0000",
"0x0004",
"0x0005",
"0xef00"
],
"output_clusters": [
"0x000a",
"0x0019"
]
}
},
"manufacturer": "_TZE204_yjjdcqsq",
"model": "TS0601",
"class": "zigpy.device.Device"
}
```
</details>
### Diagnostic information
<details><summary>Diagnostic information</summary>
```json
{
"home_assistant": {
"installation_type": "Home Assistant OS",
"version": "2024.1.2",
"dev": false,
"hassio": true,
"virtualenv": false,
"python_version": "3.11.6",
"docker": true,
"arch": "aarch64",
"timezone": "Europe/Helsinki",
"os_name": "Linux",
"os_version": "6.1.71-haos",
"supervisor": "2023.12.0",
"host_os": "Home Assistant OS 11.4",
"docker_version": "24.0.7",
"chassis": "embedded",
"run_as_root": true
},
"custom_components": {
"jatekukko": {
"version": "0.11.0",
"requirements": [
"pytekukko==0.14.0"
]
},
"ical": {
"version": "1.6.7",
"requirements": [
"icalendar==5.0.7"
]
},
"hacs": {
"version": "1.33.0",
"requirements": [
"aiogithubapi>=22.10.1"
]
},
"entsoe": {
"version": "0.0.1",
"requirements": [
"entsoe-py==0.5.8"
]
}
},
"integration_manifest": {
"domain": "zha",
"name": "Zigbee Home Automation",
"after_dependencies": [
"onboarding",
"usb"
],
"codeowners": [
"@dmulcahey",
"@adminiuga",
"@puddly",
"@TheJulianJES"
],
"config_flow": true,
"dependencies": [
"file_upload"
],
"documentation": "https://www.home-assistant.io/integrations/zha",
"iot_class": "local_polling",
"loggers": [
"aiosqlite",
"bellows",
"crccheck",
"pure_pcapy3",
"zhaquirks",
"zigpy",
"zigpy_deconz",
"zigpy_xbee",
"zigpy_zigate",
"zigpy_znp",
"universal_silabs_flasher"
],
"requirements": [
"bellows==0.37.6",
"pyserial==3.5",
"pyserial-asyncio==0.6",
"zha-quirks==0.0.109",
"zigpy-deconz==0.22.4",
"zigpy==0.60.4",
"zigpy-xbee==0.20.1",
"zigpy-zigate==0.12.0",
"zigpy-znp==0.12.1",
"universal-silabs-flasher==0.0.15",
"pyserial-asyncio-fast==0.11"
],
"usb": [
{
"vid": "10C4",
"pid": "EA60",
"description": "*2652*",
"known_devices": [
"slae.sh cc2652rb stick"
]
},
{
"vid": "1A86",
"pid": "55D4",
"description": "*sonoff*plus*",
"known_devices": [
"sonoff zigbee dongle plus v2"
]
},
{
"vid": "10C4",
"pid": "EA60",
"description": "*sonoff*plus*",
"known_devices": [
"sonoff zigbee dongle plus"
]
},
{
"vid": "10C4",
"pid": "EA60",
"description": "*tubeszb*",
"known_devices": [
"TubesZB Coordinator"
]
},
{
"vid": "1A86",
"pid": "7523",
"description": "*tubeszb*",
"known_devices": [
"TubesZB Coordinator"
]
},
{
"vid": "1A86",
"pid": "7523",
"description": "*zigstar*",
"known_devices": [
"ZigStar Coordinators"
]
},
{
"vid": "1CF1",
"pid": "0030",
"description": "*conbee*",
"known_devices": [
"Conbee II"
]
},
{
"vid": "0403",
"pid": "6015",
"description": "*conbee*",
"known_devices": [
"Conbee III"
]
},
{
"vid": "10C4",
"pid": "8A2A",
"description": "*zigbee*",
"known_devices": [
"Nortek HUSBZB-1"
]
},
{
"vid": "0403",
"pid": "6015",
"description": "*zigate*",
"known_devices": [
"ZiGate+"
]
},
{
"vid": "10C4",
"pid": "EA60",
"description": "*zigate*",
"known_devices": [
"ZiGate"
]
},
{
"vid": "10C4",
"pid": "8B34",
"description": "*bv 2010/10*",
"known_devices": [
"Bitron Video AV2010/10"
]
}
],
"zeroconf": [
{
"type": "_esphomelib._tcp.local.",
"name": "tube*"
},
{
"type": "_zigate-zigbee-gateway._tcp.local.",
"name": "*zigate*"
},
{
"type": "_zigstar_gw._tcp.local.",
"name": "*zigstar*"
},
{
"type": "_uzg-01._tcp.local.",
"name": "uzg-01*"
},
{
"type": "_slzb-06._tcp.local.",
"name": "slzb-06*"
}
],
"is_built_in": true
},
"data": {
"ieee": "**REDACTED**",
"nwk": 6268,
"manufacturer": "_TZE204_yjjdcqsq",
"model": "TS0601",
"name": "_TZE204_yjjdcqsq TS0601",
"quirk_applied": false,
"quirk_class": "zigpy.device.Device",
"quirk_id": null,
"manufacturer_code": 4417,
"power_source": "Battery or Unknown",
"lqi": 255,
"rssi": -72,
"last_seen": "2024-01-10T17:28:12",
"available": true,
"device_type": "EndDevice",
"signature": {
"node_descriptor": "NodeDescriptor(logical_type=<LogicalType.EndDevice: 2>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.AllocateAddress: 128>, manufacturer_code=4417, maximum_buffer_size=66, maximum_incoming_transfer_size=66, server_mask=10752, maximum_outgoing_transfer_size=66, descriptor_capability_field=<DescriptorCapability.NONE: 0>, *allocate_address=True, *is_alternate_pan_coordinator=False, *is_coordinator=False, *is_end_device=True, *is_full_function_device=False, *is_mains_powered=False, *is_receiver_on_when_idle=False, *is_router=False, *is_security_capable=False)",
"endpoints": {
"1": {
"profile_id": "0x0104",
"device_type": "0x0051",
"input_clusters": [
"0x0000",
"0x0004",
"0x0005",
"0xef00"
],
"output_clusters": [
"0x000a",
"0x0019"
]
}
},
"manufacturer": "_TZE204_yjjdcqsq",
"model": "TS0601"
},
"active_coordinator": false,
"entities": [],
"neighbors": [],
"routes": [],
"endpoint_names": [
{
"name": "SMART_PLUG"
}
],
"user_given_name": null,
"device_reg_id": "51b57764ccfc6310f784ac141ab39578",
"area_id": "a2e1df9ac6fb4acc817dd068c772d150",
"cluster_details": {
"1": {
"device_type": {
"name": "SMART_PLUG",
"id": 81
},
"profile_id": 260,
"in_clusters": {
"0x0004": {
"endpoint_attribute": "groups",
"attributes": {},
"unsupported_attributes": {}
},
"0x0005": {
"endpoint_attribute": "scenes",
"attributes": {},
"unsupported_attributes": {}
},
"0xef00": {
"endpoint_attribute": null,
"attributes": {},
"unsupported_attributes": {}
},
"0x0000": {
"endpoint_attribute": "basic",
"attributes": {
"0x0001": {
"attribute_name": "app_version",
"value": 73
},
"0x0004": {
"attribute_name": "manufacturer",
"value": "_TZE204_yjjdcqsq"
},
"0x0005": {
"attribute_name": "model",
"value": "TS0601"
}
},
"unsupported_attributes": {}
}
},
"out_clusters": {
"0x0019": {
"endpoint_attribute": "ota",
"attributes": {},
"unsupported_attributes": {}
},
"0x000a": {
"endpoint_attribute": "time",
"attributes": {},
"unsupported_attributes": {}
}
}
}
}
}
}
```
</details>
### Logs
<details><summary>Logs</summary>
```python
[Paste the logs here]
```
</details>
### Custom quirk
<details><summary>Custom quirk</summary>
```python
[Paste your custom quirk here]
```
</details>
### Additional information
zigbee-herdsman-converters adds it as an alias to the TZE200 one, https://github.com/Koenkk/zigbee-herdsman-converters/commit/95398b53a6af0526906c5f4d9ee50bbc9056d688
But as said I haven't got too promising results doing the equivalent in my tests.
| [
{
"content": "\"\"\"Tuya temp and humidity sensors.\"\"\"\n\nfrom typing import Any, Dict\n\nfrom zigpy.profiles import zha\nfrom zigpy.quirks import CustomDevice\nfrom zigpy.zcl.clusters.general import Basic, Groups, Ota, Scenes, Time\nfrom zigpy.zcl.clusters.measurement import (\n RelativeHumidity,\n So... | [
{
"content": "\"\"\"Tuya temp and humidity sensors.\"\"\"\n\nfrom typing import Any, Dict\n\nfrom zigpy.profiles import zha\nfrom zigpy.quirks import CustomDevice\nfrom zigpy.zcl.clusters.general import Basic, Groups, Ota, Scenes, Time\nfrom zigpy.zcl.clusters.measurement import (\n RelativeHumidity,\n So... | diff --git a/zhaquirks/tuya/ts0601_sensor.py b/zhaquirks/tuya/ts0601_sensor.py
index aaed2ba083..54bd978535 100644
--- a/zhaquirks/tuya/ts0601_sensor.py
+++ b/zhaquirks/tuya/ts0601_sensor.py
@@ -250,6 +250,7 @@ class TuyaTempHumiditySensorVar04(CustomDevice):
MODELS_INFO: [
("_TZE200_yjjdcqsq", "TS0601"),
("_TZE200_9yapgbuv", "TS0601"),
+ ("_TZE204_yjjdcqsq", "TS0601"),
],
ENDPOINTS: {
1: {
|
ckan__ckan-6125 | Remove remaining Python 2 code in core
This should be done in separate pull requests to make reviews easier
- [x] Remove `requirements.py2.*` files and update documentation to remove py2 mentions
- [x] Remove py2 specific code. Look for `if six.PY2:` and remove what's inside!
- [x] Remove py3 checks. Look for `six.PY3` and make that the standard code run (remove the check if any)
- [x] Remove usage of six. We should not need the compatibility layer any more. Make all code standard Python 3
This should definitely be done separately
- [ ] Remove unicode literals (eg `my_conf[u"test_key_1"] = u"Test value 1"` -> `my_conf["test_key_1"] = "Test value 1"`
| [
{
"content": "# encoding: utf-8\n\nimport os\nimport os.path\n\nfrom pkg_resources import parse_version\n\n# Avoid problem releasing to pypi from vagrant\nif os.environ.get('USER', '') == 'vagrant':\n del os.link\n\ntry:\n from setuptools import (setup, find_packages,\n __versio... | [
{
"content": "# encoding: utf-8\n\nimport os\nimport os.path\n\nfrom pkg_resources import parse_version\n\n# Avoid problem releasing to pypi from vagrant\nif os.environ.get('USER', '') == 'vagrant':\n del os.link\n\ntry:\n from setuptools import (setup, find_packages,\n __versio... | diff --git a/doc/maintaining/installing/install-from-package.rst b/doc/maintaining/installing/install-from-package.rst
index a7a66272646..0976f4f673c 100644
--- a/doc/maintaining/installing/install-from-package.rst
+++ b/doc/maintaining/installing/install-from-package.rst
@@ -56,16 +56,6 @@ CKAN:
sudo apt install -y libpq5 redis-server nginx supervisor
- .. note:: If you want to install CKAN 2.9 running on Python 2 for backwards compatibility, you need to also install the Python 2 libraries:
-
- .. parsed-literal::
-
- # On Ubuntu 18.04
- sudo apt install python2 libpython2.7
-
- # On Ubuntu 20.04
- sudo apt install libpython2.7
-
#. Download the CKAN package:
- On Ubuntu 18.04:
@@ -80,11 +70,6 @@ CKAN:
wget \https://packaging.ckan.org/|latest_package_name_focal_py3|
- - On Ubuntu 20.04, for Python 2:
-
- .. parsed-literal::
-
- wget \https://packaging.ckan.org/|latest_package_name_focal_py2|
#. Install the CKAN package:
@@ -100,12 +85,6 @@ CKAN:
sudo dpkg -i |latest_package_name_focal_py3|
- - On Ubuntu 20.04, for Python 2:
-
- .. parsed-literal::
-
- sudo dpkg -i |latest_package_name_focal_py2|
-
-----------------------------------
2. Install and configure PostgreSQL
diff --git a/doc/maintaining/installing/install-from-source.rst b/doc/maintaining/installing/install-from-source.rst
index 0c32e9f21d1..22ec3a21440 100644
--- a/doc/maintaining/installing/install-from-source.rst
+++ b/doc/maintaining/installing/install-from-source.rst
@@ -29,13 +29,6 @@ required packages with this command::
sudo apt-get install python3-dev postgresql libpq-dev python3-pip python3-venv git-core solr-tomcat openjdk-8-jdk redis-server
-.. note::
-
- For Python 2 (deprecated, but compatible with CKAN 2.9 and earlier), do
- this instead::
-
- sudo apt-get install python-dev postgresql libpq-dev python-pip python-virtualenv git-core solr-tomcat openjdk-8-jdk redis-server
-
If you're not using a Debian-based operating system, find the best way to
install the following packages on your operating system (see
our `How to Install CKAN <https://github.com/ckan/ckan/wiki/How-to-Install-CKAN>`_
@@ -44,7 +37,7 @@ wiki page for help):
===================== ===============================================
Package Description
===================== ===============================================
-Python `The Python programming language, v3.6 or newer (or v2.7) <https://www.python.org/getit/>`_
+Python `The Python programming language, v3.6 or newer <https://www.python.org/getit/>`_
|postgres| `The PostgreSQL database system, v9.5 or newer <https://www.postgresql.org/docs/9.5/libpq.html>`_
libpq `The C programmer's interface to PostgreSQL <http://www.postgresql.org/docs/8.1/static/libpq.html>`_
pip `A tool for installing and managing Python packages <https://pip.pypa.io/en/stable/>`_
@@ -105,14 +98,6 @@ a. Create a Python `virtual environment <https://virtualenv.pypa.io/en/latest/>`
|activate|
-.. note::
-
- For Python 2 then replace the `python3 -m venv` command with:
-
- .. parsed-literal::
-
- virtualenv --python=/usr/bin/python2.7 --no-site-packages |virtualenv|
- |activate|
b. Install the recommended ``setuptools`` version and up-to-date pip:
@@ -130,13 +115,6 @@ c. Install the CKAN source code into your virtualenv.
pip install -e 'git+\ |git_url|\@\ |current_release_tag|\#egg=ckan[requirements]'
- .. note::
-
- For Python 2 replace the last fragment with `requirements-py2`
-
- .. parsed-literal::
-
- pip install -e 'git+\ |git_url|\@\ |current_release_tag|\#egg=ckan[requirements-py2]'
If you're installing CKAN for development, you may want to install the
latest development version (the most recent commit on the master branch of
diff --git a/doc/maintaining/upgrading/upgrade-source.rst b/doc/maintaining/upgrading/upgrade-source.rst
index 502c0ad4372..5956ea892b3 100644
--- a/doc/maintaining/upgrading/upgrade-source.rst
+++ b/doc/maintaining/upgrading/upgrade-source.rst
@@ -45,9 +45,6 @@ CKAN release you're upgrading to:
pip install --upgrade -r requirements.txt
- .. note::
-
- For Python 2 replace `requirements.txt` with `requirements-py2.txt`
#. Register any new or updated plugins:
diff --git a/requirements-py2.in b/requirements-py2.in
deleted file mode 100644
index 0cfa898b29f..00000000000
--- a/requirements-py2.in
+++ /dev/null
@@ -1,45 +0,0 @@
-# The file contains the direct ckan requirements (python2).
-# Use pip-compile to create a requirements.txt file from this
-alembic==1.0.0
-Babel==2.7.0
-bleach==3.3.0
-click==7.1.2
-dominate==2.4.0
-feedgen==0.9.0
-Flask==1.1.1
-Flask-Babel==0.11.2
-flask-multistatic==1.0
-future==0.18.2
-Jinja2==2.11.3
-PyJWT==1.7.1
-Markdown==2.6.7
-passlib==1.7.3
-paste==1.7.5.1
-PasteScript==2.0.2
-polib==1.0.7
-psycopg2==2.8.2
-python-magic==0.4.15
-pysolr==3.6.0
-Pylons==0.9.7
-python-dateutil>=1.5.0
-python2-secrets==1.0.5
-pytz==2016.7
-PyUtilib==5.7.1
-pyyaml==5.3.1
-repoze.who-friendlyform==1.0.8
-repoze.who==2.3
-requests==2.24.0
-Routes==1.13
-rq==1.0
-simplejson==3.10.0
-sqlalchemy-migrate==0.12.0
-SQLAlchemy==1.3.5
-sqlparse==0.3.0
-tzlocal==1.3
-unicodecsv>=0.9
-webassets==0.12.1
-WebHelpers==1.3
-WebOb==1.0.8
-WebTest==1.4.3 # need to pin this so that Pylons does not install a newer version that conflicts with WebOb==1.0.8
-Werkzeug[watchdog]==0.16.1
-zope.interface==4.7.2
diff --git a/requirements-py2.txt b/requirements-py2.txt
deleted file mode 100644
index 9678b66b593..00000000000
--- a/requirements-py2.txt
+++ /dev/null
@@ -1,79 +0,0 @@
-#
-# This file is autogenerated by pip-compile
-# To update, run:
-#
-# pip-compile --output-file=requirements-py2.txt requirements-py2.in
-#
-alembic==1.0.0 # via -r requirements-py2.in
-babel==2.7.0 # via -r requirements-py2.in, flask-babel
-beaker==1.11.0 # via pylons
-bleach==3.3.0 # via -r requirements-py2.in
-certifi==2020.6.20 # via requests
-chardet==3.0.4 # via requests
-click==7.1.2 # via -r requirements-py2.in, flask, rq
-decorator==4.4.2 # via pylons, sqlalchemy-migrate
-dominate==2.4.0 # via -r requirements-py2.in
-feedgen==0.9.0 # via -r requirements-py2.in
-flask-babel==0.11.2 # via -r requirements-py2.in
-flask-multistatic==1.0 # via -r requirements-py2.in
-flask==1.1.1 # via -r requirements-py2.in, flask-babel, flask-multistatic
-formencode==2.0.0 # via pylons
-funcsigs==1.0.2 # via beaker
-future==0.18.2 # via -r requirements-py2.in
-idna==2.10 # via requests
-itsdangerous==1.1.0 # via flask
-jinja2==2.11.3 # via -r requirements-py2.in, flask, flask-babel
-lxml==4.6.2 # via feedgen
-mako==1.1.3 # via alembic, pylons
-markdown==2.6.7 # via -r requirements-py2.in
-markupsafe==1.1.1 # via jinja2, mako, webhelpers
-nose==1.3.7 # via pylons, pyutilib
-packaging==20.9 # via bleach
-passlib==1.7.3 # via -r requirements-py2.in
-paste==1.7.5.1 # via -r requirements-py2.in, pastescript, pylons, weberror
-pastedeploy==2.1.1 # via pastescript, pylons
-pastescript==2.0.2 # via -r requirements-py2.in, pylons
-pathtools==0.1.2 # via watchdog
-pbr==5.5.1 # via sqlalchemy-migrate
-polib==1.0.7 # via -r requirements-py2.in
-psycopg2==2.8.2 # via -r requirements-py2.in
-pygments==2.5.2 # via weberror
-pyjwt==1.7.1 # via -r requirements-py2.in
-pylons==0.9.7 # via -r requirements-py2.in
-pyparsing==2.4.7 # via packaging
-pysolr==3.6.0 # via -r requirements-py2.in
-python-dateutil==2.8.1 # via -r requirements-py2.in, alembic, feedgen
-python-editor==1.0.4 # via alembic
-python-magic==0.4.15 # via -r requirements-py2.in
-python2-secrets==1.0.5 # via -r requirements-py2.in
-pytz==2016.7 # via -r requirements-py2.in, babel, tzlocal
-pyutilib==5.7.1 # via -r requirements-py2.in
-pyyaml==5.3.1 # via -r requirements-py2.in
-redis==3.5.3 # via rq
-repoze.lru==0.7 # via routes
-repoze.who-friendlyform==1.0.8 # via -r requirements-py2.in
-repoze.who==2.3 # via -r requirements-py2.in, repoze.who-friendlyform
-requests==2.24.0 # via -r requirements-py2.in, pysolr
-routes==1.13 # via -r requirements-py2.in, pylons
-rq==1.0 # via -r requirements-py2.in
-simplejson==3.10.0 # via -r requirements-py2.in, pylons
-six==1.15.0 # via bleach, formencode, pastescript, python-dateutil, pyutilib, sqlalchemy-migrate
-sqlalchemy-migrate==0.12.0 # via -r requirements-py2.in
-sqlalchemy==1.3.5 # via -r requirements-py2.in, alembic, sqlalchemy-migrate
-sqlparse==0.3.0 # via -r requirements-py2.in, sqlalchemy-migrate
-tempita==0.5.2 # via pylons, sqlalchemy-migrate, weberror
-tzlocal==1.3 # via -r requirements-py2.in
-unicodecsv==0.14.1 # via -r requirements-py2.in
-urllib3==1.25.11 # via requests
-watchdog==0.10.3 # via werkzeug
-webassets==0.12.1 # via -r requirements-py2.in
-webencodings==0.5.1 # via bleach
-weberror==0.13.1 # via pylons
-webhelpers==1.3 # via -r requirements-py2.in, pylons
-webob==1.0.8 # via -r requirements-py2.in, pylons, repoze.who, repoze.who-friendlyform, weberror, webtest
-webtest==1.4.3 # via -r requirements-py2.in, pylons
-werkzeug[watchdog]==0.16.1 # via -r requirements-py2.in, flask
-zope.interface==4.7.2 # via -r requirements-py2.in, repoze.who, repoze.who-friendlyform
-
-# The following packages are considered to be unsafe in a requirements file:
-# setuptools
diff --git a/setup.py b/setup.py
index 6844c83727d..4a8be4e9d5c 100644
--- a/setup.py
+++ b/setup.py
@@ -191,7 +191,7 @@
extras_require = {}
_extras_groups = [
- ('requirements', 'requirements.txt'), ('requirements-py2', 'requirements-py2.txt'),
+ ('requirements', 'requirements.txt'),
('setuptools', 'requirement-setuptools.txt'), ('dev', 'dev-requirements.txt'),
]
|
cocotb__cocotb-999 | Profiling bug
When i enable the profiling i got the following traceback:
```make COCOTB_ENABLE_PROFILING=true
...
Traceback (most recent call last):
File "/home/ademski/Documents/satellogic/hdlteam/cocotb/cocotb/__init__.py", line 41, in <module>
from cocotb.scheduler import Scheduler
File "/home/ademski/Documents/satellogic/hdlteam/cocotb/cocotb/scheduler.py", line 51, in <module>
import cProfile, StringIO, pstats
ModuleNotFoundError: No module named 'StringIO
```
StringIO is not used in `scheduler.py`. I solved the problem removing that import.
Python version: 3.7.3
| [
{
"content": "#!/usr/bin/env python\n\n# Copyright (c) 2013, 2018 Potential Ventures Ltd\n# Copyright (c) 2013 SolarFlare Communications Inc\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are... | [
{
"content": "#!/usr/bin/env python\n\n# Copyright (c) 2013, 2018 Potential Ventures Ltd\n# Copyright (c) 2013 SolarFlare Communications Inc\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are... | diff --git a/cocotb/scheduler.py b/cocotb/scheduler.py
index d43c174018..de207cbec2 100755
--- a/cocotb/scheduler.py
+++ b/cocotb/scheduler.py
@@ -48,7 +48,7 @@
# Debug mode controlled by environment variables
if "COCOTB_ENABLE_PROFILING" in os.environ:
- import cProfile, StringIO, pstats
+ import cProfile, pstats
_profile = cProfile.Profile()
_profiling = True
else:
|
encode__starlette-1553 | Route naming introspection always return "method" for method endpoints
Discussion was done at https://gitter.im/encode/community. Bug was confirmed by @Kludex.
## Description
methods don't get detected on `is_function`, then we assume that `<object>.__class__.__name__ ` will give the right name (my_method on the example below) for it, but it actually gets the "method" name, which is wrong.
Unexpected behaviour seem to originate from: https://github.com/encode/starlette/blob/e086fc2da361767b532cf690e5203619bbae98aa/starlette/routing.py#L87
## Minimal example
```python
from starlette.responses import JSONResponse
from starlette.routing import Route
async def my_function(request):
return JSONResponse({'endpoint_type': 'function'})
class MyClass:
def __call__(self, request):
return JSONResponse({'endpoint_type': 'class'})
class MySpecialEndpointObject:
async def my_method(self, request):
return JSONResponse({'endpoint_type': 'method'})
endpoint_obj = MySpecialEndpointObject()
function_route = Route('/functionEndpoint', my_function)
class_route = Route('/classEndpoint', MyClass())
method_route = Route('/methodEndpoint', endpoint_obj.my_method)
assert function_route.name == "my_function"
assert class_route.name == "MyClass"
assert method_route.name == "my_method" # AssertionError
```
## Actual behavior
Value of `method_route.name` is `"method"`.
## Expected behavior
Value of `method_route.name` is `"my_method"`.
It could also be `"MySpecialEndpointObject_my_method"`. Reason here is to prevent ambiguity.
| [
{
"content": "import asyncio\nimport contextlib\nimport functools\nimport inspect\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport warnings\nfrom enum import Enum\n\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.convertors import CONVERTOR_TYPES, Convertor\nfro... | [
{
"content": "import asyncio\nimport contextlib\nimport functools\nimport inspect\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport warnings\nfrom enum import Enum\n\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.convertors import CONVERTOR_TYPES, Convertor\nfro... | diff --git a/starlette/routing.py b/starlette/routing.py
index 0388304c9..ea6ec2117 100644
--- a/starlette/routing.py
+++ b/starlette/routing.py
@@ -84,7 +84,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def get_name(endpoint: typing.Callable) -> str:
- if inspect.isfunction(endpoint) or inspect.isclass(endpoint):
+ if inspect.isroutine(endpoint) or inspect.isclass(endpoint):
return endpoint.__name__
return endpoint.__class__.__name__
diff --git a/tests/test_routing.py b/tests/test_routing.py
index 7077c5616..e8adaca48 100644
--- a/tests/test_routing.py
+++ b/tests/test_routing.py
@@ -1,4 +1,5 @@
import functools
+import typing
import uuid
import pytest
@@ -710,3 +711,38 @@ def test_duplicated_param_names():
match="Duplicated param names id, name at path /{id}/{name}/{id}/{name}",
):
Route("/{id}/{name}/{id}/{name}", user)
+
+
+class Endpoint:
+ async def my_method(self, request):
+ ... # pragma: no cover
+
+ @classmethod
+ async def my_classmethod(cls, request):
+ ... # pragma: no cover
+
+ @staticmethod
+ async def my_staticmethod(request):
+ ... # pragma: no cover
+
+ def __call__(self, request):
+ ... # pragma: no cover
+
+
+@pytest.mark.parametrize(
+ "endpoint, expected_name",
+ [
+ pytest.param(func_homepage, "func_homepage", id="function"),
+ pytest.param(Endpoint().my_method, "my_method", id="method"),
+ pytest.param(Endpoint.my_classmethod, "my_classmethod", id="classmethod"),
+ pytest.param(
+ Endpoint.my_staticmethod,
+ "my_staticmethod",
+ id="staticmethod",
+ ),
+ pytest.param(Endpoint(), "Endpoint", id="object"),
+ pytest.param(lambda request: ..., "<lambda>", id="lambda"),
+ ],
+)
+def test_route_name(endpoint: typing.Callable, expected_name: str):
+ assert Route(path="/", endpoint=endpoint).name == expected_name
|
pydantic__pydantic-3473 | pydantic.utils.to_camel() is actually to_pascal()
### Checks
* [ y ] I added a descriptive title to this issue
* [ y ] I have searched (google, github) for similar issues and couldn't find anything
* [ y ] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug
# Bug
Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
pydantic version: 1.8.1
pydantic compiled: True
install path: /home/schlerp/projects/pelt-studio/venv/lib/python3.8/site-packages/pydantic
python version: 3.8.5 (default, Sep 4 2020, 07:30:14) [GCC 7.3.0]
platform: Linux-5.15.2-zen1-1-zen-x86_64-with-glibc2.10
optional deps. installed: ['typing-extensions']
```
Camel case and pascal case are similar however, they differ by the capitalisation of the first letter. The current implementation of camel_case in pydantic us actually pascal case and not camel case at all. I suggest renaming this and also implementing a camel case. See below for code expressing the issue and suggested fix.
**Pascal Case** (aka init case or upper camel case)
All spaces/underscores removed and the start of every word is capitalised.
**Camel Case** (aka lower camel case)
All spaces and underscores removed and the start of every word, is capitalised, except the first word which is always lower case.
Issue:
```py
from pydantic.utils import to_camel
valid_pascal = "PascalCase"
valid_camel = "camelCase"
example = to_camel("i_shouldnt_be_capitalised")
assert valid_pascal == to_camel("pascal_case")
assert valid_camel != to_camel("camel_case")
```
suggested fix, rename `to_camel()` -> `to_pascal()`, and write new `to_camel()` function:
```py
def to_pascal(string: str) -> str:
return "".join(word.capitalize() for word in string.split("_"))
def to_camel(string: str) -> str:
if len(string) >= 1:
pascal_string = to_pascal(string)
return pascal_string[0].lower() + pascal_string[1:]
return string.lower()
```
Alternatively, if there is code which will break because it is dependent on the `camel_case()` function remaining pascal case, then i propose we implement a new function called `to_lower_camel()` which implements the first letter lower case variant:
```py
def to_camel(string: str) -> str:
return "".join(word.capitalize() for word in string.split("_"))
def to_lower_camel(string: str) -> str:
if len(string) >= 1:
pascal_string = to_camel(string)
return pascal_string[0].lower() + pascal_string[1:]
return string.lower()
```
| [
{
"content": "import warnings\nimport weakref\nfrom collections import OrderedDict, defaultdict, deque\nfrom copy import deepcopy\nfrom itertools import islice, zip_longest\nfrom types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType\nfrom typing import (\n TYPE_CHECK... | [
{
"content": "import warnings\nimport weakref\nfrom collections import OrderedDict, defaultdict, deque\nfrom copy import deepcopy\nfrom itertools import islice, zip_longest\nfrom types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType\nfrom typing import (\n TYPE_CHECK... | diff --git a/changes/3463-schlerp.md b/changes/3463-schlerp.md
new file mode 100644
index 00000000000..bb1fb75d3e4
--- /dev/null
+++ b/changes/3463-schlerp.md
@@ -0,0 +1 @@
+created new function `to_lower_camel()` for "non pascal case" camel case.
diff --git a/docs/usage/model_config.md b/docs/usage/model_config.md
index b6c15e06c1c..8f05fa31566 100644
--- a/docs/usage/model_config.md
+++ b/docs/usage/model_config.md
@@ -143,7 +143,7 @@ _(This script is complete, it should run "as is")_
Here camel case refers to ["upper camel case"](https://en.wikipedia.org/wiki/Camel_case) aka pascal case
e.g. `CamelCase`. If you'd like instead to use lower camel case e.g. `camelCase`,
-it should be trivial to modify the `to_camel` function above.
+instead use the `to_lower_camel` function.
## Alias Precedence
diff --git a/pydantic/utils.py b/pydantic/utils.py
index 31e74771387..62ec3fede18 100644
--- a/pydantic/utils.py
+++ b/pydantic/utils.py
@@ -303,6 +303,13 @@ def to_camel(string: str) -> str:
return ''.join(word.capitalize() for word in string.split('_'))
+def to_lower_camel(string: str) -> str:
+ if len(string) >= 1:
+ pascal_string = to_camel(string)
+ return pascal_string[0].lower() + pascal_string[1:]
+ return string.lower()
+
+
T = TypeVar('T')
diff --git a/tests/test_utils.py b/tests/test_utils.py
index d7eaa74c697..eb7caa95fdb 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -37,6 +37,7 @@
lenient_issubclass,
path_type,
smart_deepcopy,
+ to_lower_camel,
truncate,
unique_list,
)
@@ -528,6 +529,18 @@ def test_undefined_pickle():
assert undefined2 is Undefined
+def test_on_lower_camel_zero_length():
+ assert to_lower_camel('') == ''
+
+
+def test_on_lower_camel_one_length():
+ assert to_lower_camel('a') == 'a'
+
+
+def test_on_lower_camel_many_length():
+ assert to_lower_camel('i_like_turtles') == 'iLikeTurtles'
+
+
def test_limited_dict():
d = LimitedDict(10)
d[1] = '1'
|
pyodide__pyodide-4554 | `OSError: [Errno 9] Bad file descriptor` when trying to load `.npy` files, works with `.npz` file format
## 🐛 Bug
NumPy is unable to load arrays from `.npy` binaries, but it can read from compressed `.npz` archives.
### To Reproduce
I noticed this error when compiling PyWavelets (`pywt`) from source via the Emscripten toolchain.
In an activated virtual environment created by Pyodide, run the following:
```bash
git clone https://github.com/PyWavelets/pywt.git
pip install .
```
and then
```python
import pywt
import numpy as np
aero = pywt.data.aero()
ref = np.array([[178, 178, 179],
[170, 173, 171],
[185, 174, 171]])
np.testing.assert_allclose(aero[:3, :3], ref)
```
should fail. However, [after converting](https://github.com/PyWavelets/pywt/pull/701/files#diff-86b5b5c7cbe8cc8368f6991c914b7263019507351ce567543cbf2b627b91aa57) these `.npy` files to `.npz`, NumPy can safely load the arrays from the files as requested.
Here is an example of conversion from `.npy` to `.npz`:
```python
import numpy as np
ecg = np.load("pywt/data/ecg.npy")
np.savez(file="ecg.npz", data=ecg)
```
after which `ecg.npz` can be loaded as follows:
```python
import numpy as np
loaded = np.load("ecg.npz")
print(loaded["data"])
```
### Expected behavior
The Pyodide environment should be able to load the `.npy` file format stored in a directory, but [fails with multiple `OSError`s](https://github.com/agriyakhetarpal/pywt/actions/runs/7993252511/job/21828629911), possibly due to the lack of a server for filesystem access as the Pyodide documentation mentions – but this doesn't explain why `.npz` files work?
The expected behaviour should be that all file formats work.
### Environment
- Pyodide Version<!-- (e.g. 1.8.1) -->: `pyodide-build` version 0.25.0
- Browser version<!-- (e.g. Chrome 95.0.4638.54) -->: N/A
- Any other relevant information:
<!-- If you are building Pyodide by yourself, please also include these information: -->
<!--
- Commit hash of Pyodide git repository:
- Build environment<!--(e.g. Ubuntu 18.04, pyodide/pyodide-env:19 docker)- ->:
-->
### Additional context
xref: https://github.com/PyWavelets/pywt/pull/701
| [
{
"content": "\"\"\"\nVarious common utilities for testing.\n\"\"\"\n\nimport contextlib\nimport os\nimport pathlib\nimport re\nimport sys\nfrom collections.abc import Sequence\n\nimport pytest\n\nROOT_PATH = pathlib.Path(__file__).parents[0].resolve()\nDIST_PATH = ROOT_PATH / \"dist\"\n\nsys.path.append(str(RO... | [
{
"content": "\"\"\"\nVarious common utilities for testing.\n\"\"\"\n\nimport contextlib\nimport os\nimport pathlib\nimport re\nimport sys\nfrom collections.abc import Sequence\n\nimport pytest\n\nROOT_PATH = pathlib.Path(__file__).parents[0].resolve()\nDIST_PATH = ROOT_PATH / \"dist\"\n\nsys.path.append(str(RO... | diff --git a/conftest.py b/conftest.py
index bda0bcbb4d8..fb1cb42996a 100644
--- a/conftest.py
+++ b/conftest.py
@@ -54,6 +54,9 @@
only_node = pytest.mark.xfail_browsers(
chrome="node only", firefox="node only", safari="node only"
)
+only_chrome = pytest.mark.xfail_browsers(
+ node="chrome only", firefox="chrome only", safari="chrome only"
+)
def pytest_addoption(parser):
diff --git a/docs/project/changelog.md b/docs/project/changelog.md
index 6ef873c4dec..1e760490cec 100644
--- a/docs/project/changelog.md
+++ b/docs/project/changelog.md
@@ -45,6 +45,10 @@ myst:
- {{ Enhancement }} The `build/post` script now runs under the directory
where the built wheel is unpacked.
+ {pr}`4481`
+
+- {{ Fix }} `dup` now works correctly in the Node filesystem.
+ {pr}`4554`
### Packages
diff --git a/emsdk/patches/0001-Fix-dup-in-nodefs-by-refcounting-nodefs-file-descrip.patch b/emsdk/patches/0001-Fix-dup-in-nodefs-by-refcounting-nodefs-file-descrip.patch
new file mode 100644
index 00000000000..ebef6f3e2bb
--- /dev/null
+++ b/emsdk/patches/0001-Fix-dup-in-nodefs-by-refcounting-nodefs-file-descrip.patch
@@ -0,0 +1,166 @@
+From 135baa3d4cc211c0145d2e1df116e39f60df4f91 Mon Sep 17 00:00:00 2001
+From: Hood Chatham <roberthoodchatham@gmail.com>
+Date: Thu, 22 Feb 2024 21:47:13 -0800
+Subject: [PATCH] Fix dup in nodefs by refcounting nodefs file descriptors
+ (#21399)
+
+---
+ src/library_fs.js | 5 +++++
+ src/library_nodefs.js | 6 +++++-
+ src/library_syscall.js | 6 +++---
+ test/fs/test_nodefs_dup.c | 45 +++++++++++++++++++++++++++++++++++++++
+ test/test_core.py | 8 +++++++
+ 5 files changed, 66 insertions(+), 4 deletions(-)
+ create mode 100644 test/fs/test_nodefs_dup.c
+
+diff --git a/src/library_fs.js b/src/library_fs.js
+index f5d16b86c..379e65268 100644
+--- a/src/library_fs.js
++++ b/src/library_fs.js
+@@ -471,6 +471,11 @@ FS.staticInit();` +
+ closeStream(fd) {
+ FS.streams[fd] = null;
+ },
++ dupStream(origStream, fd = -1) {
++ var stream = FS.createStream(origStream, fd);
++ stream.stream_ops?.dup?.(stream);
++ return stream;
++ },
+
+ //
+ // devices
+diff --git a/src/library_nodefs.js b/src/library_nodefs.js
+index 81864ffcc..ace50458c 100644
+--- a/src/library_nodefs.js
++++ b/src/library_nodefs.js
+@@ -251,6 +251,7 @@ addToLibrary({
+ var path = NODEFS.realPath(stream.node);
+ try {
+ if (FS.isFile(stream.node.mode)) {
++ stream.shared.refcount = 1;
+ stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags));
+ }
+ } catch (e) {
+@@ -260,7 +261,7 @@ addToLibrary({
+ },
+ close(stream) {
+ try {
+- if (FS.isFile(stream.node.mode) && stream.nfd) {
++ if (FS.isFile(stream.node.mode) && stream.nfd && --stream.shared.refcount === 0) {
+ fs.closeSync(stream.nfd);
+ }
+ } catch (e) {
+@@ -268,6 +269,9 @@ addToLibrary({
+ throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
+ }
+ },
++ dup(stream) {
++ stream.shared.refcount++;
++ },
+ read(stream, buffer, offset, length, position) {
+ // Node.js < 6 compatibility: node errors on 0 length reads
+ if (length === 0) return 0;
+diff --git a/src/library_syscall.js b/src/library_syscall.js
+index b078bd71c..69ea6f8b2 100644
+--- a/src/library_syscall.js
++++ b/src/library_syscall.js
+@@ -183,7 +183,7 @@ var SyscallsLibrary = {
+ },
+ __syscall_dup: (fd) => {
+ var old = SYSCALLS.getStreamFromFD(fd);
+- return FS.createStream(old).fd;
++ return FS.dupStream(old).fd;
+ },
+ __syscall_pipe__deps: ['$PIPEFS'],
+ __syscall_pipe: (fdPtr) => {
+@@ -760,7 +760,7 @@ var SyscallsLibrary = {
+ arg++;
+ }
+ var newStream;
+- newStream = FS.createStream(stream, arg);
++ newStream = FS.dupStream(stream, arg);
+ return newStream.fd;
+ }
+ case {{{ cDefs.F_GETFD }}}:
+@@ -1007,7 +1007,7 @@ var SyscallsLibrary = {
+ if (old.fd === newfd) return -{{{ cDefs.EINVAL }}};
+ var existing = FS.getStream(newfd);
+ if (existing) FS.close(existing);
+- return FS.createStream(old, newfd).fd;
++ return FS.dupStream(old, newfd).fd;
+ },
+ };
+
+diff --git a/test/fs/test_nodefs_dup.c b/test/fs/test_nodefs_dup.c
+new file mode 100644
+index 000000000..abf34935b
+--- /dev/null
++++ b/test/fs/test_nodefs_dup.c
+@@ -0,0 +1,45 @@
++/*
++ * Copyright 2018 The Emscripten Authors. All rights reserved.
++ * Emscripten is available under two separate licenses, the MIT license and the
++ * University of Illinois/NCSA Open Source License. Both these licenses can be
++ * found in the LICENSE file.
++ */
++
++#include <assert.h>
++#include <emscripten.h>
++#include <fcntl.h>
++#include <stdio.h>
++#include <unistd.h>
++
++#ifdef NODERAWFS
++#define CWD ""
++#else
++#define CWD "/working/"
++#endif
++
++int main(void)
++{
++ EM_ASM(
++#ifdef NODERAWFS
++ FS.close(FS.open('test.txt', 'w'));
++#else
++ FS.mkdir('/working');
++ FS.mount(NODEFS, {root: '.'}, '/working');
++ FS.close(FS.open('/working/test.txt', 'w'));
++#endif
++ );
++ int fd1 = open(CWD "test.txt", O_WRONLY);
++ int fd2 = dup(fd1);
++ int fd3 = fcntl(fd1, F_DUPFD_CLOEXEC, 0);
++
++ assert(fd1 == 3);
++ assert(fd2 == 4);
++ assert(fd3 == 5);
++ assert(close(fd1) == 0);
++ assert(write(fd2, "abcdef", 6) == 6);
++ assert(close(fd2) == 0);
++ assert(write(fd3, "ghijkl", 6) == 6);
++ assert(close(fd3) == 0);
++ printf("success\n");
++ return 0;
++}
+diff --git a/test/test_core.py b/test/test_core.py
+index 3f21eb5ef..f304f1366 100644
+--- a/test/test_core.py
++++ b/test/test_core.py
+@@ -5745,6 +5745,14 @@ Module = {
+ self.emcc_args += ['-lnodefs.js']
+ self.do_runf('fs/test_nodefs_cloexec.c', 'success')
+
++ @also_with_noderawfs
++ @requires_node
++ def test_fs_nodefs_dup(self):
++ if self.get_setting('WASMFS'):
++ self.set_setting('FORCE_FILESYSTEM')
++ self.emcc_args += ['-lnodefs.js']
++ self.do_runf('fs/test_nodefs_dup.c', 'success')
++
+ @requires_node
+ def test_fs_nodefs_home(self):
+ self.set_setting('FORCE_FILESYSTEM')
+--
+2.34.1
+
diff --git a/src/tests/test_filesystem.py b/src/tests/test_filesystem.py
index 036d778a16e..a0decd0ad0c 100644
--- a/src/tests/test_filesystem.py
+++ b/src/tests/test_filesystem.py
@@ -4,6 +4,9 @@
"""
import pytest
+from pytest_pyodide import run_in_pyodide
+
+from conftest import only_chrome
@pytest.mark.skip_refcount_check
@@ -22,7 +25,7 @@ def test_idbfs_persist_code(selenium_standalone):
f"""
let mountDir = '{mount_dir}';
pyodide.FS.mkdir(mountDir);
- pyodide.FS.mount(pyodide.FS.filesystems.{fstype}, {{root : "."}}, "{mount_dir}");
+ pyodide.FS.mount(pyodide.FS.filesystems.{fstype}, {{root : "."}}, mountDir);
"""
)
# create file in mount
@@ -109,9 +112,7 @@ def test_idbfs_persist_code(selenium_standalone):
@pytest.mark.requires_dynamic_linking
-@pytest.mark.xfail_browsers(
- node="Not available", firefox="Not available", safari="Not available"
-)
+@only_chrome
def test_nativefs_dir(request, selenium_standalone):
# Note: Using *real* native file system requires
# user interaction so it is not available in headless mode.
@@ -254,3 +255,78 @@ def test_nativefs_dir(request, selenium_standalone):
pyodide.FS.unmount("/mnt/nativefs");
"""
)
+
+
+@pytest.fixture
+def browser(selenium):
+ return selenium.browser
+
+
+@pytest.fixture
+def runner(request):
+ return request.config.option.runner
+
+
+@run_in_pyodide
+def test_fs_dup(selenium, browser):
+ from os import close, dup
+ from pathlib import Path
+
+ from pyodide.code import run_js
+
+ if browser == "node":
+ fstype = "NODEFS"
+ else:
+ fstype = "IDBFS"
+
+ mount_dir = Path("/mount_test")
+ mount_dir.mkdir(exist_ok=True)
+ run_js(
+ """
+ (fstype, mountDir) =>
+ pyodide.FS.mount(pyodide.FS.filesystems[fstype], {root : "."}, mountDir);
+ """
+ )(fstype, str(mount_dir))
+
+ file = open("/mount_test/a.txt", "w")
+ fd2 = dup(file.fileno())
+ close(fd2)
+ file.write("abcd")
+ file.close()
+
+
+@pytest.mark.requires_dynamic_linking
+@only_chrome
+@run_in_pyodide
+async def test_nativefs_dup(selenium, runner):
+ from os import close, dup
+
+ import pytest
+
+ from pyodide.code import run_js
+
+ # Note: Using *real* native file system requires
+ # user interaction so it is not available in headless mode.
+ # So in this test we use OPFS (Origin Private File System)
+ # which is part of File System Access API but uses indexDB as a backend.
+
+ if runner == "playwright":
+ pytest.xfail("Playwright doesn't support file system access APIs")
+
+ await run_js(
+ """
+ async () => {
+ root = await navigator.storage.getDirectory();
+ testFileHandle = await root.getFileHandle('test_read', { create: true });
+ writable = await testFileHandle.createWritable();
+ await writable.write("hello_read");
+ await writable.close();
+ await pyodide.mountNativeFS("/mnt/nativefs", root);
+ }
+ """
+ )()
+ file = open("/mnt/nativefs/test_read")
+ fd2 = dup(file.fileno())
+ close(fd2)
+ assert file.read() == "hello_read"
+ file.close()
|
mozilla__bugbug-331 | Figure out what to do with http_service on CI
We have two options:
- build the http_service with fake models and don't push it on CI. Build it with real models and push it after training;
- build the http_service without models and let it download models at runtime.
| [
{
"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 logging\nimport os\nimport sys\n\nfrom bugbug.models.component... | [
{
"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 logging\nimport os\nimport sys\n\nfrom bugbug.models.component... | diff --git a/.taskcluster.yml b/.taskcluster.yml
index 8eede7e15a..6caaaefb5a 100644
--- a/.taskcluster.yml
+++ b/.taskcluster.yml
@@ -153,14 +153,14 @@ tasks:
capabilities:
privileged: true
maxRunTime: 10800
- image: mozilla/taskboot:0.1.0
+ image: mozilla/taskboot:0.1.1
command:
- "/bin/sh"
- "-lcxe"
- "git clone ${repository} /code &&
cd /code &&
git checkout ${head_rev} &&
- taskboot --cache /cache --target /code build-compose --registry=registry.hub.docker.com --write /images"
+ taskboot --cache /cache --target /code build-compose --registry=registry.hub.docker.com --write /images --build-arg CHECK_MODELS=0"
artifacts:
public/bugbug:
expires: {$fromNow: '2 weeks'}
@@ -229,12 +229,13 @@ tasks:
taskclusterProxy:
true
maxRunTime: 3600
- image: mozilla/taskboot:0.1.0
+ image: mozilla/taskboot:0.1.1
env:
TASKCLUSTER_SECRET: project/relman/bugbug/deploy
command:
- taskboot
- push-artifact
+ - --exclude-filter *http-service*
routes:
- project.relman.bugbug.deploy_ending
metadata:
@@ -260,7 +261,7 @@ tasks:
taskclusterProxy:
true
maxRunTime: 3600
- image: mozilla/taskboot:0.1.0
+ image: mozilla/taskboot:0.1.1
env:
GIT_REPOSITORY: ${repository}
GIT_REVISION: ${head_rev}
diff --git a/docker-compose.yml b/docker-compose.yml
index 7e320e9f9b..e7582f5542 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -56,11 +56,17 @@ services:
dockerfile: infra/dockerfile.train_tracking
image: mozilla/bugbug-train-tracking
- bugbug-http-service-base:
+ bugbug-http-service:
build:
context: http_service
- dockerfile: Dockerfile.base
- image: mozilla/bugbug-http-service-base
+ image: mozilla/bugbug-http-service
+ environment:
+ - BUGBUG_BUGZILLA_TOKEN
+ ports:
+ - target: 8000
+ published: 8000
+ protocol: tcp
+ mode: host
bugbug-spawn-data-pipeline:
build:
diff --git a/http_service/Dockerfile b/http_service/Dockerfile
index 565fb75a18..f050d8cbb3 100644
--- a/http_service/Dockerfile
+++ b/http_service/Dockerfile
@@ -1,10 +1,21 @@
-FROM mozilla/bugbug-http-service-base:latest
+FROM mozilla/bugbug-base:latest
+
+RUN env
+
+COPY requirements.txt /code/bugbug_http_service/
+
+RUN pip install -r /code/bugbug_http_service/requirements.txt
+
+COPY . /code/bugbug_http_service/
# Load the models
WORKDIR /code/
COPY ./models /code/models
+ARG CHECK_MODELS
+ENV CHECK_MODELS="${CHECK_MODELS}"
+
RUN python /code/bugbug_http_service/check_models.py
CMD ["gunicorn", "-b", "0.0.0.0:8000", "bugbug_http_service.app", "--preload", "--timeout", "30", "-w", "3"]
diff --git a/http_service/Dockerfile.base b/http_service/Dockerfile.base
deleted file mode 100644
index 78906e7695..0000000000
--- a/http_service/Dockerfile.base
+++ /dev/null
@@ -1,7 +0,0 @@
-FROM mozilla/bugbug-base:latest
-
-COPY requirements.txt /code/bugbug_http_service/
-
-RUN pip install -r /code/bugbug_http_service/requirements.txt
-
-COPY . /code/bugbug_http_service/
diff --git a/http_service/check_models.py b/http_service/check_models.py
index 08fa46ff04..e838b2c80f 100644
--- a/http_service/check_models.py
+++ b/http_service/check_models.py
@@ -36,6 +36,13 @@ def check_models():
if __name__ == "__main__":
+
+ should_check_models = os.environ.get("CHECK_MODELS", "1")
+
+ if should_check_models == "0":
+ print("Skipping checking models as instructed by env var $CHECK_MODELS")
+ sys.exit(0)
+
try:
check_models()
except Exception:
diff --git a/http_service/docker-compose.yml b/http_service/docker-compose.yml
deleted file mode 100644
index 56bd616694..0000000000
--- a/http_service/docker-compose.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-version: '3.2'
-services:
- bugbug-http-service:
- build: .
- image: mozilla/bugbug-http-service
- environment:
- - BUGBUG_BUGZILLA_TOKEN
- ports:
- - target: 8000
- published: 8000
- protocol: tcp
- mode: host
\ No newline at end of file
diff --git a/infra/data-pipeline.yml b/infra/data-pipeline.yml
index b22c639ab7..93be2726f7 100644
--- a/infra/data-pipeline.yml
+++ b/infra/data-pipeline.yml
@@ -178,7 +178,7 @@ tasks:
capabilities:
privileged: true
maxRunTime: 3600
- image: mozilla/taskboot:0.1.0
+ image: mozilla/taskboot:0.1.1
command:
- "/bin/sh"
- "-lcxe"
@@ -218,7 +218,7 @@ tasks:
taskclusterProxy:
true
maxRunTime: 3600
- image: mozilla/taskboot:0.1.0
+ image: mozilla/taskboot:0.1.1
env:
TASKCLUSTER_SECRET: project/relman/bugbug/deploy
command:
|
unionai-oss__pandera-1591 | Error Importing Pandera with Polars extra
**Describe the bug**
I get an error when importing pandera after installing the latest 0.19.0b2 version with the polars extra in a clean environment. I can import it successfully if I install without the polars extra.
- [x] I have checked that this issue has not already been reported.
- [x] I have confirmed this bug exists on the latest version of pandera.
- [ ] (optional) I have confirmed this bug exists on the main branch of pandera.
#### Code Sample, a copy-pastable example
I installed pandera 0.19.0b2 in a clean virtual environment using `pip install pandera[polars]==0.19.0b2` and attempted to import pandera:
```python
import pandera as pa
```
I got the following error message:
```
>>> import pandera as pa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".venv/lib/python3.11/site-packages/pandera/__init__.py", line 6, in <module>
from pandera import errors, external_config, typing
File ".venv/lib/python3.11/site-packages/pandera/external_config.py", line 23, in <module>
import pyspark.pandas
ModuleNotFoundError: No module named 'pyspark'
```
#### Versions:
- Pandera: 0.19.0b2
- Python: 3.11.7
- Ubuntu: 22.04
| [
{
"content": "\"\"\"Configuration for external packages.\"\"\"\n\nimport os\n\nis_spark_local_ip_dirty = False\nis_pyarrow_ignore_timezone_dirty = False\n\ntry:\n # try importing pyspark to see if it exists. This is important because the\n # pandera.typing module defines a Series type that inherits from\n... | [
{
"content": "\"\"\"Configuration for external packages.\"\"\"\n\nimport os\n\nis_spark_local_ip_dirty = False\nis_pyarrow_ignore_timezone_dirty = False\n\ntry:\n # try importing pyspark to see if it exists. This is important because the\n # pandera.typing module defines a Series type that inherits from\n... | diff --git a/pandera/external_config.py b/pandera/external_config.py
index bd81a8d39..0e076e70e 100644
--- a/pandera/external_config.py
+++ b/pandera/external_config.py
@@ -21,6 +21,8 @@
os.environ["PYARROW_IGNORE_TIMEZONE"] = "1"
import pyspark.pandas
+except (ImportError, ModuleNotFoundError):
+ pass
finally:
if is_spark_local_ip_dirty:
os.environ.pop("SPARK_LOCAL_IP")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.